code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __A ( unittest.TestCase ): def __init__(self : List[str] , __a : Union[str, Any] , __a : List[str]=13 , __a : List[Any]=7 , __a : Union[str, Any]=True , __a : Any=True , __a : List[Any]=True , __a : str=True , __a : List[Any]=99 , __a : Any=32 , __a : Tuple=5 , __a : Union[str, Any]=4 , __a : List[str]=37 , __a : Tuple="gelu" , __a : int=0.1 , __a : str=0.1 , __a : List[Any]=512 , __a : Optional[int]=16 , __a : Tuple=2 , __a : Any=0.02 , __a : Union[str, Any]=4 , ): UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = seq_length UpperCAmelCase_ = is_training UpperCAmelCase_ = use_attention_mask UpperCAmelCase_ = use_token_type_ids UpperCAmelCase_ = use_labels UpperCAmelCase_ = vocab_size UpperCAmelCase_ = hidden_size UpperCAmelCase_ = num_hidden_layers UpperCAmelCase_ = num_attention_heads UpperCAmelCase_ = intermediate_size UpperCAmelCase_ = hidden_act UpperCAmelCase_ = hidden_dropout_prob UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = max_position_embeddings UpperCAmelCase_ = type_vocab_size UpperCAmelCase_ = type_sequence_label_size UpperCAmelCase_ = initializer_range UpperCAmelCase_ = num_choices def _lowercase (self : int ): UpperCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ = None if self.use_attention_mask: UpperCAmelCase_ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase_ = None if self.use_token_type_ids: UpperCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase_ = 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 , is_decoder=__a , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def _lowercase (self : List[Any] ): UpperCAmelCase_ = self.prepare_config_and_inputs() UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = config_and_inputs UpperCAmelCase_ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict @require_flax class __A ( UpperCamelCase__ , unittest.TestCase ): a__ : Dict = True a__ : Dict = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _lowercase (self : Dict ): UpperCAmelCase_ = FlaxRoFormerModelTester(self ) @slow def _lowercase (self : Optional[Any] ): for model_class_name in self.all_model_classes: UpperCAmelCase_ = model_class_name.from_pretrained("junnyu/roformer_chinese_small" , from_pt=__a ) UpperCAmelCase_ = model(np.ones((1, 1) ) ) self.assertIsNotNone(__a ) @require_flax class __A ( unittest.TestCase ): @slow def _lowercase (self : List[Any] ): UpperCAmelCase_ = FlaxRoFormerForMaskedLM.from_pretrained("junnyu/roformer_chinese_base" ) UpperCAmelCase_ = jnp.array([[0, 1, 2, 3, 4, 5]] ) UpperCAmelCase_ = model(__a )[0] UpperCAmelCase_ = 50000 UpperCAmelCase_ = (1, 6, vocab_size) self.assertEqual(output.shape , __a ) UpperCAmelCase_ = jnp.array( [[[-0.12_05, -1.02_65, 0.29_22], [-1.51_34, 0.19_74, 0.15_19], [-5.01_35, -3.90_03, -0.84_04]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , __a , atol=1E-4 ) )
1
"""simple docstring""" import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) __SCREAMING_SNAKE_CASE : List[str] = logging.getLogger(__name__) __SCREAMING_SNAKE_CASE : str = tf.data.AUTOTUNE def _a ( ) -> List[str]: snake_case_ = argparse.ArgumentParser(description="""Train a masked language model on TPU.""" ) parser.add_argument( """--pretrained_model_config""" , type=_SCREAMING_SNAKE_CASE , default="""roberta-base""" , help="""The model config to use. Note that we don't copy the model's weights, only the config!""" , ) parser.add_argument( """--tokenizer""" , type=_SCREAMING_SNAKE_CASE , default="""unigram-tokenizer-wikitext""" , help="""The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model's vocab size.""" , ) parser.add_argument( """--per_replica_batch_size""" , type=_SCREAMING_SNAKE_CASE , default=8 , help="""Batch size per TPU core.""" , ) parser.add_argument( """--no_tpu""" , action="""store_true""" , help="""If set, run on CPU and don't try to initialize a TPU. Useful for debugging on non-TPU instances.""" , ) parser.add_argument( """--tpu_name""" , type=_SCREAMING_SNAKE_CASE , help="""Name of TPU resource to initialize. Should be blank on Colab, and 'local' on TPU VMs.""" , default="""local""" , ) parser.add_argument( """--tpu_zone""" , type=_SCREAMING_SNAKE_CASE , help="""Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes.""" , ) parser.add_argument( """--gcp_project""" , type=_SCREAMING_SNAKE_CASE , help="""Google cloud project name. Only used for non-Colab TPU nodes.""" ) parser.add_argument( """--bfloat16""" , action="""store_true""" , help="""Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU.""" , ) parser.add_argument( """--train_dataset""" , type=_SCREAMING_SNAKE_CASE , help="""Path to training dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--shuffle_buffer_size""" , type=_SCREAMING_SNAKE_CASE , default=2**18 , help="""Size of the shuffle buffer (in samples)""" , ) parser.add_argument( """--eval_dataset""" , type=_SCREAMING_SNAKE_CASE , help="""Path to evaluation dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--num_epochs""" , type=_SCREAMING_SNAKE_CASE , default=1 , help="""Number of epochs to train for.""" , ) parser.add_argument( """--learning_rate""" , type=_SCREAMING_SNAKE_CASE , default=1E-4 , help="""Learning rate to use for training.""" , ) parser.add_argument( """--weight_decay_rate""" , type=_SCREAMING_SNAKE_CASE , default=1E-3 , help="""Weight decay rate to use for training.""" , ) parser.add_argument( """--max_length""" , type=_SCREAMING_SNAKE_CASE , default=512 , help="""Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py""" , ) parser.add_argument( """--mlm_probability""" , type=_SCREAMING_SNAKE_CASE , default=0.15 , help="""Fraction of tokens to mask during training.""" , ) parser.add_argument("""--output_dir""" , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help="""Path to save model checkpoints to.""" ) parser.add_argument("""--hub_model_id""" , type=_SCREAMING_SNAKE_CASE , help="""Model ID to upload to on the Hugging Face Hub.""" ) snake_case_ = parser.parse_args() return args def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: try: if args.tpu_name: snake_case_ = tf.distribute.cluster_resolver.TPUClusterResolver( args.tpu_name , zone=args.tpu_zone , project=args.gcp_project ) else: snake_case_ = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: raise RuntimeError( """Couldn't connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or """ """--gcp_project. When running on a TPU VM, use --tpu_name local.""" ) tf.config.experimental_connect_to_cluster(_SCREAMING_SNAKE_CASE ) tf.tpu.experimental.initialize_tpu_system(_SCREAMING_SNAKE_CASE ) return tpu def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = 0 for file in file_list: snake_case_ = file.split("""/""" )[-1] snake_case_ = re.search(r"""-\d+-(\d+)\.tfrecord""" , _SCREAMING_SNAKE_CASE ).group(1 ) snake_case_ = int(_SCREAMING_SNAKE_CASE ) num_samples += sample_count return num_samples def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Union[str, Any]: snake_case_ = count_samples(_SCREAMING_SNAKE_CASE ) snake_case_ = tf.data.Dataset.from_tensor_slices(_SCREAMING_SNAKE_CASE ) if shuffle: snake_case_ = dataset.shuffle(len(_SCREAMING_SNAKE_CASE ) ) snake_case_ = tf.data.TFRecordDataset(_SCREAMING_SNAKE_CASE , num_parallel_reads=_SCREAMING_SNAKE_CASE ) # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here snake_case_ = dataset.apply(tf.data.experimental.assert_cardinality(_SCREAMING_SNAKE_CASE ) ) snake_case_ = dataset.map(_SCREAMING_SNAKE_CASE , num_parallel_calls=_SCREAMING_SNAKE_CASE ) if shuffle: assert shuffle_buffer_size is not None snake_case_ = dataset.shuffle(args.shuffle_buffer_size ) snake_case_ = dataset.batch(_SCREAMING_SNAKE_CASE , drop_remainder=_SCREAMING_SNAKE_CASE ) snake_case_ = dataset.map(_SCREAMING_SNAKE_CASE , num_parallel_calls=_SCREAMING_SNAKE_CASE ) snake_case_ = dataset.prefetch(_SCREAMING_SNAKE_CASE ) return dataset def _a ( _SCREAMING_SNAKE_CASE ) -> List[Any]: if not args.no_tpu: snake_case_ = initialize_tpu(_SCREAMING_SNAKE_CASE ) snake_case_ = tf.distribute.TPUStrategy(_SCREAMING_SNAKE_CASE ) else: snake_case_ = tf.distribute.OneDeviceStrategy(device="""/gpu:0""" ) if args.bfloataa: tf.keras.mixed_precision.set_global_policy("""mixed_bfloat16""" ) snake_case_ = AutoTokenizer.from_pretrained(args.tokenizer ) snake_case_ = AutoConfig.from_pretrained(args.pretrained_model_config ) snake_case_ = tokenizer.vocab_size snake_case_ = tf.io.gfile.glob(os.path.join(args.train_dataset , """*.tfrecord""" ) ) if not training_records: raise ValueError(f"""No .tfrecord files found in {args.train_dataset}.""" ) snake_case_ = tf.io.gfile.glob(os.path.join(args.eval_dataset , """*.tfrecord""" ) ) if not eval_records: raise ValueError(f"""No .tfrecord files found in {args.eval_dataset}.""" ) snake_case_ = count_samples(_SCREAMING_SNAKE_CASE ) snake_case_ = num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync) snake_case_ = steps_per_epoch * args.num_epochs with strategy.scope(): snake_case_ = TFAutoModelForMaskedLM.from_config(_SCREAMING_SNAKE_CASE ) model(model.dummy_inputs ) # Pass some dummy inputs through the model to ensure all the weights are built snake_case_ , snake_case_ = create_optimizer( num_train_steps=_SCREAMING_SNAKE_CASE , num_warmup_steps=total_train_steps // 20 , init_lr=args.learning_rate , weight_decay_rate=args.weight_decay_rate , ) # Transformers models compute the right loss for their task by default when labels are passed, and will # use this for training unless you specify your own loss function in compile(). model.compile(optimizer=_SCREAMING_SNAKE_CASE , metrics=["""accuracy"""] ) def decode_fn(_SCREAMING_SNAKE_CASE ): snake_case_ = { """input_ids""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), """attention_mask""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), } return tf.io.parse_single_example(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can # use their methods in our data pipeline. snake_case_ = DataCollatorForLanguageModeling( tokenizer=_SCREAMING_SNAKE_CASE , mlm_probability=args.mlm_probability , mlm=_SCREAMING_SNAKE_CASE , return_tensors="""tf""" ) def mask_with_collator(_SCREAMING_SNAKE_CASE ): # TF really needs an isin() function snake_case_ = ( ~tf.cast(batch["""attention_mask"""] , tf.bool ) | (batch["""input_ids"""] == tokenizer.cls_token_id) | (batch["""input_ids"""] == tokenizer.sep_token_id) ) snake_case_ , snake_case_ = data_collator.tf_mask_tokens( batch["""input_ids"""] , vocab_size=len(_SCREAMING_SNAKE_CASE ) , mask_token_id=tokenizer.mask_token_id , special_tokens_mask=_SCREAMING_SNAKE_CASE , ) return batch snake_case_ = args.per_replica_batch_size * strategy.num_replicas_in_sync snake_case_ = prepare_dataset( _SCREAMING_SNAKE_CASE , decode_fn=_SCREAMING_SNAKE_CASE , mask_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , shuffle=_SCREAMING_SNAKE_CASE , shuffle_buffer_size=args.shuffle_buffer_size , ) snake_case_ = prepare_dataset( _SCREAMING_SNAKE_CASE , decode_fn=_SCREAMING_SNAKE_CASE , mask_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , shuffle=_SCREAMING_SNAKE_CASE , ) snake_case_ = [] if args.hub_model_id: callbacks.append( PushToHubCallback(output_dir=args.output_dir , hub_model_id=args.hub_model_id , tokenizer=_SCREAMING_SNAKE_CASE ) ) model.fit( _SCREAMING_SNAKE_CASE , validation_data=_SCREAMING_SNAKE_CASE , epochs=args.num_epochs , callbacks=_SCREAMING_SNAKE_CASE , ) model.save_pretrained(args.output_dir ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = parse_args() main(args)
347
0
'''simple docstring''' import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline from .continous_encoder import SpectrogramContEncoder from .notes_encoder import SpectrogramNotesEncoder lowerCamelCase : Optional[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCamelCase : Dict = 256 class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : List[Any] = ["""melgan"""] def __init__(self : Tuple , UpperCamelCase : SpectrogramNotesEncoder , UpperCamelCase : SpectrogramContEncoder , UpperCamelCase : TaFilmDecoder , UpperCamelCase : DDPMScheduler , UpperCamelCase : OnnxRuntimeModel if is_onnx_available() else Any , ): '''simple docstring''' super().__init__() # From MELGAN lowercase__ = math.log(1E-5 ) # Matches MelGAN training. lowercase__ = 4.0 # Largest value for most examples lowercase__ = 128 self.register_modules( notes_encoder=UpperCamelCase , continuous_encoder=UpperCamelCase , decoder=UpperCamelCase , scheduler=UpperCamelCase , melgan=UpperCamelCase , ) def UpperCamelCase__ (self : str , UpperCamelCase : Dict , UpperCamelCase : Tuple=(-1.0, 1.0) , UpperCamelCase : int=False ): '''simple docstring''' lowercase__ ,lowercase__ = output_range if clip: lowercase__ = torch.clip(UpperCamelCase , self.min_value , self.max_value ) # Scale to [0, 1]. lowercase__ = (features - self.min_value) / (self.max_value - self.min_value) # Scale to [min_out, max_out]. return zero_one * (max_out - min_out) + min_out def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : List[str] , UpperCamelCase : Union[str, Any]=(-1.0, 1.0) , UpperCamelCase : Dict=False ): '''simple docstring''' lowercase__ ,lowercase__ = input_range lowercase__ = torch.clip(UpperCamelCase , UpperCamelCase , UpperCamelCase ) if clip else outputs # Scale to [0, 1]. lowercase__ = (outputs - min_out) / (max_out - min_out) # Scale to [self.min_value, self.max_value]. return zero_one * (self.max_value - self.min_value) + self.min_value def UpperCamelCase__ (self : Dict , UpperCamelCase : List[Any] , UpperCamelCase : List[str] , UpperCamelCase : Union[str, Any] ): '''simple docstring''' lowercase__ = input_tokens > 0 lowercase__ ,lowercase__ = self.notes_encoder( encoder_input_tokens=UpperCamelCase , encoder_inputs_mask=UpperCamelCase ) lowercase__ ,lowercase__ = self.continuous_encoder( encoder_inputs=UpperCamelCase , encoder_inputs_mask=UpperCamelCase ) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def UpperCamelCase__ (self : Dict , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[int] , UpperCamelCase : Any ): '''simple docstring''' lowercase__ = noise_time if not torch.is_tensor(UpperCamelCase ): lowercase__ = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device ) elif torch.is_tensor(UpperCamelCase ) and len(timesteps.shape ) == 0: lowercase__ = timesteps[None].to(input_tokens.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML lowercase__ = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device ) lowercase__ = self.decoder( encodings_and_masks=UpperCamelCase , decoder_input_tokens=UpperCamelCase , decoder_noise_time=UpperCamelCase ) return logits @torch.no_grad() def __call__(self : List[Any] , UpperCamelCase : List[List[int]] , UpperCamelCase : Optional[torch.Generator] = None , UpperCamelCase : int = 100 , UpperCamelCase : bool = True , UpperCamelCase : str = "numpy" , UpperCamelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCamelCase : int = 1 , ): '''simple docstring''' if (callback_steps is None) or ( callback_steps is not None and (not isinstance(UpperCamelCase , UpperCamelCase ) or callback_steps <= 0) ): raise ValueError( f"`callback_steps` has to be a positive integer but is {callback_steps} of type" f" {type(UpperCamelCase )}." ) lowercase__ = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa ) lowercase__ = np.zeros([1, 0, self.n_dims] , np.floataa ) lowercase__ = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=UpperCamelCase , device=self.device ) for i, encoder_input_tokens in enumerate(UpperCamelCase ): if i == 0: lowercase__ = torch.from_numpy(pred_mel[:1].copy() ).to( device=self.device , dtype=self.decoder.dtype ) # The first chunk has no previous context. lowercase__ = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=UpperCamelCase , device=self.device ) else: # The full song pipeline does not feed in a context feature, so the mask # will be all 0s after the feature converter. Because we know we're # feeding in a full context chunk from the previous prediction, set it # to all 1s. lowercase__ = ones lowercase__ = self.scale_features( UpperCamelCase , output_range=[-1.0, 1.0] , clip=UpperCamelCase ) lowercase__ = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=UpperCamelCase , continuous_mask=UpperCamelCase , ) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop lowercase__ = randn_tensor( shape=encoder_continuous_inputs.shape , generator=UpperCamelCase , device=self.device , dtype=self.decoder.dtype , ) # set step values self.scheduler.set_timesteps(UpperCamelCase ) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): lowercase__ = self.decode( encodings_and_masks=UpperCamelCase , input_tokens=UpperCamelCase , noise_time=t / self.scheduler.config.num_train_timesteps , ) # Compute previous output: x_t -> x_t-1 lowercase__ = self.scheduler.step(UpperCamelCase , UpperCamelCase , UpperCamelCase , generator=UpperCamelCase ).prev_sample lowercase__ = self.scale_to_features(UpperCamelCase , input_range=[-1.0, 1.0] ) lowercase__ = mel[:1] lowercase__ = mel.cpu().float().numpy() lowercase__ = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 ) # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(UpperCamelCase , UpperCamelCase ) logger.info('''Generated segment''' , UpperCamelCase ) if output_type == "numpy" and not is_onnx_available(): raise ValueError( '''Cannot return output in \'np\' format if ONNX is not available. Make sure to have ONNX installed or set \'output_type\' to \'mel\'.''' ) elif output_type == "numpy" and self.melgan is None: raise ValueError( '''Cannot return output in \'np\' format if melgan component is not defined. Make sure to define `self.melgan` or set \'output_type\' to \'mel\'.''' ) if output_type == "numpy": lowercase__ = self.melgan(input_features=full_pred_mel.astype(np.floataa ) ) else: lowercase__ = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=UpperCamelCase )
2
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float: if density <= 0: raise ValueError("""Impossible fluid density""" ) if bulk_modulus <= 0: raise ValueError("""Impossible bulk modulus""" ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
347
0
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class A : __magic_name__ = 42 __magic_name__ = None __magic_name__ = None lowercase : Union[str, Any] = namedtuple('CoinsDistribResult', 'moves excess') def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if root is None: return 0 # Validation def count_nodes(snake_case__ ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(snake_case__ ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(snake_case__ ) != count_coins(snake_case__ ): raise ValueError('''The nodes number should be same as the number of coins''' ) # Main calculation def get_distrib(snake_case__ ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) A, A : Optional[int] = get_distrib(node.left ) A, A : List[str] = get_distrib(node.right ) A : List[Any] = 1 - left_distrib_excess A : int = 1 - right_distrib_excess A : Union[str, Any] = ( left_distrib_moves + right_distrib_moves + abs(snake_case__ ) + abs(snake_case__ ) ) A : Optional[int] = node.data - coins_to_left - coins_to_right return CoinsDistribResult(snake_case__ , snake_case__ ) return get_distrib(snake_case__ )[0] if __name__ == "__main__": import doctest doctest.testmod()
3
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if num < 0: return False snake_case_ = num snake_case_ = 0 while num > 0: snake_case_ = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
347
0
'''simple docstring''' import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def a_ ( lowerCamelCase : int = 8 ): lowerCAmelCase = ascii_letters + digits + punctuation return "".join(secrets.choice(lowerCamelCase ) for _ in range(lowerCamelCase ) ) def a_ ( lowerCamelCase : str , lowerCamelCase : int ): # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(lowerCamelCase ) lowerCAmelCase = i // 3 lowerCAmelCase = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) lowerCAmelCase = ( chars_incl + random(lowerCamelCase , quotient + remainder ) + random(lowerCamelCase , lowerCamelCase ) + random(lowerCamelCase , lowerCamelCase ) ) lowerCAmelCase = list(lowerCamelCase ) shuffle(lowerCamelCase ) return "".join(lowerCamelCase ) # random is a generalised function for letters, characters and numbers def a_ ( lowerCamelCase : str , lowerCamelCase : int ): return "".join(secrets.choice(lowerCamelCase ) for _ in range(lowerCamelCase ) ) def a_ ( lowerCamelCase : str , lowerCamelCase : Tuple ): pass # Put your code here... def a_ ( lowerCamelCase : Optional[int] , lowerCamelCase : Tuple ): pass # Put your code here... def a_ ( lowerCamelCase : int , lowerCamelCase : Dict ): pass # Put your code here... def a_ ( lowerCamelCase : str , lowerCamelCase : int = 8 ): if len(lowerCamelCase ) < min_length: # Your Password must be at least 8 characters long return False lowerCAmelCase = any(char in ascii_uppercase for char in password ) lowerCAmelCase = any(char in ascii_lowercase for char in password ) lowerCAmelCase = any(char in digits for char in password ) lowerCAmelCase = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def a_ ( ): lowerCAmelCase = int(input('Please indicate the max length of your password: ' ).strip() ) lowerCAmelCase = input( 'Please indicate the characters that must be in your password: ' ).strip() print('Password generated:' , password_generator(lowerCamelCase ) ) print( 'Alternative Password generated:' , alternative_password_generator(lowerCamelCase , lowerCamelCase ) , ) print('[If you are thinking of using this passsword, You better save it.]' ) if __name__ == "__main__": main()
4
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin __SCREAMING_SNAKE_CASE : Tuple = get_tests_dir('fixtures/test_sentencepiece_bpe_char.model') @require_sentencepiece @require_tokenizers class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Tuple = SpeechTaTokenizer __lowercase: int = False __lowercase: List[str] = True def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing snake_case_ = SpeechTaTokenizer(UpperCAmelCase_ ) snake_case_ = AddedToken("""<mask>""" , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) snake_case_ = mask_token tokenizer.add_special_tokens({"""mask_token""": mask_token} ) tokenizer.add_tokens(["""<ctc_blank>"""] ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = """this is a test""" snake_case_ = """this is a test""" return input_text, output_text def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Any=False , UpperCAmelCase_ : Tuple=20 , UpperCAmelCase_ : Dict=5 ) ->List[Any]: """simple docstring""" snake_case_ , snake_case_ = self.get_input_output_texts(UpperCAmelCase_ ) snake_case_ = tokenizer.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ ) snake_case_ = tokenizer.decode(UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ ) return text, ids def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" snake_case_ = """<pad>""" snake_case_ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_ ) , UpperCAmelCase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_ ) , UpperCAmelCase_ ) def lowerCAmelCase ( self : int ) ->str: """simple docstring""" snake_case_ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-4] , """œ""" ) self.assertEqual(vocab_keys[-2] , """<mask>""" ) self.assertEqual(vocab_keys[-1] , """<ctc_blank>""" ) self.assertEqual(len(UpperCAmelCase_ ) , 81 ) def lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = self.get_tokenizers(do_lower_case=UpperCAmelCase_ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case_ = tokenizer.vocab_size snake_case_ = len(UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) snake_case_ = ["""aaaaa bbbbbb""", """cccccccccdddddddd"""] snake_case_ = tokenizer.add_tokens(UpperCAmelCase_ ) snake_case_ = tokenizer.vocab_size snake_case_ = len(UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , 0 ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , len(UpperCAmelCase_ ) ) self.assertEqual(UpperCAmelCase_ , all_size + len(UpperCAmelCase_ ) ) snake_case_ = tokenizer.encode("""aaaaa bbbbbb low cccccccccdddddddd l""" , add_special_tokens=UpperCAmelCase_ ) self.assertGreaterEqual(len(UpperCAmelCase_ ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) snake_case_ = {"""eos_token""": """>>>>|||<||<<|<<""", """pad_token""": """<<<<<|||>|>>>>|>"""} snake_case_ = tokenizer.add_special_tokens(UpperCAmelCase_ ) snake_case_ = tokenizer.vocab_size snake_case_ = len(UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , 0 ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , len(UpperCAmelCase_ ) ) self.assertEqual(UpperCAmelCase_ , all_size_a + len(UpperCAmelCase_ ) ) snake_case_ = tokenizer.encode( """>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l""" , add_special_tokens=UpperCAmelCase_ ) self.assertGreaterEqual(len(UpperCAmelCase_ ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" pass def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" pass def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = self.get_tokenizer() snake_case_ = tokenizer.tokenize("""This is a test""" ) # fmt: off self.assertListEqual(UpperCAmelCase_ , [SPIECE_UNDERLINE, """T""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """a""", SPIECE_UNDERLINE, """t""", """e""", """s""", """t"""] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) snake_case_ = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( UpperCAmelCase_ , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """92000""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) snake_case_ = tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) # fmt: off self.assertListEqual(UpperCAmelCase_ , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on snake_case_ = tokenizer.convert_ids_to_tokens(UpperCAmelCase_ ) self.assertListEqual( UpperCAmelCase_ , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """<unk>""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) @slow def lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" snake_case_ = [ """Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides """ """general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural """ """Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained """ """models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.""", """BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly """ """conditioning on both left and right context in all layers.""", """The quick brown fox jumps over the lazy dog.""", ] # fmt: off snake_case_ = { """input_ids""": [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], """attention_mask""": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase_ , model_name="""microsoft/speecht5_asr""" , revision="""c5ef64c71905caeccde0e4462ef3f9077224c524""" , sequences=UpperCAmelCase_ , )
347
0
import os def UpperCAmelCase_ ( ) -> Union[str, Any]: """simple docstring""" _lowercase =os.path.dirname(os.path.realpath(__snake_case ) ) _lowercase =os.path.join(__snake_case , '''triangle.txt''' ) with open(__snake_case ) as f: _lowercase =f.readlines() _lowercase =[] for line in triangle: _lowercase =[] for number in line.strip().split(''' ''' ): numbers_from_line.append(int(__snake_case ) ) a.append(__snake_case ) for i in range(1 , len(__snake_case ) ): for j in range(len(a[i] ) ): _lowercase =a[i - 1][j] if j != len(a[i - 1] ) else 0 _lowercase =a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(__snake_case , __snake_case ) return max(a[-1] ) if __name__ == "__main__": print(solution())
5
"""simple docstring""" import datasets __SCREAMING_SNAKE_CASE : Tuple = '\\n@InProceedings{conneau2018xnli,\n author = "Conneau, Alexis\n and Rinott, Ruty\n and Lample, Guillaume\n and Williams, Adina\n and Bowman, Samuel R.\n and Schwenk, Holger\n and Stoyanov, Veselin",\n title = "XNLI: Evaluating Cross-lingual Sentence Representations",\n booktitle = "Proceedings of the 2018 Conference on Empirical Methods\n in Natural Language Processing",\n year = "2018",\n publisher = "Association for Computational Linguistics",\n location = "Brussels, Belgium",\n}\n' __SCREAMING_SNAKE_CASE : Dict = '\\nXNLI is a subset of a few thousand examples from MNLI which has been translated\ninto a 14 different languages (some low-ish resource). As with MNLI, the goal is\nto predict textual entailment (does sentence A imply/contradict/neither sentence\nB) and is a classification task (given two sentences, predict one of three\nlabels).\n' __SCREAMING_SNAKE_CASE : List[str] = '\nComputes XNLI score which is just simple accuracy.\nArgs:\n predictions: Predicted labels.\n references: Ground truth labels.\nReturns:\n \'accuracy\': accuracy\nExamples:\n\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> xnli_metric = datasets.load_metric("xnli")\n >>> results = xnli_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n' def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: return (preds == labels).mean() @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __A (datasets.Metric): '''simple docstring''' def lowerCAmelCase ( self : str ) ->Any: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), """references""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), } ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" , ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" return {"accuracy": simple_accuracy(UpperCAmelCase_ , UpperCAmelCase_ )}
347
0
import unittest import numpy as np from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class __A( a , unittest.TestCase ): # FIXME: add fast tests pass @nightly @require_onnxruntime @require_torch_gpu class __A( unittest.TestCase ): @property def SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def SCREAMING_SNAKE_CASE_ ( self ) -> Union[str, Any]: '''simple docstring''' __a = ort.SessionOptions() __a = False return options def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[Any]: '''simple docstring''' __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo.png''' ) __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo_mask.png''' ) __a = OnnxStableDiffusionInpaintPipeline.from_pretrained( '''runwayml/stable-diffusion-inpainting''' , revision='''onnx''' , safety_checker=_snake_case , feature_extractor=_snake_case , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_snake_case ) __a = '''A red cat sitting on a park bench''' __a = np.random.RandomState(0 ) __a = pipe( prompt=_snake_case , image=_snake_case , mask_image=_snake_case , guidance_scale=7.5 , num_inference_steps=10 , generator=_snake_case , output_type='''np''' , ) __a = output.images __a = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) __a = np.array([0.2514, 0.3007, 0.3517, 0.1790, 0.2382, 0.3167, 0.1944, 0.2273, 0.2464] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def SCREAMING_SNAKE_CASE_ ( self ) -> Tuple: '''simple docstring''' __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo.png''' ) __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo_mask.png''' ) __a = LMSDiscreteScheduler.from_pretrained( '''runwayml/stable-diffusion-inpainting''' , subfolder='''scheduler''' , revision='''onnx''' ) __a = OnnxStableDiffusionInpaintPipeline.from_pretrained( '''runwayml/stable-diffusion-inpainting''' , revision='''onnx''' , scheduler=_snake_case , safety_checker=_snake_case , feature_extractor=_snake_case , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_snake_case ) __a = '''A red cat sitting on a park bench''' __a = np.random.RandomState(0 ) __a = pipe( prompt=_snake_case , image=_snake_case , mask_image=_snake_case , guidance_scale=7.5 , num_inference_steps=20 , generator=_snake_case , output_type='''np''' , ) __a = output.images __a = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) __a = np.array([0.0086, 0.0077, 0.0083, 0.0093, 0.0107, 0.0139, 0.0094, 0.0097, 0.0125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
6
"""simple docstring""" from ..utils import DummyObject, requires_backends class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : List[str] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""sentencepiece"""] def __init__( self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Tuple ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : Any , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : List[Any] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Dict = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[str] = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : int ) ->List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Tuple , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Dict ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Union[str, Any] ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[Any] = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : Optional[Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""sentencepiece"""] def __init__( self : Optional[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : str , **UpperCAmelCase_ : int ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Optional[int] , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Tuple = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : List[Any] ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : List[str] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Tuple = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Optional[Any] ) ->str: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Optional[Any] ) ->int: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = ["""sentencepiece"""] def __init__( self : Optional[Any] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : Optional[Any] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Dict ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : List[str] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any] ) ->List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : Any , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Optional[Any] ) ->List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Dict = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Union[str, Any] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Optional[int] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = ["""sentencepiece"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : str ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""sentencepiece"""] def __init__( self : Tuple , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Optional[int] ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Dict = ["""sentencepiece"""] def __init__( self : Optional[int] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : List[str] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Optional[int] ) ->Any: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[str] = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Union[str, Any] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Optional[int] ) ->str: """simple docstring""" requires_backends(self , ["""sentencepiece"""] )
347
0
import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class A ( ctypes.Structure ): """simple docstring""" lowerCamelCase = [('size', ctypes.c_int), ('visible', ctypes.c_byte)] def _snake_case( ) -> Optional[int]: '''simple docstring''' if os.name == "nt": A__ = CursorInfo() A__ = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(SCREAMING_SNAKE_CASE__ , ctypes.byref(SCREAMING_SNAKE_CASE__ ) ) A__ = False ctypes.windll.kernelaa.SetConsoleCursorInfo(SCREAMING_SNAKE_CASE__ , ctypes.byref(SCREAMING_SNAKE_CASE__ ) ) elif os.name == "posix": sys.stdout.write('\033[?25l' ) sys.stdout.flush() def _snake_case( ) -> Optional[int]: '''simple docstring''' if os.name == "nt": A__ = CursorInfo() A__ = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(SCREAMING_SNAKE_CASE__ , ctypes.byref(SCREAMING_SNAKE_CASE__ ) ) A__ = True ctypes.windll.kernelaa.SetConsoleCursorInfo(SCREAMING_SNAKE_CASE__ , ctypes.byref(SCREAMING_SNAKE_CASE__ ) ) elif os.name == "posix": sys.stdout.write('\033[?25h' ) sys.stdout.flush() @contextmanager def _snake_case( ) -> Union[str, Any]: '''simple docstring''' try: hide_cursor() yield finally: show_cursor()
7
"""simple docstring""" import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor __SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) class __A (snake_case__): '''simple docstring''' def __init__( self : str , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int ) ->None: """simple docstring""" warnings.warn( """The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use MobileViTImageProcessor instead.""" , UpperCAmelCase_ , ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ )
347
0
from ..utils import DummyObject, requires_backends class snake_case_ ( metaclass=__A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = ["flax", "transformers"] def __init__( self : Optional[int] , *_UpperCamelCase : int , **_UpperCamelCase : Tuple ) ->Any: requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : List[str] , *_UpperCamelCase : int , **_UpperCamelCase : str ) ->Any: requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : Union[str, Any] , *_UpperCamelCase : Optional[Any] , **_UpperCamelCase : Any ) ->Dict: requires_backends(cls , ['''flax''', '''transformers'''] ) class snake_case_ ( metaclass=__A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = ["flax", "transformers"] def __init__( self : Any , *_UpperCamelCase : Optional[Any] , **_UpperCamelCase : Optional[int] ) ->Dict: requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : str , *_UpperCamelCase : List[Any] , **_UpperCamelCase : int ) ->str: requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : str , *_UpperCamelCase : List[Any] , **_UpperCamelCase : Dict ) ->Union[str, Any]: requires_backends(cls , ['''flax''', '''transformers'''] ) class snake_case_ ( metaclass=__A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = ["flax", "transformers"] def __init__( self : Union[str, Any] , *_UpperCamelCase : Dict , **_UpperCamelCase : Tuple ) ->List[str]: requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : Optional[int] , *_UpperCamelCase : str , **_UpperCamelCase : str ) ->Union[str, Any]: requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : Any , *_UpperCamelCase : Any , **_UpperCamelCase : List[str] ) ->int: requires_backends(cls , ['''flax''', '''transformers'''] ) class snake_case_ ( metaclass=__A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = ["flax", "transformers"] def __init__( self : Tuple , *_UpperCamelCase : str , **_UpperCamelCase : int ) ->Any: requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : List[Any] , *_UpperCamelCase : List[str] , **_UpperCamelCase : Union[str, Any] ) ->List[Any]: requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : Union[str, Any] , *_UpperCamelCase : str , **_UpperCamelCase : List[Any] ) ->List[Any]: requires_backends(cls , ['''flax''', '''transformers'''] )
8
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Any: snake_case_ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"""blocks.{i}.norm1.weight""", f"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """vit.embeddings.cls_token"""), ("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" snake_case_ = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) return rename_keys def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Tuple: for i in range(config.num_hidden_layers ): if base_model: snake_case_ = """""" else: snake_case_ = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case_ = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" ) snake_case_ = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict snake_case_ = in_proj_weight[ : config.hidden_size, : ] snake_case_ = in_proj_bias[: config.hidden_size] snake_case_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case_ = in_proj_weight[ -config.hidden_size :, : ] snake_case_ = in_proj_bias[-config.hidden_size :] def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: snake_case_ = dct.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = val def _a ( ) -> Any: snake_case_ = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = ViTConfig() snake_case_ = False # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size if vit_name[-5:] == "in21k": snake_case_ = True snake_case_ = int(vit_name[-12:-10] ) snake_case_ = int(vit_name[-9:-6] ) else: snake_case_ = 1_000 snake_case_ = """huggingface/label-files""" snake_case_ = """imagenet-1k-id2label.json""" snake_case_ = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) snake_case_ = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} snake_case_ = idalabel snake_case_ = {v: k for k, v in idalabel.items()} snake_case_ = int(vit_name[-6:-4] ) snake_case_ = int(vit_name[-3:] ) # size of the architecture if "deit" in vit_name: if vit_name[9:].startswith("""tiny""" ): snake_case_ = 192 snake_case_ = 768 snake_case_ = 12 snake_case_ = 3 elif vit_name[9:].startswith("""small""" ): snake_case_ = 384 snake_case_ = 1_536 snake_case_ = 12 snake_case_ = 6 else: pass else: if vit_name[4:].startswith("""small""" ): snake_case_ = 768 snake_case_ = 2_304 snake_case_ = 8 snake_case_ = 8 elif vit_name[4:].startswith("""base""" ): pass elif vit_name[4:].startswith("""large""" ): snake_case_ = 1_024 snake_case_ = 4_096 snake_case_ = 24 snake_case_ = 16 elif vit_name[4:].startswith("""huge""" ): snake_case_ = 1_280 snake_case_ = 5_120 snake_case_ = 32 snake_case_ = 16 # load original model from timm snake_case_ = timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ) timm_model.eval() # load state_dict of original model, remove and rename some keys snake_case_ = timm_model.state_dict() if base_model: remove_classification_head_(_SCREAMING_SNAKE_CASE ) snake_case_ = create_rename_keys(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for src, dest in rename_keys: rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) read_in_q_k_v(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load HuggingFace model if vit_name[-5:] == "in21k": snake_case_ = ViTModel(_SCREAMING_SNAKE_CASE ).eval() else: snake_case_ = ViTForImageClassification(_SCREAMING_SNAKE_CASE ).eval() model.load_state_dict(_SCREAMING_SNAKE_CASE ) # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor if "deit" in vit_name: snake_case_ = DeiTImageProcessor(size=config.image_size ) else: snake_case_ = ViTImageProcessor(size=config.image_size ) snake_case_ = image_processor(images=prepare_img() , return_tensors="""pt""" ) snake_case_ = encoding["""pixel_values"""] snake_case_ = model(_SCREAMING_SNAKE_CASE ) if base_model: snake_case_ = timm_model.forward_features(_SCREAMING_SNAKE_CASE ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(_SCREAMING_SNAKE_CASE , outputs.pooler_output , atol=1E-3 ) else: snake_case_ = timm_model(_SCREAMING_SNAKE_CASE ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_SCREAMING_SNAKE_CASE , outputs.logits , atol=1E-3 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(f"""Saving model {vit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--vit_name', default='vit_base_patch16_224', type=str, help='Name of the ViT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) __SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
347
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 _UpperCamelCase ( lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : List[Any] = XCLIPTextConfig() # derive patch size from model name __SCREAMING_SNAKE_CASE : Optional[int] = model_name.find('''patch''' ) __SCREAMING_SNAKE_CASE : Dict = int(model_name[start_idx + len('''patch''' ) : start_idx + len('''patch''' ) + 2] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = XCLIPVisionConfig(patch_size=lowercase__ , num_frames=lowercase__ ) if "large" in model_name: __SCREAMING_SNAKE_CASE : int = 768 __SCREAMING_SNAKE_CASE : Dict = 3072 __SCREAMING_SNAKE_CASE : List[Any] = 12 __SCREAMING_SNAKE_CASE : Any = 1024 __SCREAMING_SNAKE_CASE : Union[str, Any] = 4096 __SCREAMING_SNAKE_CASE : Union[str, Any] = 16 __SCREAMING_SNAKE_CASE : List[Any] = 24 __SCREAMING_SNAKE_CASE : Union[str, Any] = 768 __SCREAMING_SNAKE_CASE : str = 3072 if model_name == "xclip-large-patch14-16-frames": __SCREAMING_SNAKE_CASE : Any = 336 __SCREAMING_SNAKE_CASE : int = XCLIPConfig.from_text_vision_configs(lowercase__ , lowercase__ ) if "large" in model_name: __SCREAMING_SNAKE_CASE : Optional[int] = 768 return config def _UpperCamelCase ( lowercase__ ): # text encoder if name == "token_embedding.weight": __SCREAMING_SNAKE_CASE : Dict = name.replace('''token_embedding.weight''' , '''text_model.embeddings.token_embedding.weight''' ) if name == "positional_embedding": __SCREAMING_SNAKE_CASE : Optional[Any] = name.replace('''positional_embedding''' , '''text_model.embeddings.position_embedding.weight''' ) if "ln_1" in name: __SCREAMING_SNAKE_CASE : Dict = name.replace('''ln_1''' , '''layer_norm1''' ) if "ln_2" in name: __SCREAMING_SNAKE_CASE : Optional[int] = name.replace('''ln_2''' , '''layer_norm2''' ) if "c_fc" in name: __SCREAMING_SNAKE_CASE : Tuple = name.replace('''c_fc''' , '''fc1''' ) if "c_proj" in name: __SCREAMING_SNAKE_CASE : Tuple = name.replace('''c_proj''' , '''fc2''' ) if name.startswith('''transformer.resblocks''' ): __SCREAMING_SNAKE_CASE : int = name.replace('''transformer.resblocks''' , '''text_model.encoder.layers''' ) if "attn.out_proj" in name and "message" not in name: __SCREAMING_SNAKE_CASE : List[Any] = name.replace('''attn.out_proj''' , '''self_attn.out_proj''' ) if "ln_final" in name: __SCREAMING_SNAKE_CASE : List[Any] = name.replace('''ln_final''' , '''text_model.final_layer_norm''' ) # visual encoder if name == "visual.class_embedding": __SCREAMING_SNAKE_CASE : List[str] = name.replace('''visual.class_embedding''' , '''vision_model.embeddings.class_embedding''' ) if name == "visual.positional_embedding": __SCREAMING_SNAKE_CASE : str = name.replace('''visual.positional_embedding''' , '''vision_model.embeddings.position_embedding.weight''' ) if name.startswith('''visual.transformer.resblocks''' ): __SCREAMING_SNAKE_CASE : List[str] = name.replace('''visual.transformer.resblocks''' , '''vision_model.encoder.layers''' ) if "visual.conv1" in name: __SCREAMING_SNAKE_CASE : List[Any] = name.replace('''visual.conv1''' , '''vision_model.embeddings.patch_embedding''' ) if "visual.ln_pre" in name: __SCREAMING_SNAKE_CASE : Dict = name.replace('''visual.ln_pre''' , '''vision_model.pre_layernorm''' ) if "visual.ln_post" in name: __SCREAMING_SNAKE_CASE : Optional[Any] = name.replace('''visual.ln_post''' , '''vision_model.post_layernorm''' ) if "visual.proj" in name: __SCREAMING_SNAKE_CASE : str = name.replace('''visual.proj''' , '''visual_projection.weight''' ) if "text_projection" in name: __SCREAMING_SNAKE_CASE : List[str] = name.replace('''text_projection''' , '''text_projection.weight''' ) # things on top if "prompts_visual_proj" in name: __SCREAMING_SNAKE_CASE : Tuple = name.replace('''prompts_visual_proj''' , '''prompts_visual_projection''' ) if "prompts_visual_ln" in name: __SCREAMING_SNAKE_CASE : Any = name.replace('''prompts_visual_ln''' , '''prompts_visual_layernorm''' ) # mit if name == "mit.positional_embedding": __SCREAMING_SNAKE_CASE : Dict = name.replace('''positional''' , '''position''' ) if name.startswith('''mit.resblocks''' ): __SCREAMING_SNAKE_CASE : Optional[int] = name.replace('''mit.resblocks''' , '''mit.encoder.layers''' ) # prompts generator if name.startswith('''prompts_generator.norm''' ): __SCREAMING_SNAKE_CASE : List[Any] = name.replace('''prompts_generator.norm''' , '''prompts_generator.layernorm''' ) return name def _UpperCamelCase ( lowercase__ , lowercase__ ): for key in orig_state_dict.copy().keys(): __SCREAMING_SNAKE_CASE : List[str] = orig_state_dict.pop(lowercase__ ) if "attn.in_proj" in key: __SCREAMING_SNAKE_CASE : str = key.split('''.''' ) if key.startswith('''visual''' ): __SCREAMING_SNAKE_CASE : str = key_split[3] __SCREAMING_SNAKE_CASE : Union[str, Any] = config.vision_config.hidden_size if "message_attn" in key: if "weight" in key: __SCREAMING_SNAKE_CASE : int = val[ :dim, : ] __SCREAMING_SNAKE_CASE : str = val[ dim : dim * 2, : ] __SCREAMING_SNAKE_CASE : str = val[ -dim:, : ] else: __SCREAMING_SNAKE_CASE : str = val[ :dim ] __SCREAMING_SNAKE_CASE : Union[str, Any] = val[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE : Optional[int] = val[ -dim: ] else: if "weight" in key: __SCREAMING_SNAKE_CASE : Any = val[ :dim, : ] __SCREAMING_SNAKE_CASE : Optional[int] = val[ dim : dim * 2, : ] __SCREAMING_SNAKE_CASE : Optional[int] = val[ -dim:, : ] else: __SCREAMING_SNAKE_CASE : Optional[int] = val[:dim] __SCREAMING_SNAKE_CASE : Optional[int] = val[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE : Tuple = val[-dim:] elif key.startswith('''mit''' ): __SCREAMING_SNAKE_CASE : Dict = key_split[2] __SCREAMING_SNAKE_CASE : Any = config.vision_config.mit_hidden_size if "weight" in key: __SCREAMING_SNAKE_CASE : Dict = val[:dim, :] __SCREAMING_SNAKE_CASE : Union[str, Any] = val[dim : dim * 2, :] __SCREAMING_SNAKE_CASE : List[Any] = val[-dim:, :] else: __SCREAMING_SNAKE_CASE : Dict = val[:dim] __SCREAMING_SNAKE_CASE : Optional[Any] = val[dim : dim * 2] __SCREAMING_SNAKE_CASE : List[str] = val[-dim:] else: __SCREAMING_SNAKE_CASE : Optional[Any] = key_split[2] __SCREAMING_SNAKE_CASE : Optional[int] = config.text_config.hidden_size if "weight" in key: __SCREAMING_SNAKE_CASE : Dict = val[:dim, :] __SCREAMING_SNAKE_CASE : Optional[Any] = val[ dim : dim * 2, : ] __SCREAMING_SNAKE_CASE : Optional[Any] = val[-dim:, :] else: __SCREAMING_SNAKE_CASE : Tuple = val[:dim] __SCREAMING_SNAKE_CASE : Any = val[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE : Any = val[-dim:] else: __SCREAMING_SNAKE_CASE : List[str] = rename_key(lowercase__ ) if new_key_name in ["visual_projection.weight", "text_projection.weight"]: __SCREAMING_SNAKE_CASE : Any = val.T __SCREAMING_SNAKE_CASE : Dict = val return orig_state_dict def _UpperCamelCase ( lowercase__ ): if num_frames == 8: __SCREAMING_SNAKE_CASE : List[str] = '''eating_spaghetti_8_frames.npy''' elif num_frames == 16: __SCREAMING_SNAKE_CASE : str = '''eating_spaghetti.npy''' elif num_frames == 32: __SCREAMING_SNAKE_CASE : Dict = '''eating_spaghetti_32_frames.npy''' __SCREAMING_SNAKE_CASE : str = hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''' , filename=lowercase__ , repo_type='''dataset''' , ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.load(lowercase__ ) return list(lowercase__ ) def _UpperCamelCase ( lowercase__ , lowercase__=None , lowercase__=False ): __SCREAMING_SNAKE_CASE : 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''', } __SCREAMING_SNAKE_CASE : Optional[Any] = model_to_url[model_name] __SCREAMING_SNAKE_CASE : int = 8 if "16-frames" in model_name: __SCREAMING_SNAKE_CASE : Tuple = 16 elif "shot" in model_name: __SCREAMING_SNAKE_CASE : List[Any] = 32 __SCREAMING_SNAKE_CASE : Any = get_xclip_config(lowercase__ , lowercase__ ) __SCREAMING_SNAKE_CASE : str = XCLIPModel(lowercase__ ) model.eval() if "drive" in checkpoint_url: __SCREAMING_SNAKE_CASE : Optional[int] = '''pytorch_model.bin''' gdown.cached_download(lowercase__ , lowercase__ , quiet=lowercase__ ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.load(lowercase__ , map_location='''cpu''' )['''model'''] else: __SCREAMING_SNAKE_CASE : List[str] = torch.hub.load_state_dict_from_url(lowercase__ )['''model'''] __SCREAMING_SNAKE_CASE : str = convert_state_dict(lowercase__ , lowercase__ ) __SCREAMING_SNAKE_CASE : Dict = XCLIPModel(lowercase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = model.load_state_dict(lowercase__ , strict=lowercase__ ) assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"] model.eval() __SCREAMING_SNAKE_CASE : Tuple = 336 if model_name == '''xclip-large-patch14-16-frames''' else 224 __SCREAMING_SNAKE_CASE : Dict = VideoMAEImageProcessor(size=lowercase__ ) __SCREAMING_SNAKE_CASE : List[Any] = CLIPTokenizer.from_pretrained('''openai/clip-vit-base-patch32''' ) __SCREAMING_SNAKE_CASE : int = CLIPTokenizerFast.from_pretrained('''openai/clip-vit-base-patch32''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = XCLIPProcessor(image_processor=lowercase__ , tokenizer=lowercase__ ) __SCREAMING_SNAKE_CASE : Dict = prepare_video(lowercase__ ) __SCREAMING_SNAKE_CASE : int = processor( text=['''playing sports''', '''eating spaghetti''', '''go shopping'''] , videos=lowercase__ , return_tensors='''pt''' , padding=lowercase__ ) print('''Shape of pixel values:''' , inputs.pixel_values.shape ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Optional[Any] = model(**lowercase__ ) # Verify outputs __SCREAMING_SNAKE_CASE : Tuple = outputs.logits_per_video __SCREAMING_SNAKE_CASE : Optional[int] = logits_per_video.softmax(dim=1 ) print('''Probs:''' , lowercase__ ) # kinetics-400 if model_name == "xclip-base-patch32": __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[0.0019, 0.9951, 0.0030]] ) elif model_name == "xclip-base-patch32-16-frames": __SCREAMING_SNAKE_CASE : Dict = torch.tensor([[7.09_99e-04, 9.98_83e-01, 4.55_80e-04]] ) elif model_name == "xclip-base-patch16": __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([[0.0083, 0.9681, 0.0236]] ) elif model_name == "xclip-base-patch16-16-frames": __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([[7.69_37e-04, 9.97_28e-01, 1.94_73e-03]] ) elif model_name == "xclip-large-patch14": __SCREAMING_SNAKE_CASE : Any = torch.tensor([[0.0062, 0.9864, 0.0075]] ) elif model_name == "xclip-large-patch14-16-frames": __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[3.38_77e-04, 9.99_37e-01, 2.88_88e-04]] ) # kinetics-600 elif model_name == "xclip-base-patch16-kinetics-600": __SCREAMING_SNAKE_CASE : Any = torch.tensor([[0.0555, 0.8914, 0.0531]] ) elif model_name == "xclip-base-patch16-kinetics-600-16-frames": __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[3.85_54e-04, 9.99_29e-01, 3.27_54e-04]] ) elif model_name == "xclip-large-patch14-kinetics-600": __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[0.0036, 0.9920, 0.0045]] ) # few shot elif model_name == "xclip-base-patch16-hmdb-2-shot": __SCREAMING_SNAKE_CASE : str = torch.tensor([[7.18_90e-06, 9.99_94e-01, 5.65_59e-05]] ) elif model_name == "xclip-base-patch16-hmdb-4-shot": __SCREAMING_SNAKE_CASE : Dict = torch.tensor([[1.03_20e-05, 9.99_93e-01, 6.24_35e-05]] ) elif model_name == "xclip-base-patch16-hmdb-8-shot": __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[4.13_77e-06, 9.99_90e-01, 9.83_86e-05]] ) elif model_name == "xclip-base-patch16-hmdb-16-shot": __SCREAMING_SNAKE_CASE : Any = torch.tensor([[4.13_47e-05, 9.99_62e-01, 3.34_11e-04]] ) elif model_name == "xclip-base-patch16-ucf-2-shot": __SCREAMING_SNAKE_CASE : Dict = torch.tensor([[8.58_57e-05, 9.99_28e-01, 6.32_91e-04]] ) elif model_name == "xclip-base-patch16-ucf-4-shot": __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([[8.58_57e-05, 9.99_28e-01, 6.32_91e-04]] ) elif model_name == "xclip-base-patch16-ucf-8-shot": __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[0.0027, 0.9904, 0.0070]] ) elif model_name == "xclip-base-patch16-ucf-16-shot": __SCREAMING_SNAKE_CASE : str = torch.tensor([[9.82_19e-04, 9.95_93e-01, 3.08_63e-03]] ) # zero shot elif model_name == "xclip-base-patch16-zero-shot": __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[3.50_82e-04, 9.97_85e-01, 1.79_66e-03]] ) else: raise ValueError(F'''Model name {model_name} not supported''' ) assert torch.allclose(lowercase__ , lowercase__ , 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(lowercase__ ) if push_to_hub: print('''Pushing model, processor and slow tokenizer files to the hub...''' ) model.push_to_hub(lowercase__ , organization='''nielsr''' ) processor.push_to_hub(lowercase__ , organization='''nielsr''' ) slow_tokenizer.push_to_hub(lowercase__ , organization='''nielsr''' ) if __name__ == "__main__": __lowerCAmelCase : Union[str, 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.' ) __lowerCAmelCase : Optional[int] =parser.parse_args() convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
9
"""simple docstring""" import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __A (unittest.TestCase): '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple=13 , UpperCAmelCase_ : List[Any]=7 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Dict=99 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : Tuple=5 , UpperCAmelCase_ : Union[str, Any]=4 , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : int="gelu" , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : Dict=512 , UpperCAmelCase_ : Optional[Any]=16 , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : str=0.02 , UpperCAmelCase_ : str=4 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_attention_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_choices def lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_attention_mask: snake_case_ = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = 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 , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Union[str, Any] = True __lowercase: int = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" snake_case_ = FlaxRoFormerModelTester(self ) @slow def lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=UpperCAmelCase_ ) snake_case_ = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCAmelCase_ ) @require_flax class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" snake_case_ = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) snake_case_ = jnp.array([[0, 1, 2, 3, 4, 5]] ) snake_case_ = model(UpperCAmelCase_ )[0] snake_case_ = 50_000 snake_case_ = (1, 6, vocab_size) self.assertEqual(output.shape , UpperCAmelCase_ ) snake_case_ = jnp.array( [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) )
347
0
import collections import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __A = logging.get_logger(__name__) __A = "▁" __A = {"vocab_file": "prophetnet.tokenizer"} __A = { "vocab_file": { "microsoft/xprophetnet-large-wiki100-cased": ( "https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/prophetnet.tokenizer" ), } } __A = { "microsoft/xprophetnet-large-wiki100-cased": {"do_lower_case": False}, } __A = { "microsoft/xprophetnet-large-wiki100-cased": 512, } def lowerCAmelCase_ ( __a ) -> int: """simple docstring""" lowerCamelCase__: Optional[Any] =collections.OrderedDict() with open(__a , "r" , encoding="utf-8" ) as reader: lowerCamelCase__: int =reader.readlines() for index, token in enumerate(__a ): lowerCamelCase__: List[str] =token.rstrip("\n" ) lowerCamelCase__: List[Any] =index return vocab class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = ["input_ids", "attention_mask"] def __init__(self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]="[SEP]" , UpperCAmelCase_ : List[Any]="[SEP]" , UpperCAmelCase_ : Optional[Any]="[SEP]" , UpperCAmelCase_ : int="[UNK]" , UpperCAmelCase_ : Optional[Any]="[PAD]" , UpperCAmelCase_ : Dict="[CLS]" , UpperCAmelCase_ : Dict="[MASK]" , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , **UpperCAmelCase_ : Tuple , ) ->None: '''simple docstring''' lowerCamelCase__: int ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) try: import sentencepiece as spm except ImportError: logger.warning( "You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece" " pip install sentencepiece") raise lowerCamelCase__: Optional[int] =spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(UpperCAmelCase_)) lowerCamelCase__: Optional[int] =vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # put special tokens and [unused] tokens into the vocab lowerCamelCase__: Optional[int] ={"[PAD]": 0, "[CLS]": 1, "[SEP]": 2, "[UNK]": 3, "[MASK]": 4} for i in range(10): lowerCamelCase__: Optional[int] =F"""[unused{i}]""" lowerCamelCase__: int =5 + i # The first "real" token "," has position 15 in the embedding vocab and position 3 in the spm vocab lowerCamelCase__: int =12 lowerCamelCase__: Optional[Any] ={v: k for k, v in self.fairseq_tokens_to_ids.items()} for k in self.fairseq_tokens_to_ids.keys(): self.unique_no_split_tokens.append(UpperCAmelCase_) def __getstate__(self : List[str]) ->Dict: '''simple docstring''' lowerCamelCase__: Optional[int] =self.__dict__.copy() lowerCamelCase__: Dict =None return state def __setstate__(self : List[str] , UpperCAmelCase_ : Union[str, Any]) ->Dict: '''simple docstring''' lowerCamelCase__: Tuple =d try: import sentencepiece as spm except ImportError: logger.warning( "You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece" " pip install sentencepiece") raise # for backward compatibility if not hasattr(self , "sp_model_kwargs"): lowerCamelCase__: Dict ={} lowerCamelCase__: Tuple =spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False) ->List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_) if token_ids_a is None: return ([0] * len(UpperCAmelCase_)) + [1] return ([0] * len(UpperCAmelCase_)) + [1] + ([0] * len(UpperCAmelCase_)) + [1] def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]: '''simple docstring''' lowerCamelCase__: Any =[self.sep_token_id] if token_ids_a is None: return len(token_ids_a + sep) * [0] return len(token_ids_a + sep + sep + token_ids_a + sep) * [0] @property def SCREAMING_SNAKE_CASE_ (self : str) ->Dict: '''simple docstring''' return len(self.sp_model) + self.fairseq_offset def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Tuple: '''simple docstring''' lowerCamelCase__: str ={self.convert_ids_to_tokens(UpperCAmelCase_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : str) ->str: '''simple docstring''' return self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : List[Any]) ->str: '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowerCamelCase__: str =self.sp_model.PieceToId(UpperCAmelCase_) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any]) ->Optional[int]: '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset) def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Optional[Any]) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Union[str, Any] ="".join(UpperCAmelCase_).replace(UpperCAmelCase_ , " ").strip() return out_string def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]: '''simple docstring''' if not os.path.isdir(UpperCAmelCase_): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""") return lowerCamelCase__: List[str] =os.path.join( UpperCAmelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]) if os.path.abspath(self.vocab_file) != os.path.abspath(UpperCAmelCase_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , UpperCAmelCase_) elif not os.path.isfile(self.vocab_file): with open(UpperCAmelCase_ , "wb") as fi: lowerCamelCase__: Dict =self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_) return (out_vocab_file,) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]: '''simple docstring''' if token_ids_a is None: return token_ids_a + [self.sep_token_id] lowerCamelCase__: Union[str, Any] =[self.sep_token_id] return token_ids_a + sep + token_ids_a + sep
10
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> bool: snake_case_ = get_failure_array(_SCREAMING_SNAKE_CASE ) # 2) Step through text searching for pattern snake_case_ , snake_case_ = 0, 0 # index into text, pattern while i < len(_SCREAMING_SNAKE_CASE ): if pattern[j] == text[i]: if j == (len(_SCREAMING_SNAKE_CASE ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: snake_case_ = failure[j - 1] continue i += 1 return False def _a ( _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = [0] snake_case_ = 0 snake_case_ = 1 while j < len(_SCREAMING_SNAKE_CASE ): if pattern[i] == pattern[j]: i += 1 elif i > 0: snake_case_ = failure[i - 1] continue j += 1 failure.append(_SCREAMING_SNAKE_CASE ) return failure if __name__ == "__main__": # Test 1) __SCREAMING_SNAKE_CASE : Optional[int] = 'abc1abc12' __SCREAMING_SNAKE_CASE : Optional[int] = 'alskfjaldsabc1abc1abc12k23adsfabcabc' __SCREAMING_SNAKE_CASE : List[str] = 'alskfjaldsk23adsfabcabc' assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) __SCREAMING_SNAKE_CASE : int = 'ABABX' __SCREAMING_SNAKE_CASE : Optional[Any] = 'ABABZABABYABABX' assert kmp(pattern, text) # Test 3) __SCREAMING_SNAKE_CASE : Any = 'AAAB' __SCREAMING_SNAKE_CASE : List[Any] = 'ABAAAAAB' assert kmp(pattern, text) # Test 4) __SCREAMING_SNAKE_CASE : Optional[int] = 'abcdabcy' __SCREAMING_SNAKE_CASE : str = 'abcxabcdabxabcdabcdabcy' assert kmp(pattern, text) # Test 5) __SCREAMING_SNAKE_CASE : Any = 'aabaabaaa' assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
347
0
import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowerCAmelCase__ ( a): '''simple docstring''' __SCREAMING_SNAKE_CASE = ["image_processor", "tokenizer"] __SCREAMING_SNAKE_CASE = "LayoutLMv3ImageProcessor" __SCREAMING_SNAKE_CASE = ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast") def __init__( self , __lowerCamelCase=None , __lowerCamelCase=None , **__lowerCamelCase) -> Any: _A : Optional[Any] = 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 , ) _A : List[str] = kwargs.pop("feature_extractor") _A : Union[str, Any] = 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 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = True , __lowerCamelCase = False , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = True , __lowerCamelCase = None , **__lowerCamelCase , ) -> BatchEncoding: # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.") if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( "You cannot provide word labels if you initialized the image processor with apply_ocr set to True.") # first, apply the image processor _A : List[Any] = self.image_processor(images=__lowerCamelCase , return_tensors=__lowerCamelCase) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(__lowerCamelCase , __lowerCamelCase): _A : Dict = [text] # add batch dimension (as the image processor always adds a batch dimension) _A : Tuple = features["words"] _A : List[str] = self.tokenizer( text=text if text is not None else features["words"] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["boxes"] , word_labels=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) # add pixel values _A : Dict = features.pop("pixel_values") if return_overflowing_tokens is True: _A : int = self.get_overflowing_images(__lowerCamelCase , encoded_inputs["overflow_to_sample_mapping"]) _A : int = images return encoded_inputs def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase) -> Tuple: # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image _A : Optional[Any] = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx]) if len(__lowerCamelCase) != len(__lowerCamelCase): raise ValueError( "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got" F" {len(__lowerCamelCase)} and {len(__lowerCamelCase)}") return images_with_overflow def _lowerCamelCase ( self , *__lowerCamelCase , **__lowerCamelCase) -> List[str]: return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase) def _lowerCamelCase ( self , *__lowerCamelCase , **__lowerCamelCase) -> List[str]: return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase) @property def _lowerCamelCase ( self) -> Optional[Any]: return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def _lowerCamelCase ( self) -> str: warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , __lowerCamelCase , ) return self.image_processor_class @property def _lowerCamelCase ( self) -> List[Any]: warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , __lowerCamelCase , ) return self.image_processor
11
"""simple docstring""" from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class __A (snake_case__): '''simple docstring''' @slow @require_torch def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = EncoderDecoderModel.from_encoder_decoder_pretrained("""prajjwal1/bert-tiny""" , """prajjwal1/bert-tiny""" ) snake_case_ = BertTokenizer.from_pretrained("""bert-base-uncased""" ) snake_case_ = bertabert.config.encoder.vocab_size snake_case_ = tokenizer.sep_token_id snake_case_ = tokenizer.cls_token_id snake_case_ = 128 snake_case_ = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""train[:1%]""" ) snake_case_ = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""validation[:1%]""" ) snake_case_ = train_dataset.select(range(32 ) ) snake_case_ = val_dataset.select(range(16 ) ) snake_case_ = 4 def _map_to_encoder_decoder_inputs(UpperCAmelCase_ : int ): # Tokenizer will automatically set [BOS] <text> [EOS] snake_case_ = tokenizer(batch["""article"""] , padding="""max_length""" , truncation=UpperCAmelCase_ , max_length=512 ) snake_case_ = tokenizer(batch["""highlights"""] , padding="""max_length""" , truncation=UpperCAmelCase_ , max_length=128 ) snake_case_ = inputs.input_ids snake_case_ = inputs.attention_mask snake_case_ = outputs.input_ids snake_case_ = outputs.input_ids.copy() snake_case_ = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["""labels"""] ] snake_case_ = outputs.attention_mask assert all(len(UpperCAmelCase_ ) == 512 for x in inputs.input_ids ) assert all(len(UpperCAmelCase_ ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(UpperCAmelCase_ : Union[str, Any] ): snake_case_ = pred.label_ids snake_case_ = pred.predictions # all unnecessary tokens are removed snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = sum([int(pred_str[i] == label_str[i] ) for i in range(len(UpperCAmelCase_ ) )] ) / len(UpperCAmelCase_ ) return {"accuracy": accuracy} # map train dataset snake_case_ = train_dataset.map( _map_to_encoder_decoder_inputs , batched=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , remove_columns=["""article""", """highlights"""] , ) train_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) # same for validation dataset snake_case_ = val_dataset.map( _map_to_encoder_decoder_inputs , batched=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , remove_columns=["""article""", """highlights"""] , ) val_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) snake_case_ = self.get_auto_remove_tmp_dir() snake_case_ = SeqaSeqTrainingArguments( output_dir=UpperCAmelCase_ , per_device_train_batch_size=UpperCAmelCase_ , per_device_eval_batch_size=UpperCAmelCase_ , predict_with_generate=UpperCAmelCase_ , evaluation_strategy="""steps""" , do_train=UpperCAmelCase_ , do_eval=UpperCAmelCase_ , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer snake_case_ = SeqaSeqTrainer( model=UpperCAmelCase_ , args=UpperCAmelCase_ , compute_metrics=_compute_metrics , train_dataset=UpperCAmelCase_ , eval_dataset=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ , ) # start training trainer.train()
347
0
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = { 'EleutherAI/gpt-neo-1.3B': 'https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json', # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class lowerCamelCase__( __lowerCamelCase): UpperCAmelCase__ : int = 'gpt_neo' UpperCAmelCase__ : Union[str, Any] = ['past_key_values'] UpperCAmelCase__ : int = {'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'} def __init__( self: List[Any] , UpperCamelCase_: Union[str, Any]=5_02_57 , UpperCamelCase_: Any=20_48 , UpperCamelCase_: Optional[Any]=20_48 , UpperCamelCase_: Any=24 , UpperCamelCase_: int=[[["global", "local"], 12]] , UpperCamelCase_: Optional[int]=16 , UpperCamelCase_: str=None , UpperCamelCase_: Any=2_56 , UpperCamelCase_: List[str]="gelu_new" , UpperCamelCase_: Union[str, Any]=0.0 , UpperCamelCase_: Optional[Any]=0.0 , UpperCamelCase_: Union[str, Any]=0.0 , UpperCamelCase_: Dict=0.1 , UpperCamelCase_: List[Any]=1E-5 , UpperCamelCase_: Optional[Any]=0.02 , UpperCamelCase_: int=True , UpperCamelCase_: Optional[Any]=5_02_56 , UpperCamelCase_: Dict=5_02_56 , **UpperCamelCase_: int , ): __lowerCamelCase = vocab_size __lowerCamelCase = max_position_embeddings __lowerCamelCase = hidden_size __lowerCamelCase = num_layers __lowerCamelCase = num_heads __lowerCamelCase = intermediate_size __lowerCamelCase = window_size __lowerCamelCase = activation_function __lowerCamelCase = resid_dropout __lowerCamelCase = embed_dropout __lowerCamelCase = attention_dropout __lowerCamelCase = classifier_dropout __lowerCamelCase = layer_norm_epsilon __lowerCamelCase = initializer_range __lowerCamelCase = use_cache __lowerCamelCase = bos_token_id __lowerCamelCase = eos_token_id __lowerCamelCase = attention_types __lowerCamelCase = self.expand_attention_types_params(UpperCamelCase_ ) if len(self.attention_layers ) != self.num_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.attention_layers)` == `config.num_layers` """ F'but is `len(config.attention_layers) = {len(self.attention_layers )}`, ' F'`config.num_layers = {self.num_layers}`. ' """`config.attention_layers` is prepared using `config.attention_types`. """ """Please verify the value of `config.attention_types` argument.""" ) super().__init__(bos_token_id=UpperCamelCase_ , eos_token_id=UpperCamelCase_ , **UpperCamelCase_ ) @staticmethod def lowerCAmelCase__ ( UpperCamelCase_: Tuple ): __lowerCamelCase = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def lowerCamelCase__ ( A__ : int , A__ : Optional[Any] , A__ : Optional[int] , A__ : List[Any] ): '''simple docstring''' import torch __lowerCamelCase = input.size() __lowerCamelCase = len(A__ ) __lowerCamelCase = shape[dimension] __lowerCamelCase = torch.arange(0 , A__ , A__ ) __lowerCamelCase = torch.div(sizedim - size , A__ , rounding_mode="""floor""" ) + 1 __lowerCamelCase = torch.arange(A__ ) + low_indices[:min_length][:, None] __lowerCamelCase = [slice(A__ )] * rank __lowerCamelCase = indices __lowerCamelCase = input[s] __lowerCamelCase = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(A__ ) def lowerCamelCase__ ( A__ : Optional[int] , A__ : List[str] ): '''simple docstring''' import torch __lowerCamelCase = torch.arange(1 , A__ ) __lowerCamelCase = torch.remainder(A__ , A__ ) __lowerCamelCase = remainders == 0 __lowerCamelCase = candidates[divisor_indices] __lowerCamelCase = torch.max(A__ ) return largest_divisor, torch.div(A__ , A__ , rounding_mode="""floor""" ) class lowerCamelCase__( __lowerCamelCase): @property def lowerCAmelCase__ ( self: Any ): __lowerCamelCase = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(UpperCamelCase_ , direction="""inputs""" ) __lowerCamelCase = {0: """batch""", 1: """past_sequence + sequence"""} else: __lowerCamelCase = {0: """batch""", 1: """sequence"""} return common_inputs @property def lowerCAmelCase__ ( self: Dict ): return self._config.num_heads def lowerCAmelCase__ ( self: Tuple , UpperCamelCase_: PreTrainedTokenizer , UpperCamelCase_: int = -1 , UpperCamelCase_: int = -1 , UpperCamelCase_: bool = False , UpperCamelCase_: Optional[TensorType] = None , ): __lowerCamelCase = super(UpperCamelCase_ , self ).generate_dummy_inputs( UpperCamelCase_ , batch_size=UpperCamelCase_ , seq_length=UpperCamelCase_ , is_pair=UpperCamelCase_ , framework=UpperCamelCase_ ) # We need to order the input in the way they appears in the forward() __lowerCamelCase = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch __lowerCamelCase, __lowerCamelCase = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values __lowerCamelCase = seqlen + 2 __lowerCamelCase = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __lowerCamelCase = [ (torch.zeros(UpperCamelCase_ ), torch.zeros(UpperCamelCase_ )) for _ in range(self.num_layers ) ] __lowerCamelCase = common_inputs["""attention_mask"""] if self.use_past: __lowerCamelCase = ordered_inputs["""attention_mask"""].dtype __lowerCamelCase = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(UpperCamelCase_ , UpperCamelCase_ , dtype=UpperCamelCase_ )] , dim=1 ) return ordered_inputs @property def lowerCAmelCase__ ( self: Optional[Any] ): return 13
12
"""simple docstring""" # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys __SCREAMING_SNAKE_CASE : Tuple = subprocess.check_output('git merge-base main HEAD'.split()).decode('utf-8') __SCREAMING_SNAKE_CASE : Tuple = subprocess.check_output(f"""git diff --name-only {fork_point_sha}""".split()).decode('utf-8').split() __SCREAMING_SNAKE_CASE : Any = '|'.join(sys.argv[1:]) __SCREAMING_SNAKE_CASE : Optional[Any] = re.compile(Rf"""^({joined_dirs}).*?\.py$""") __SCREAMING_SNAKE_CASE : List[str] = [x for x in modified_files if regex.match(x)] print(' '.join(relevant_modified_files), end='')
347
0
import unittest import numpy as np from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING from transformers.pipelines import AudioClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_torchaudio, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class __lowercase ( unittest.TestCase ): """simple docstring""" _UpperCAmelCase : Optional[int] = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING _UpperCAmelCase : int = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Dict): SCREAMING_SNAKE_CASE_: Any = AudioClassificationPipeline(model=lowerCAmelCase__ , feature_extractor=lowerCAmelCase__) # test with a raw waveform SCREAMING_SNAKE_CASE_: Union[str, Any] = np.zeros((3_4000,)) SCREAMING_SNAKE_CASE_: List[Any] = np.zeros((1_4000,)) return audio_classifier, [audioa, audio] def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Optional[Any]): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Any = examples SCREAMING_SNAKE_CASE_: List[str] = audio_classifier(lowerCAmelCase__) # by default a model is initialized with num_labels=2 self.assertEqual( lowerCAmelCase__ , [ {"score": ANY(lowerCAmelCase__), "label": ANY(lowerCAmelCase__)}, {"score": ANY(lowerCAmelCase__), "label": ANY(lowerCAmelCase__)}, ] , ) SCREAMING_SNAKE_CASE_: Dict = audio_classifier(lowerCAmelCase__ , top_k=1) self.assertEqual( lowerCAmelCase__ , [ {"score": ANY(lowerCAmelCase__), "label": ANY(lowerCAmelCase__)}, ] , ) self.run_torchaudio(lowerCAmelCase__) @require_torchaudio def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : Dict): import datasets # test with a local file SCREAMING_SNAKE_CASE_: Optional[Any] = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation") SCREAMING_SNAKE_CASE_: List[Any] = dataset[0]["audio"]["array"] SCREAMING_SNAKE_CASE_: Tuple = audio_classifier(lowerCAmelCase__) self.assertEqual( lowerCAmelCase__ , [ {"score": ANY(lowerCAmelCase__), "label": ANY(lowerCAmelCase__)}, {"score": ANY(lowerCAmelCase__), "label": ANY(lowerCAmelCase__)}, ] , ) @require_torch def _SCREAMING_SNAKE_CASE ( self : int): SCREAMING_SNAKE_CASE_: List[str] = "anton-l/wav2vec2-random-tiny-classifier" SCREAMING_SNAKE_CASE_: Tuple = pipeline("audio-classification" , model=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: str = np.ones((8000,)) SCREAMING_SNAKE_CASE_: Optional[int] = audio_classifier(lowerCAmelCase__ , top_k=4) SCREAMING_SNAKE_CASE_: List[Any] = [ {"score": 0.0842, "label": "no"}, {"score": 0.0838, "label": "up"}, {"score": 0.0837, "label": "go"}, {"score": 0.0834, "label": "right"}, ] SCREAMING_SNAKE_CASE_: List[Any] = [ {"score": 0.0845, "label": "stop"}, {"score": 0.0844, "label": "on"}, {"score": 0.0841, "label": "right"}, {"score": 0.0834, "label": "left"}, ] self.assertIn(nested_simplify(lowerCAmelCase__ , decimals=4) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]) SCREAMING_SNAKE_CASE_: int = {"array": np.ones((8000,)), "sampling_rate": audio_classifier.feature_extractor.sampling_rate} SCREAMING_SNAKE_CASE_: str = audio_classifier(lowerCAmelCase__ , top_k=4) self.assertIn(nested_simplify(lowerCAmelCase__ , decimals=4) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]) @require_torch @slow def _SCREAMING_SNAKE_CASE ( self : Any): import datasets SCREAMING_SNAKE_CASE_: Optional[Any] = "superb/wav2vec2-base-superb-ks" SCREAMING_SNAKE_CASE_: Union[str, Any] = pipeline("audio-classification" , model=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Any = datasets.load_dataset("anton-l/superb_dummy" , "ks" , split="test") SCREAMING_SNAKE_CASE_: List[Any] = np.array(dataset[3]["speech"] , dtype=np.floataa) SCREAMING_SNAKE_CASE_: str = audio_classifier(lowerCAmelCase__ , top_k=4) self.assertEqual( nested_simplify(lowerCAmelCase__ , decimals=3) , [ {"score": 0.981, "label": "go"}, {"score": 0.007, "label": "up"}, {"score": 0.006, "label": "_unknown_"}, {"score": 0.001, "label": "down"}, ] , ) @require_tf @unittest.skip("Audio classification is not implemented for TF") def _SCREAMING_SNAKE_CASE ( self : List[str]): pass
13
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } __SCREAMING_SNAKE_CASE : List[Any] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = {} with open(_SCREAMING_SNAKE_CASE , """r""" ) as file: for line_number, line in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = line.strip() if line: snake_case_ = line.split() snake_case_ = line_number snake_case_ = words[0] snake_case_ = value return result def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: for attribute in key.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(_SCREAMING_SNAKE_CASE ): snake_case_ = PARAM_MAPPING[full_name.split(""".""" )[-1]] snake_case_ = """param""" if weight_type is not None and weight_type != "param": snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape elif weight_type is not None and weight_type == "param": snake_case_ = hf_pointer for attribute in hf_param_name.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = shape_pointer.shape # let's reduce dimension snake_case_ = value[0] else: snake_case_ = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": snake_case_ = value elif weight_type == "weight_g": snake_case_ = value elif weight_type == "weight_v": snake_case_ = value elif weight_type == "bias": snake_case_ = value elif weight_type == "param": for attribute in hf_param_name.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = value else: snake_case_ = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(_SCREAMING_SNAKE_CASE ): snake_case_ = PARAM_MAPPING[full_name.split(""".""" )[-1]] snake_case_ = """param""" if weight_type is not None and weight_type != "param": snake_case_ = """.""".join([key, weight_type] ) elif weight_type is not None and weight_type == "param": snake_case_ = """.""".join([key, hf_param_name] ) else: snake_case_ = key snake_case_ = value if """lm_head""" in full_key else value[0] __SCREAMING_SNAKE_CASE : int = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> List[str]: snake_case_ = False for key, mapped_key in MAPPING.items(): snake_case_ = """wav2vec2.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: snake_case_ = True if "*" in mapped_key: snake_case_ = name.split(_SCREAMING_SNAKE_CASE )[0].split(""".""" )[-2] snake_case_ = mapped_key.replace("""*""" , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: snake_case_ = """weight_g""" elif "weight_v" in name: snake_case_ = """weight_v""" elif "bias" in name: snake_case_ = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj snake_case_ = """weight""" else: snake_case_ = None if hf_dict is not None: rename_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return is_used return is_used def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = [] snake_case_ = fairseq_model.state_dict() snake_case_ = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): snake_case_ = False if "conv_layers" in name: load_conv_layer( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == """group""" , ) snake_case_ = True else: snake_case_ = load_wavaveca_layer(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(f"""Unused weights: {unused_weights}""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = full_name.split("""conv_layers.""" )[-1] snake_case_ = name.split(""".""" ) snake_case_ = int(items[0] ) snake_case_ = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_SCREAMING_SNAKE_CASE ) @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False ) -> int: if config_path is not None: snake_case_ = WavaVecaConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) else: snake_case_ = WavaVecaConfig() if is_seq_class: snake_case_ = read_txt_into_dict(_SCREAMING_SNAKE_CASE ) snake_case_ = idalabel snake_case_ = WavaVecaForSequenceClassification(_SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) elif is_finetuned: if dict_path: snake_case_ = Dictionary.load(_SCREAMING_SNAKE_CASE ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq snake_case_ = target_dict.pad_index snake_case_ = target_dict.bos_index snake_case_ = target_dict.eos_index snake_case_ = len(target_dict.symbols ) snake_case_ = os.path.join(_SCREAMING_SNAKE_CASE , """vocab.json""" ) if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) ) return os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) snake_case_ = target_dict.indices # fairseq has the <pad> and <s> switched snake_case_ = 0 snake_case_ = 1 with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaCTCTokenizer( _SCREAMING_SNAKE_CASE , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=_SCREAMING_SNAKE_CASE , ) snake_case_ = True if config.feat_extract_norm == """layer""" else False snake_case_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) snake_case_ = WavaVecaProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaForCTC(_SCREAMING_SNAKE_CASE ) else: snake_case_ = WavaVecaForPreTraining(_SCREAMING_SNAKE_CASE ) if is_finetuned or is_seq_class: snake_case_ , snake_case_ , snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: snake_case_ = argparse.Namespace(task="""audio_pretraining""" ) snake_case_ = fairseq.tasks.setup_task(_SCREAMING_SNAKE_CASE ) snake_case_ , snake_case_ , snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=_SCREAMING_SNAKE_CASE ) snake_case_ = model[0].eval() recursively_load_weights(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , not is_finetuned ) hf_wavavec.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) __SCREAMING_SNAKE_CASE : Any = parser.parse_args() __SCREAMING_SNAKE_CASE : List[Any] = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
347
0
from __future__ import annotations def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> tuple[float, list[float]]: """simple docstring""" A__ = list(range(len(lowercase_ ) ) ) A__ = [v / w for v, w in zip(lowercase_ , lowercase_ )] index.sort(key=lambda lowercase_ : ratio[i] , reverse=lowercase_ ) A__ = 0 A__ = [0] * len(lowercase_ ) for i in index: if weight[i] <= capacity: A__ = 1 max_value += value[i] capacity -= weight[i] else: A__ = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
14
"""simple docstring""" import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class __A : '''simple docstring''' def __init__( self : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any=14 , UpperCAmelCase_ : Union[str, Any]=7 , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : str=99 , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : List[Any]=4 , UpperCAmelCase_ : Optional[int]=4 , UpperCAmelCase_ : int=4 , UpperCAmelCase_ : str=37 , UpperCAmelCase_ : Any="gelu" , UpperCAmelCase_ : str=0.1 , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : int=512 , UpperCAmelCase_ : Tuple=0.02 , ) ->List[str]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = rotary_dim snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = initializer_range snake_case_ = None snake_case_ = vocab_size - 1 snake_case_ = vocab_size - 1 snake_case_ = vocab_size - 1 def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_input_mask: snake_case_ = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=UpperCAmelCase_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""input_ids""": input_ids, """attention_mask""": attention_mask} return config, inputs_dict def lowerCAmelCase ( self : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict ) ->Tuple: """simple docstring""" snake_case_ = 20 snake_case_ = model_class_name(UpperCAmelCase_ ) snake_case_ = model.init_cache(input_ids.shape[0] , UpperCAmelCase_ ) snake_case_ = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) snake_case_ = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) snake_case_ = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) snake_case_ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="""i4""" ) snake_case_ = model( input_ids[:, -1:] , attention_mask=UpperCAmelCase_ , past_key_values=outputs_cache.past_key_values , position_ids=UpperCAmelCase_ , ) snake_case_ = model(UpperCAmelCase_ ) snake_case_ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = 20 snake_case_ = model_class_name(UpperCAmelCase_ ) snake_case_ = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) snake_case_ = model.init_cache(input_ids.shape[0] , UpperCAmelCase_ ) snake_case_ = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) snake_case_ = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) snake_case_ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="""i4""" ) snake_case_ = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) snake_case_ = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ ) snake_case_ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) @require_flax class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Any = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () __lowercase: List[str] = (FlaxGPTJForCausalLM,) if is_flax_available() else () def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = FlaxGPTJModelTester(self ) def lowerCAmelCase ( self : int ) ->List[Any]: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ , snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : List[str] ) ->Any: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ , snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) @tooslow def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" snake_case_ = GPTaTokenizer.from_pretrained("""gpt2""" , pad_token="""<|endoftext|>""" , padding_side="""left""" ) snake_case_ = tokenizer(["""Hello this is a long string""", """Hey"""] , return_tensors="""np""" , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ ) snake_case_ = FlaxGPTJForCausalLM.from_pretrained("""EleutherAI/gpt-j-6B""" ) snake_case_ = False snake_case_ = model.config.eos_token_id snake_case_ = jax.jit(model.generate ) snake_case_ = jit_generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , pad_token_id=tokenizer.pad_token_id ).sequences snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = [ """Hello this is a long string of text.\n\nI'm trying to get the text of the""", """Hey, I'm a little late to the party. I'm going to""", ] self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) @is_pt_flax_cross_test def lowerCAmelCase ( self : int ) ->str: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class snake_case_ = model_class.__name__[4:] # Skip the "Flax" at the beginning snake_case_ = getattr(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ , snake_case_ = pt_inputs["""input_ids"""].shape snake_case_ = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCAmelCase_ ): snake_case_ = 0 snake_case_ = 1 snake_case_ = 0 snake_case_ = 1 snake_case_ = pt_model_class(UpperCAmelCase_ ).eval() snake_case_ = model_class(UpperCAmelCase_ , dtype=jnp.floataa ) snake_case_ = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , UpperCAmelCase_ ) snake_case_ = fx_state with torch.no_grad(): snake_case_ = pt_model(**UpperCAmelCase_ ).to_tuple() snake_case_ = fx_model(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(UpperCAmelCase_ ) snake_case_ = model_class.from_pretrained(UpperCAmelCase_ , from_pt=UpperCAmelCase_ ) snake_case_ = fx_model_loaded(**UpperCAmelCase_ ).to_tuple() self.assertEqual( len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output_loaded, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class snake_case_ = model_class.__name__[4:] # Skip the "Flax" at the beginning snake_case_ = getattr(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = pt_model_class(UpperCAmelCase_ ).eval() snake_case_ = model_class(UpperCAmelCase_ , dtype=jnp.floataa ) snake_case_ = load_flax_weights_in_pytorch_model(UpperCAmelCase_ , fx_model.params ) snake_case_ , snake_case_ = pt_inputs["""input_ids"""].shape snake_case_ = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCAmelCase_ ): snake_case_ = 0 snake_case_ = 1 snake_case_ = 0 snake_case_ = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): snake_case_ = pt_model(**UpperCAmelCase_ ).to_tuple() snake_case_ = fx_model(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(UpperCAmelCase_ ) snake_case_ = pt_model_class.from_pretrained(UpperCAmelCase_ , from_flax=UpperCAmelCase_ ) with torch.no_grad(): snake_case_ = pt_model_loaded(**UpperCAmelCase_ ).to_tuple() self.assertEqual( len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ = model_class_name.from_pretrained("""EleutherAI/gpt-j-6B""" ) snake_case_ = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCAmelCase_ )
347
0
import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : int ): __A = logging.get_logger() # the current default level is logging.WARNING __A = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() ,logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() ,logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() ,logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() ,logging.get_verbosity() ) # restore to the original level logging.set_verbosity(A ) def UpperCamelCase_ ( self : Dict ): __A = logging.get_verbosity() __A = logging.get_logger("transformers.models.bart.tokenization_bart" ) __A = "Testing 1, 2, 3" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(A ) as cl: logger.warning(A ) self.assertEqual(cl.out ,msg + "\n" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(A ) as cl: logger.warning(A ) self.assertEqual(cl.out ,"" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(A ) as cl: logger.warning(A ) self.assertEqual(cl.out ,msg + "\n" ) # restore to the original level logging.set_verbosity(A ) @mockenv(TRANSFORMERS_VERBOSITY="error" ) def UpperCamelCase_ ( self : Optional[Any] ): # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() # this action activates the env var __A = logging.get_logger("transformers.models.bart.tokenization_bart" ) __A = os.getenv("TRANSFORMERS_VERBOSITY" ,A ) __A = logging.log_levels[env_level_str] __A = logging.get_verbosity() self.assertEqual( A ,A ,f'''TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}''' ,) # restore to the original level __A = "" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="super-error" ) def UpperCamelCase_ ( self : Tuple ): # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() __A = logging.logging.getLogger() with CaptureLogger(A ) as cl: # this action activates the env var logging.get_logger("transformers.models.bart.tokenization_bart" ) self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" ,cl.out ) # no need to restore as nothing was changed def UpperCamelCase_ ( self : int ): # testing `logger.warning_advice()` transformers.utils.logging._reset_library_root_logger() __A = logging.get_logger("transformers.models.bart.tokenization_bart" ) __A = "Testing 1, 2, 3" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ): # nothing should be logged as env var disables this method with CaptureLogger(A ) as cl: logger.warning_advice(A ) self.assertEqual(cl.out ,"" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(A ) as cl: logger.warning_advice(A ) self.assertEqual(cl.out ,msg + "\n" ) def UpperCAmelCase ( ) -> List[str]: """simple docstring""" disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
15
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING __SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) class __A (snake_case__): '''simple docstring''' __lowercase: int = """upernet""" def __init__( self : str , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : str=512 , UpperCAmelCase_ : int=0.02 , UpperCAmelCase_ : Optional[Any]=[1, 2, 3, 6] , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Tuple=0.4 , UpperCAmelCase_ : Tuple=384 , UpperCAmelCase_ : Union[str, Any]=256 , UpperCAmelCase_ : str=1 , UpperCAmelCase_ : Tuple=False , UpperCAmelCase_ : Tuple=255 , **UpperCAmelCase_ : Dict , ) ->Union[str, Any]: """simple docstring""" super().__init__(**UpperCAmelCase_ ) if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) snake_case_ = CONFIG_MAPPING["""resnet"""](out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = backbone_config.get("""model_type""" ) snake_case_ = CONFIG_MAPPING[backbone_model_type] snake_case_ = config_class.from_dict(UpperCAmelCase_ ) snake_case_ = backbone_config snake_case_ = hidden_size snake_case_ = initializer_range snake_case_ = pool_scales snake_case_ = use_auxiliary_head snake_case_ = auxiliary_loss_weight snake_case_ = auxiliary_in_channels snake_case_ = auxiliary_channels snake_case_ = auxiliary_num_convs snake_case_ = auxiliary_concat_input snake_case_ = loss_ignore_index def lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.backbone_config.to_dict() snake_case_ = self.__class__.model_type return output
347
0
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class __A ( unittest.TestCase ): '''simple docstring''' def UpperCAmelCase ( self : List[Any] ) -> Tuple: """simple docstring""" lowercase__ : List[Any] = inspect.getfile(accelerate.test_utils ) lowercase__ : Tuple = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) lowercase__ : Tuple = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) lowercase__ : Any = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def UpperCAmelCase ( self : Dict ) -> Any: """simple docstring""" print(f"""Found {torch.cuda.device_count()} devices.""" ) lowercase__ : Any = ['''torchrun''', f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_snake_case ,env=os.environ.copy() ) @require_multi_gpu def UpperCAmelCase ( self : str ) -> List[Any]: """simple docstring""" print(f"""Found {torch.cuda.device_count()} devices.""" ) lowercase__ : Dict = ['''torchrun''', f"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(f"""Command: {cmd}""" ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_snake_case ,env=os.environ.copy() ) @require_multi_gpu def UpperCAmelCase ( self : Optional[int] ) -> str: """simple docstring""" lowercase__ : Any = ['''torchrun''', f"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_snake_case ,env=os.environ.copy() ) @require_multi_gpu def UpperCAmelCase ( self : Dict ) -> Optional[Any]: """simple docstring""" print(f"""Found {torch.cuda.device_count()} devices, using 2 devices only""" ) lowercase__ : str = ['''torchrun''', f"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 ,cuda_visible_devices='''0,1''' ): execute_subprocess_async(_snake_case ,env=os.environ.copy() ) if __name__ == "__main__": lowerCAmelCase_ = Accelerator() lowerCAmelCase_ = (accelerator.state.process_index + 2, 10) lowerCAmelCase_ = torch.randint(0, 10, shape).to(accelerator.device) lowerCAmelCase_ = '' lowerCAmelCase_ = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." lowerCAmelCase_ = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." lowerCAmelCase_ = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
16
"""simple docstring""" import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = """ylacombe/bark-small""" snake_case_ = tempfile.mkdtemp() snake_case_ = """en_speaker_1""" snake_case_ = """This is a test string""" snake_case_ = """speaker_embeddings_path.json""" snake_case_ = """speaker_embeddings""" def lowerCAmelCase ( self : List[str] , **UpperCAmelCase_ : str ) ->Optional[int]: """simple docstring""" return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = self.get_tokenizer() snake_case_ = BarkProcessor(tokenizer=UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) snake_case_ = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def lowerCAmelCase ( self : Dict ) ->int: """simple docstring""" snake_case_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) snake_case_ = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) snake_case_ = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) snake_case_ = 35 snake_case_ = 2 snake_case_ = 8 snake_case_ = { """semantic_prompt""": np.ones(UpperCAmelCase_ ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset snake_case_ = processor(text=self.input_string , voice_preset=UpperCAmelCase_ ) snake_case_ = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([] ) ).tolist() ) # test loading voice preset from npz file snake_case_ = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(UpperCAmelCase_ , **UpperCAmelCase_ ) snake_case_ = processor(text=self.input_string , voice_preset=UpperCAmelCase_ ) snake_case_ = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([] ) ).tolist() ) # test loading voice preset from the hub snake_case_ = processor(text=self.input_string , voice_preset=self.voice_preset ) def lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" snake_case_ = self.get_tokenizer() snake_case_ = BarkProcessor(tokenizer=UpperCAmelCase_ ) snake_case_ = processor(text=self.input_string ) snake_case_ = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
347
0
"""simple docstring""" def _A ( UpperCamelCase_ : Any) -> List[str]: '''simple docstring''' __lowercase ,__lowercase = [], [] while len(UpperCamelCase_) > 1: __lowercase ,__lowercase = min(UpperCamelCase_), max(UpperCamelCase_) start.append(UpperCamelCase_) end.append(UpperCamelCase_) collection.remove(UpperCamelCase_) collection.remove(UpperCamelCase_) end.reverse() return start + collection + end if __name__ == "__main__": _a = input('Enter numbers separated by a comma:\n').strip() _a = [int(item) for item in user_input.split(',')] print(*merge_sort(unsorted), sep=',')
17
"""simple docstring""" import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 __SCREAMING_SNAKE_CASE : int = sys.version_info >= (3, 10) def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: return field(default_factory=lambda: default , metadata=_SCREAMING_SNAKE_CASE ) @dataclass class __A : '''simple docstring''' __lowercase: int __lowercase: float __lowercase: str __lowercase: bool @dataclass class __A : '''simple docstring''' __lowercase: int = 42 __lowercase: str = field(default="""toto""" , metadata={"""help""": """help message"""}) @dataclass class __A : '''simple docstring''' __lowercase: bool = False __lowercase: bool = True __lowercase: Optional[bool] = None class __A (snake_case__): '''simple docstring''' __lowercase: str = """titi""" __lowercase: Any = """toto""" class __A (snake_case__): '''simple docstring''' __lowercase: int = """titi""" __lowercase: Optional[Any] = """toto""" __lowercase: List[Any] = 42 @dataclass class __A : '''simple docstring''' __lowercase: BasicEnum = "toto" def lowerCAmelCase ( self : int ) ->List[Any]: """simple docstring""" snake_case_ = BasicEnum(self.foo ) @dataclass class __A : '''simple docstring''' __lowercase: MixedTypeEnum = "toto" def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = MixedTypeEnum(self.foo ) @dataclass class __A : '''simple docstring''' __lowercase: Optional[int] = None __lowercase: Optional[float] = field(default=snake_case__ , metadata={"""help""": """help message"""}) __lowercase: Optional[str] = None __lowercase: Optional[List[str]] = list_field(default=[]) __lowercase: Optional[List[int]] = list_field(default=[]) @dataclass class __A : '''simple docstring''' __lowercase: List[int] = list_field(default=[]) __lowercase: List[int] = list_field(default=[1, 2, 3]) __lowercase: List[str] = list_field(default=["""Hallo""", """Bonjour""", """Hello"""]) __lowercase: List[float] = list_field(default=[0.1, 0.2, 0.3]) @dataclass class __A : '''simple docstring''' __lowercase: List[int] = field() __lowercase: str = field() __lowercase: BasicEnum = field() def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" snake_case_ = BasicEnum(self.required_enum ) @dataclass class __A : '''simple docstring''' __lowercase: int __lowercase: "BasicEnum" = field() __lowercase: "Optional[bool]" = None __lowercase: "str" = field(default="""toto""" , metadata={"""help""": """help message"""}) __lowercase: "List[str]" = list_field(default=["""Hallo""", """Bonjour""", """Hello"""]) if is_python_no_less_than_3_10: @dataclass class __A : '''simple docstring''' __lowercase: bool = False __lowercase: bool = True __lowercase: bool | None = None @dataclass class __A : '''simple docstring''' __lowercase: int | None = None __lowercase: float | None = field(default=snake_case__ , metadata={"""help""": """help message"""}) __lowercase: str | None = None __lowercase: list[str] | None = list_field(default=[]) __lowercase: list[int] | None = list_field(default=[]) class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : argparse.ArgumentParser , UpperCAmelCase_ : argparse.ArgumentParser ) ->Optional[int]: """simple docstring""" self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): snake_case_ = {k: v for k, v in vars(UpperCAmelCase_ ).items() if k != """container"""} snake_case_ = {k: v for k, v in vars(UpperCAmelCase_ ).items() if k != """container"""} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("""choices""" , UpperCAmelCase_ ) and yy.get("""choices""" , UpperCAmelCase_ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["""type"""](UpperCAmelCase_ ) , yy["""type"""](UpperCAmelCase_ ) ) del xx["type"], yy["type"] self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : int ) ->Any: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--bar""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--baz""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--flag""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ , const=UpperCAmelCase_ , nargs="""?""" ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = ["""--foo""", """1""", """--baz""", """quux""", """--bar""", """0.5"""] ((snake_case_) , ) = parser.parse_args_into_dataclasses(UpperCAmelCase_ , look_for_args_file=UpperCAmelCase_ ) self.assertFalse(example.flag ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=42 , type=UpperCAmelCase_ ) expected.add_argument("""--baz""" , default="""toto""" , type=UpperCAmelCase_ , help="""help message""" ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ , const=UpperCAmelCase_ , nargs="""?""" ) expected.add_argument("""--baz""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ , const=UpperCAmelCase_ , nargs="""?""" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("""--no_baz""" , action="""store_false""" , default=UpperCAmelCase_ , dest="""baz""" ) expected.add_argument("""--opt""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ ) snake_case_ = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(UpperCAmelCase_ ) for dataclass_type in dataclass_types: snake_case_ = HfArgumentParser(UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """--no_baz"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """--baz"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """True""", """--baz""", """True""", """--opt""", """True"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """False""", """--baz""", """False""", """--opt""", """False"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) def lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=["""titi""", """toto""", 42] , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) snake_case_ = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) snake_case_ = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) snake_case_ = parser.parse_args_into_dataclasses(["""--foo""", """titi"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) snake_case_ = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) snake_case_ = parser.parse_args_into_dataclasses(["""--foo""", """42"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" @dataclass class __A : '''simple docstring''' __lowercase: Literal["titi", "toto", 42] = "toto" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=("""titi""", """toto""", 42) , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) snake_case_ = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) snake_case_ = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo_int""" , nargs="""+""" , default=[] , type=UpperCAmelCase_ ) expected.add_argument("""--bar_int""" , nargs="""+""" , default=[1, 2, 3] , type=UpperCAmelCase_ ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=UpperCAmelCase_ ) expected.add_argument("""--foo_float""" , nargs="""+""" , default=[0.1, 0.2, 0.3] , type=UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual( UpperCAmelCase_ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["""Hallo""", """Bonjour""", """Hello"""] , foo_float=[0.1, 0.2, 0.3] ) , ) snake_case_ = parser.parse_args("""--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7""".split() ) self.assertEqual(UpperCAmelCase_ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["""a""", """b""", """c"""] , foo_float=[0.1, 0.7] ) ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=UpperCAmelCase_ , type=UpperCAmelCase_ ) expected.add_argument("""--bar""" , default=UpperCAmelCase_ , type=UpperCAmelCase_ , help="""help message""" ) expected.add_argument("""--baz""" , default=UpperCAmelCase_ , type=UpperCAmelCase_ ) expected.add_argument("""--ces""" , nargs="""+""" , default=[] , type=UpperCAmelCase_ ) expected.add_argument("""--des""" , nargs="""+""" , default=[] , type=UpperCAmelCase_ ) snake_case_ = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(UpperCAmelCase_ ) for dataclass_type in dataclass_types: snake_case_ = HfArgumentParser(UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , bar=UpperCAmelCase_ , baz=UpperCAmelCase_ , ces=[] , des=[] ) ) snake_case_ = parser.parse_args("""--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3""".split() ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=12 , bar=3.14 , baz="""42""" , ces=["""a""", """b""", """c"""] , des=[1, 2, 3] ) ) def lowerCAmelCase ( self : Optional[Any] ) ->Optional[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--required_list""" , nargs="""+""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--required_str""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=UpperCAmelCase_ , ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=UpperCAmelCase_ , ) expected.add_argument("""--opt""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ ) expected.add_argument("""--baz""" , default="""toto""" , type=UpperCAmelCase_ , help="""help message""" ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } snake_case_ = parser.parse_dict(UpperCAmelCase_ )[0] snake_case_ = BasicExample(**UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, """extra""": 42, } self.assertRaises(UpperCAmelCase_ , parser.parse_dict , UpperCAmelCase_ , allow_extra_keys=UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = os.path.join(UpperCAmelCase_ , """temp_json""" ) os.mkdir(UpperCAmelCase_ ) with open(temp_local_path + """.json""" , """w+""" ) as f: json.dump(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_yaml_file(Path(temp_local_path + """.json""" ) )[0] snake_case_ = BasicExample(**UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = os.path.join(UpperCAmelCase_ , """temp_yaml""" ) os.mkdir(UpperCAmelCase_ ) with open(temp_local_path + """.yaml""" , """w+""" ) as f: yaml.dump(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_yaml_file(Path(temp_local_path + """.yaml""" ) )[0] snake_case_ = BasicExample(**UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ )
347
0
import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def _snake_case ( lowerCAmelCase : Dict ): """simple docstring""" if ( (cp >= 0X4_E_0_0 and cp <= 0X9_F_F_F) or (cp >= 0X3_4_0_0 and cp <= 0X4_D_B_F) # or (cp >= 0X2_0_0_0_0 and cp <= 0X2_A_6_D_F) # or (cp >= 0X2_A_7_0_0 and cp <= 0X2_B_7_3_F) # or (cp >= 0X2_B_7_4_0 and cp <= 0X2_B_8_1_F) # or (cp >= 0X2_B_8_2_0 and cp <= 0X2_C_E_A_F) # or (cp >= 0XF_9_0_0 and cp <= 0XF_A_F_F) or (cp >= 0X2_F_8_0_0 and cp <= 0X2_F_A_1_F) # ): # return True return False def _snake_case ( lowerCAmelCase : str ): """simple docstring""" for char in word: SCREAMING_SNAKE_CASE_ : Any = ord(lowerCAmelCase ) if not _is_chinese_char(lowerCAmelCase ): return 0 return 1 def _snake_case ( lowerCAmelCase : List[str] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = set() for token in tokens: SCREAMING_SNAKE_CASE_ : int = len(lowerCAmelCase ) > 1 and is_chinese(lowerCAmelCase ) if chinese_word: word_set.add(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = list(lowerCAmelCase ) return word_list def _snake_case ( lowerCAmelCase : List[str] , lowerCAmelCase : set() ): """simple docstring""" if not chinese_word_set: return bert_tokens SCREAMING_SNAKE_CASE_ : str = max([len(lowerCAmelCase ) for w in chinese_word_set] ) SCREAMING_SNAKE_CASE_ : int = bert_tokens SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = 0, len(lowerCAmelCase ) while start < end: SCREAMING_SNAKE_CASE_ : Optional[int] = True if is_chinese(bert_word[start] ): SCREAMING_SNAKE_CASE_ : List[str] = min(end - start , lowerCAmelCase ) for i in range(lowerCAmelCase , 1 , -1 ): SCREAMING_SNAKE_CASE_ : Tuple = "".join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): SCREAMING_SNAKE_CASE_ : Optional[int] = "##" + bert_word[j] SCREAMING_SNAKE_CASE_ : int = start + i SCREAMING_SNAKE_CASE_ : Optional[Any] = False break if single_word: start += 1 return bert_word def _snake_case ( lowerCAmelCase : List[str] , lowerCAmelCase : LTP , lowerCAmelCase : BertTokenizer ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] for i in range(0 , len(lowerCAmelCase ) , 1_0_0 ): SCREAMING_SNAKE_CASE_ : Optional[int] = ltp_tokenizer.seg(lines[i : i + 1_0_0] )[0] SCREAMING_SNAKE_CASE_ : List[Any] = [get_chinese_word(lowerCAmelCase ) for r in res] ltp_res.extend(lowerCAmelCase ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] for i in range(0 , len(lowerCAmelCase ) , 1_0_0 ): SCREAMING_SNAKE_CASE_ : str = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=lowerCAmelCase , truncation=lowerCAmelCase , max_length=5_1_2 ) bert_res.extend(res["input_ids"] ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : int = [] for input_ids, chinese_word in zip(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_ : str = [] for id in input_ids: SCREAMING_SNAKE_CASE_ : Tuple = bert_tokenizer._convert_id_to_token(lowerCAmelCase ) input_tokens.append(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Any = add_sub_symbol(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Tuple = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(lowerCAmelCase ): if token[:2] == "##": SCREAMING_SNAKE_CASE_ : List[Any] = token[2:] # save chinese tokens' pos if len(lowerCAmelCase ) == 1 and _is_chinese_char(ord(lowerCAmelCase ) ): ref_id.append(lowerCAmelCase ) ref_ids.append(lowerCAmelCase ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ) return ref_ids def _snake_case ( lowerCAmelCase : Optional[int] ): """simple docstring""" with open(args.file_name , "r" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_ : List[Any] = f.readlines() SCREAMING_SNAKE_CASE_ : int = [line.strip() for line in data if len(lowerCAmelCase ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LTP(args.ltp ) # faster in GPU device SCREAMING_SNAKE_CASE_ : Tuple = BertTokenizer.from_pretrained(args.bert ) SCREAMING_SNAKE_CASE_ : List[str] = prepare_ref(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) with open(args.save_path , "w" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_ : Optional[int] = [json.dumps(lowerCAmelCase ) + "\n" for ref in ref_ids] f.writelines(lowerCAmelCase ) if __name__ == "__main__": __lowerCamelCase : Any = argparse.ArgumentParser(description='''prepare_chinese_ref''') parser.add_argument( '''--file_name''', type=str, default='''./resources/chinese-demo.txt''', help='''file need process, same as training data in lm''', ) parser.add_argument( '''--ltp''', type=str, default='''./resources/ltp''', help='''resources for LTP tokenizer, usually a path''' ) parser.add_argument('''--bert''', type=str, default='''./resources/robert''', help='''resources for Bert tokenizer''') parser.add_argument('''--save_path''', type=str, default='''./resources/ref.txt''', help='''path to save res''') __lowerCamelCase : int = parser.parse_args() main(args)
18
"""simple docstring""" import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy __SCREAMING_SNAKE_CASE : Any = logging.getLogger(__name__) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , ) -> Optional[Any]: snake_case_ = bnb_quantization_config.load_in_abit snake_case_ = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( """You have a version of `bitsandbytes` that is not compatible with 8bit quantization,""" """ make sure you have the latest version of `bitsandbytes` installed.""" ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( """You have a version of `bitsandbytes` that is not compatible with 4bit quantization,""" """make sure you have the latest version of `bitsandbytes` installed.""" ) snake_case_ = [] # custom device map if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(device_map.keys() ) > 1: snake_case_ = [key for key, value in device_map.items() if value in ["""disk""", """cpu"""]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: snake_case_ = get_keys_to_not_convert(_SCREAMING_SNAKE_CASE ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(_SCREAMING_SNAKE_CASE ) snake_case_ = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: snake_case_ = [] snake_case_ = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(_SCREAMING_SNAKE_CASE ) # compatibility with peft snake_case_ = load_in_abit snake_case_ = load_in_abit snake_case_ = get_parameter_device(_SCREAMING_SNAKE_CASE ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( """It is not recommended to quantize a loaded model. """ """The model should be instantiated under the `init_empty_weights` context manager.""" ) snake_case_ = replace_with_bnb_layers(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE ) # convert param to the right dtype snake_case_ = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: snake_case_ = name.replace(""".weight""" , """""" ).replace(""".bias""" , """""" ) snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(_SCREAMING_SNAKE_CASE ): param.to(_SCREAMING_SNAKE_CASE ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info( f"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" """We move the model to cuda.""" ) return model elif weights_location is None: raise RuntimeError( f"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): snake_case_ = replace_with_bnb_layers( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE ) snake_case_ = get_quantized_model_device_map( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_memory=_SCREAMING_SNAKE_CASE , no_split_module_classes=_SCREAMING_SNAKE_CASE , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): snake_case_ = True snake_case_ = any(x in list(device_map.values() ) for x in ["""cpu""", """disk"""] ) load_checkpoint_in_model( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=bnb_quantization_config.torch_dtype , offload_folder=_SCREAMING_SNAKE_CASE , offload_state_dict=_SCREAMING_SNAKE_CASE , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(_SCREAMING_SNAKE_CASE , device_map=_SCREAMING_SNAKE_CASE , offload_dir=_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: if device_map is None: if torch.cuda.is_available(): snake_case_ = {"""""": torch.cuda.current_device()} else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info("""The device_map was not initialized.""" """Setting device_map to `{'':torch.cuda.current_device()}`.""" ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( """If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or """ """'sequential'.""" ) snake_case_ = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) snake_case_ = {} snake_case_ = special_dtypes snake_case_ = no_split_module_classes snake_case_ = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": snake_case_ = get_balanced_memory( _SCREAMING_SNAKE_CASE , low_zero=(device_map == """balanced_low_0""") , max_memory=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) snake_case_ = max_memory snake_case_ = infer_auto_device_map(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # check if don't have any quantized module on the cpu snake_case_ = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules snake_case_ = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( """ Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules in `torch_dtype`, you need to pass a custom `device_map` to `load_and_quantize_model`. Check https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk for more details. """ ) else: logger.info( """Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit""" ) del device_map_without_some_modules return device_map def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: if modules_to_not_convert is None: snake_case_ = [] snake_case_ , snake_case_ = _replace_with_bnb_layers( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , ) -> List[Any]: snake_case_ = False for name, module in model.named_children(): if current_key_name is None: snake_case_ = [] current_key_name.append(_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` snake_case_ = """.""".join(_SCREAMING_SNAKE_CASE ) snake_case_ = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: snake_case_ = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: snake_case_ = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=_SCREAMING_SNAKE_CASE , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: snake_case_ = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("""load_in_8bit and load_in_4bit can't be both False""" ) snake_case_ = module.weight.data if module.bias is not None: snake_case_ = module.bias.data bnb_module.requires_grad_(_SCREAMING_SNAKE_CASE ) setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = True if len(list(module.children() ) ) > 0: snake_case_ , snake_case_ = _replace_with_bnb_layers( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def _a ( _SCREAMING_SNAKE_CASE ) -> Any: # Create a copy of the model with init_empty_weights(): snake_case_ = deepcopy(_SCREAMING_SNAKE_CASE ) # this has 0 cost since it is done inside `init_empty_weights` context manager` snake_case_ = find_tied_parameters(_SCREAMING_SNAKE_CASE ) # For compatibility with Accelerate < 0.18 if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: snake_case_ = sum(_SCREAMING_SNAKE_CASE , [] ) snake_case_ = len(_SCREAMING_SNAKE_CASE ) > 0 # Check if it is a base model snake_case_ = False if hasattr(_SCREAMING_SNAKE_CASE , """base_model_prefix""" ): snake_case_ = not hasattr(_SCREAMING_SNAKE_CASE , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head snake_case_ = list(model.named_children() ) snake_case_ = [list_modules[-1][0]] # add last module together with tied weights snake_case_ = set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE ) snake_case_ = list(set(_SCREAMING_SNAKE_CASE ) ) + list(_SCREAMING_SNAKE_CASE ) # remove ".weight" from the keys snake_case_ = [""".weight""", """.bias"""] snake_case_ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: snake_case_ = name.replace(_SCREAMING_SNAKE_CASE , """""" ) filtered_module_names.append(_SCREAMING_SNAKE_CASE ) return filtered_module_names def _a ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: for m in model.modules(): if isinstance(_SCREAMING_SNAKE_CASE , bnb.nn.Linearabit ): return True return False def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: return next(parameter.parameters() ).device def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: # if it is not quantized, we quantize and offload the quantized weights and the SCB stats if fpaa_statistics is None: set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 0 , dtype=_SCREAMING_SNAKE_CASE , value=_SCREAMING_SNAKE_CASE ) snake_case_ = param_name snake_case_ = model if "." in tensor_name: snake_case_ = tensor_name.split(""".""" ) for split in splits[:-1]: snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if new_module is None: raise ValueError(f"""{module} has no attribute {split}.""" ) snake_case_ = new_module snake_case_ = splits[-1] # offload weights snake_case_ = False offload_weight(module._parameters[tensor_name] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) if hasattr(module._parameters[tensor_name] , """SCB""" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("""weight""" , """SCB""" ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE , ) else: offload_weight(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) offload_weight(_SCREAMING_SNAKE_CASE , param_name.replace("""weight""" , """SCB""" ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , """meta""" , dtype=_SCREAMING_SNAKE_CASE , value=torch.empty(*param.size() ) )
347
0
import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging __A =logging.get_logger(__name__) def lowerCamelCase_ ( ): # Get the sagemaker specific mp parameters from smp_options variable. lowerCamelCase_ = os.getenv("SM_HP_MP_PARAMETERS" , "{}" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. lowerCamelCase_ = json.loads(lowerCamelCase__ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. lowerCamelCase_ = os.getenv("SM_FRAMEWORK_PARAMS" , "{}" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". lowerCamelCase_ = json.loads(lowerCamelCase__ ) if not mpi_options.get("sagemaker_mpi_enabled" , lowerCamelCase__ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("smdistributed" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class _SCREAMING_SNAKE_CASE ( snake_case_ ): lowerCAmelCase__ = field( default='' , metadata={'help': 'Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer'} , ) def SCREAMING_SNAKE_CASE_( self ) -> Tuple: super().__post_init__() warnings.warn( "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use " "`TrainingArguments` instead." , lowercase , ) @cached_property def SCREAMING_SNAKE_CASE_( self ) -> "torch.device": logger.info("PyTorch: setting up devices" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( "torch.distributed process group is initialized, but local_rank == -1. " "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch" ) if self.no_cuda: lowerCamelCase_ = torch.device("cpu" ) lowerCamelCase_ = 0 elif is_sagemaker_model_parallel_available(): lowerCamelCase_ = smp.local_rank() lowerCamelCase_ = torch.device("cuda" , lowercase ) lowerCamelCase_ = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="smddp" , timeout=self.ddp_timeout_delta ) lowerCamelCase_ = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK" ) ) lowerCamelCase_ = torch.device("cuda" , self.local_rank ) lowerCamelCase_ = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 lowerCamelCase_ = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. lowerCamelCase_ = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="nccl" , timeout=self.ddp_timeout_delta ) lowerCamelCase_ = torch.device("cuda" , self.local_rank ) lowerCamelCase_ = 1 if device.type == "cuda": torch.cuda.set_device(lowercase ) return device @property def SCREAMING_SNAKE_CASE_( self ) -> Tuple: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def SCREAMING_SNAKE_CASE_( self ) -> List[str]: return not is_sagemaker_model_parallel_available() @property def SCREAMING_SNAKE_CASE_( self ) -> Dict: return False
19
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple = { 'microsoft/beit-base-patch16-224-pt22k': ( 'https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json' ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __A (snake_case__): '''simple docstring''' __lowercase: Optional[int] = """beit""" def __init__( self : List[str] , UpperCAmelCase_ : List[Any]=8_192 , UpperCAmelCase_ : Dict=768 , UpperCAmelCase_ : int=12 , UpperCAmelCase_ : Tuple=12 , UpperCAmelCase_ : List[Any]=3_072 , UpperCAmelCase_ : Tuple="gelu" , UpperCAmelCase_ : Dict=0.0 , UpperCAmelCase_ : List[str]=0.0 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : Optional[Any]=1E-12 , UpperCAmelCase_ : int=224 , UpperCAmelCase_ : Tuple=16 , UpperCAmelCase_ : List[str]=3 , UpperCAmelCase_ : int=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Tuple=False , UpperCAmelCase_ : int=False , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Dict=[3, 5, 7, 11] , UpperCAmelCase_ : Tuple=[1, 2, 3, 6] , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[Any]=0.4 , UpperCAmelCase_ : Optional[Any]=256 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : int=False , UpperCAmelCase_ : Tuple=255 , **UpperCAmelCase_ : List[str] , ) ->Optional[Any]: """simple docstring""" super().__init__(**UpperCAmelCase_ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = use_mask_token snake_case_ = use_absolute_position_embeddings snake_case_ = use_relative_position_bias snake_case_ = use_shared_relative_position_bias snake_case_ = layer_scale_init_value snake_case_ = drop_path_rate snake_case_ = use_mean_pooling # decode head attributes (semantic segmentation) snake_case_ = out_indices snake_case_ = pool_scales # auxiliary head attributes (semantic segmentation) snake_case_ = use_auxiliary_head snake_case_ = auxiliary_loss_weight snake_case_ = auxiliary_channels snake_case_ = auxiliary_num_convs snake_case_ = auxiliary_concat_input snake_case_ = semantic_loss_ignore_index class __A (snake_case__): '''simple docstring''' __lowercase: List[Any] = version.parse("""1.11""") @property def lowerCAmelCase ( self : Dict ) ->Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def lowerCAmelCase ( self : Any ) ->float: """simple docstring""" return 1E-4
347
0
from typing import Tuple, Union from ...modeling_outputs import BackboneOutput from ...modeling_utils import PreTrainedModel from ...utils import is_timm_available, is_torch_available, requires_backends from ...utils.backbone_utils import BackboneMixin from .configuration_timm_backbone import TimmBackboneConfig if is_timm_available(): import timm if is_torch_available(): from torch import Tensor class __snake_case ( lowerCAmelCase , lowerCAmelCase ): _a : int= "pixel_values" _a : List[str]= False _a : Union[str, Any]= TimmBackboneConfig def __init__( self ,snake_case ,**snake_case ): '''simple docstring''' requires_backends(self ,"""timm""" ) super().__init__(snake_case ) lowercase : int = config if config.backbone is None: raise ValueError("""backbone is not set in the config. Please set it to a timm model name.""" ) if config.backbone not in timm.list_models(): raise ValueError(f"backbone {config.backbone} is not supported by timm." ) if hasattr(snake_case ,"""out_features""" ) and config.out_features is not None: raise ValueError("""out_features is not supported by TimmBackbone. Please use out_indices instead.""" ) lowercase : str = getattr(snake_case ,"""use_pretrained_backbone""" ,snake_case ) if pretrained is None: raise ValueError("""use_pretrained_backbone is not set in the config. Please set it to True or False.""" ) # We just take the final layer by default. This matches the default for the transformers models. lowercase : Optional[int] = config.out_indices if getattr(snake_case ,"""out_indices""" ,snake_case ) is not None else (-1,) lowercase : List[Any] = timm.create_model( config.backbone ,pretrained=snake_case ,features_only=config.features_only ,in_chans=config.num_channels ,out_indices=snake_case ,**snake_case ,) # These are used to control the output of the model when called. If output_hidden_states is True, then # return_layers is modified to include all layers. lowercase : Optional[int] = self._backbone.return_layers lowercase : Tuple = {layer["""module"""]: str(snake_case ) for i, layer in enumerate(self._backbone.feature_info.info )} super()._init_backbone(snake_case ) @classmethod def _SCREAMING_SNAKE_CASE ( cls ,snake_case ,*snake_case ,**snake_case ): '''simple docstring''' requires_backends(cls ,["""vision""", """timm"""] ) from ...models.timm_backbone import TimmBackboneConfig lowercase : Tuple = kwargs.pop("""config""" ,TimmBackboneConfig() ) lowercase : int = kwargs.pop("""use_timm_backbone""" ,snake_case ) if not use_timm: raise ValueError("""use_timm_backbone must be True for timm backbones""" ) lowercase : Any = kwargs.pop("""num_channels""" ,config.num_channels ) lowercase : List[Any] = kwargs.pop("""features_only""" ,config.features_only ) lowercase : Any = kwargs.pop("""use_pretrained_backbone""" ,config.use_pretrained_backbone ) lowercase : Dict = kwargs.pop("""out_indices""" ,config.out_indices ) lowercase : Any = TimmBackboneConfig( backbone=snake_case ,num_channels=snake_case ,features_only=snake_case ,use_pretrained_backbone=snake_case ,out_indices=snake_case ,) return super()._from_config(snake_case ,**snake_case ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case=None ,snake_case=None ,snake_case=None ,**snake_case ): '''simple docstring''' lowercase : List[Any] = return_dict if return_dict is not None else self.config.use_return_dict lowercase : Union[str, Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowercase : Any = output_attentions if output_attentions is not None else self.config.output_attentions if output_attentions: raise ValueError("""Cannot output attentions for timm backbones at the moment""" ) if output_hidden_states: # We modify the return layers to include all the stages of the backbone lowercase : str = self._all_layers lowercase : Any = self._backbone(snake_case ,**snake_case ) lowercase : List[str] = self._return_layers lowercase : List[Any] = tuple(hidden_states[i] for i in self.out_indices ) else: lowercase : List[Any] = self._backbone(snake_case ,**snake_case ) lowercase : Tuple = None lowercase : Any = tuple(snake_case ) lowercase : Dict = tuple(snake_case ) if hidden_states is not None else None if not return_dict: lowercase : Union[str, Any] = (feature_maps,) if output_hidden_states: lowercase : Optional[Any] = output + (hidden_states,) return output return BackboneOutput(feature_maps=snake_case ,hidden_states=snake_case ,attentions=snake_case )
20
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : List[Any] = {'vocab_file': 'spiece.model'} __SCREAMING_SNAKE_CASE : int = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', } } # TODO(PVP) - this should be removed in Transformers v5 __SCREAMING_SNAKE_CASE : Dict = { 't5-small': 512, 't5-base': 512, 't5-large': 512, 't5-3b': 512, 't5-11b': 512, } __SCREAMING_SNAKE_CASE : Optional[int] = '▁' class __A (snake_case__): '''simple docstring''' __lowercase: Optional[int] = VOCAB_FILES_NAMES __lowercase: Any = PRETRAINED_VOCAB_FILES_MAP __lowercase: Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase: List[str] = ["""input_ids""", """attention_mask"""] def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any]="</s>" , UpperCAmelCase_ : Optional[Any]="<unk>" , UpperCAmelCase_ : Any="<pad>" , UpperCAmelCase_ : Tuple=100 , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , UpperCAmelCase_ : Optional[int]=True , **UpperCAmelCase_ : Dict , ) ->None: """simple docstring""" if extra_ids > 0 and additional_special_tokens is None: snake_case_ = [F"""<extra_id_{i}>""" for i in range(UpperCAmelCase_ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens snake_case_ = len(set(filter(lambda UpperCAmelCase_ : bool("""extra_id""" in str(UpperCAmelCase_ ) ) , UpperCAmelCase_ ) ) ) if extra_tokens != extra_ids: raise ValueError( F"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are""" """ provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids""" """ tokens""" ) if legacy: logger.warning_once( F"""You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to""" """ read the related pull request available at https://github.com/huggingface/transformers/pull/24565""" ) snake_case_ = legacy snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , extra_ids=UpperCAmelCase_ , additional_special_tokens=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , legacy=UpperCAmelCase_ , **UpperCAmelCase_ , ) snake_case_ = vocab_file snake_case_ = extra_ids snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) @staticmethod def lowerCAmelCase ( UpperCAmelCase_ : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any] ) ->Union[str, Any]: """simple docstring""" if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: snake_case_ = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( """This tokenizer was incorrectly instantiated with a model max length of""" F""" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this""" """ behavior is kept to avoid breaking backwards compatibility when padding/encoding with""" """ `truncation is True`.\n- Be aware that you SHOULD NOT rely on""" F""" {pretrained_model_name_or_path} automatically truncating your input to""" F""" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences""" F""" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with""" """ `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please""" """ instantiate this tokenizer with `model_max_length` set to your preferred value.""" , UpperCAmelCase_ , ) return max_model_length @property def lowerCAmelCase ( self : Optional[Any] ) ->Optional[Any]: """simple docstring""" return self.sp_model.get_piece_size() + self._extra_ids def lowerCAmelCase ( self : Any ) ->Optional[int]: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(UpperCAmelCase_ )) + [1] return ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" return list( set(filter(lambda UpperCAmelCase_ : bool(re.search(R"""<extra_id_\d+>""" , UpperCAmelCase_ ) ) is not None , self.additional_special_tokens ) ) ) def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" return [self._convert_token_to_id(UpperCAmelCase_ ) for token in self.get_sentinel_tokens()] def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[int] ) ->List[int]: """simple docstring""" if len(UpperCAmelCase_ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F"""This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated""" """ eos tokens being added.""" ) return token_ids else: return token_ids + [self.eos_token_id] def lowerCAmelCase ( self : str , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = self._add_eos_if_not_present(UpperCAmelCase_ ) if token_ids_a is None: return token_ids_a else: snake_case_ = self._add_eos_if_not_present(UpperCAmelCase_ ) return token_ids_a + token_ids_a def __getstate__( self : Optional[Any] ) ->Tuple: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Optional[Any] , UpperCAmelCase_ : List[Any] ) ->List[Any]: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : "TextInput" , **UpperCAmelCase_ : Tuple ) ->List[str]: """simple docstring""" if not self.legacy: snake_case_ = SPIECE_UNDERLINE + text.replace(UpperCAmelCase_ , """ """ ) return super().tokenize(UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Any ) ->Tuple: """simple docstring""" if not self.legacy: snake_case_ = text.startswith(UpperCAmelCase_ ) if is_first: snake_case_ = text[1:] snake_case_ = self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) if not self.legacy and not is_first and not text.startswith(""" """ ) and tokens[0].startswith(UpperCAmelCase_ ): snake_case_ = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" if token.startswith("""<extra_id_""" ): snake_case_ = re.match(R"""<extra_id_(\d+)>""" , UpperCAmelCase_ ) snake_case_ = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(UpperCAmelCase_ ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" if index < self.sp_model.get_piece_size(): snake_case_ = self.sp_model.IdToPiece(UpperCAmelCase_ ) else: snake_case_ = F"""<extra_id_{self.vocab_size - 1 - index}>""" return token def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[str] ) ->Optional[Any]: """simple docstring""" snake_case_ = [] snake_case_ = """""" snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase_ ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(UpperCAmelCase_ ) snake_case_ = False out_string += self.sp_model.decode(UpperCAmelCase_ ) return out_string.strip() def lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,)
347
0
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer SCREAMING_SNAKE_CASE : str = "bart" SCREAMING_SNAKE_CASE : Optional[int] = True @st.cache(allow_output_mutation=lowerCamelCase_ ) def UpperCamelCase_( ) -> int: if LOAD_DENSE_INDEX: _lowercase : str = AutoTokenizer.from_pretrained('yjernite/retribert-base-uncased' ) _lowercase : Union[str, Any] = AutoModel.from_pretrained('yjernite/retribert-base-uncased' ).to('cuda:0' ) _lowercase : str = qar_model.eval() else: _lowercase , _lowercase : Any = (None, None) if MODEL_TYPE == "bart": _lowercase : Dict = AutoTokenizer.from_pretrained('yjernite/bart_eli5' ) _lowercase : int = AutoModelForSeqaSeqLM.from_pretrained('yjernite/bart_eli5' ).to('cuda:0' ) _lowercase : Any = torch.load('seq2seq_models/eli5_bart_model_blm_2.pth' ) sas_model.load_state_dict(save_dict['model'] ) _lowercase : List[Any] = sas_model.eval() else: _lowercase , _lowercase : Union[str, Any] = make_qa_sas_model( model_name='t5-small' , from_file='seq2seq_models/eli5_t5_model_1024_4.pth' , device='cuda:0' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=lowerCamelCase_ ) def UpperCamelCase_( ) -> str: if LOAD_DENSE_INDEX: _lowercase : Optional[Any] = faiss.StandardGpuResources() _lowercase : Optional[int] = datasets.load_dataset(path='wiki_snippets' , name='wiki40b_en_100_0' )['train'] _lowercase : Tuple = np.memmap( 'wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat' , dtype='float32' , mode='r' , shape=(wikiaab_passages.num_rows, 128) , ) _lowercase : Any = faiss.IndexFlatIP(128 ) _lowercase : Union[str, Any] = faiss.index_cpu_to_gpu(lowerCamelCase_ , 1 , lowerCamelCase_ ) wikiaab_gpu_index_flat.add(lowerCamelCase_ ) # TODO fix for larger GPU else: _lowercase , _lowercase : Any = (None, None) _lowercase : List[str] = Elasticsearch([{'host': 'localhost', 'port': '9200'}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=lowerCamelCase_ ) def UpperCamelCase_( ) -> Any: _lowercase : List[str] = datasets.load_dataset('eli5' , name='LFQA_reddit' ) _lowercase : Optional[Any] = elia['train_eli5'] _lowercase : Tuple = np.memmap( 'eli5_questions_reps.dat' , dtype='float32' , mode='r' , shape=(elia_train.num_rows, 128) ) _lowercase : Union[str, Any] = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(lowerCamelCase_ ) return (elia_train, eli5_train_q_index) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = load_indexes() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = load_models() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = load_train_data() def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_=10 ) -> List[str]: _lowercase : Any = embed_questions_for_retrieval([question] , lowerCamelCase_ , lowerCamelCase_ ) _lowercase , _lowercase : List[str] = eli5_train_q_index.search(lowerCamelCase_ , lowerCamelCase_ ) _lowercase : List[str] = [elia_train[int(lowerCamelCase_ )] for i in I[0]] return nn_examples def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_="wiki40b" , lowerCamelCase_="dense" , lowerCamelCase_=10 ) -> Dict: if source == "none": _lowercase , _lowercase : Union[str, Any] = (' <P> '.join(['' for _ in range(11 )] ).strip(), []) else: if method == "dense": _lowercase , _lowercase : Dict = query_qa_dense_index( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) else: _lowercase , _lowercase : str = query_es_index( lowerCamelCase_ , lowerCamelCase_ , index_name='english_wiki40b_snippets_100w' , n_results=lowerCamelCase_ , ) _lowercase : List[Any] = [ (res['article_title'], res['section_title'].strip(), res['score'], res['passage_text']) for res in hit_lst ] _lowercase : Union[str, Any] = 'question: {} context: {}'.format(lowerCamelCase_ , lowerCamelCase_ ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda lowerCamelCase_ : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda lowerCamelCase_ : None), } ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=64 , lowerCamelCase_=256 , lowerCamelCase_=False , lowerCamelCase_=2 , lowerCamelCase_=0.95 , lowerCamelCase_=0.8 ) -> Dict: with torch.no_grad(): _lowercase : str = qa_sas_generate( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , num_answers=1 , num_beams=lowerCamelCase_ , min_len=lowerCamelCase_ , max_len=lowerCamelCase_ , do_sample=lowerCamelCase_ , temp=lowerCamelCase_ , top_p=lowerCamelCase_ , top_k=lowerCamelCase_ , max_input_length=1024 , device='cuda:0' , )[0] return (answer, support_list) st.title("Long Form Question Answering with ELI5") # Start sidebar SCREAMING_SNAKE_CASE : Union[str, Any] = "<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>" SCREAMING_SNAKE_CASE : List[Any] = "\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class=\"img-container\"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n" % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia SCREAMING_SNAKE_CASE : Any = "\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n" st.sidebar.markdown(description, unsafe_allow_html=True) SCREAMING_SNAKE_CASE : Union[str, Any] = [ "Answer the question", "View the retrieved document only", "View the most similar ELI5 question and answer", "Show me everything, please!", ] SCREAMING_SNAKE_CASE : Optional[int] = st.sidebar.checkbox("Demo options") if demo_options: SCREAMING_SNAKE_CASE : List[str] = st.sidebar.selectbox( "", action_list, index=3, ) SCREAMING_SNAKE_CASE : Optional[int] = action_list.index(action_st) SCREAMING_SNAKE_CASE : Tuple = st.sidebar.selectbox( "", ["Show full text of passages", "Show passage section titles"], index=0, ) SCREAMING_SNAKE_CASE : int = show_type == "Show full text of passages" else: SCREAMING_SNAKE_CASE : Any = 3 SCREAMING_SNAKE_CASE : Dict = True SCREAMING_SNAKE_CASE : Union[str, Any] = st.sidebar.checkbox("Retrieval options") if retrieval_options: SCREAMING_SNAKE_CASE : Tuple = "\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n " st.sidebar.markdown(retriever_info) SCREAMING_SNAKE_CASE : Dict = st.sidebar.selectbox("Which Wikipedia format should the model use?", ["wiki40b", "none"]) SCREAMING_SNAKE_CASE : Union[str, Any] = st.sidebar.selectbox("Which Wikipedia indexer should the model use?", ["dense", "sparse", "mixed"]) else: SCREAMING_SNAKE_CASE : int = "wiki40b" SCREAMING_SNAKE_CASE : int = "dense" SCREAMING_SNAKE_CASE : str = "beam" SCREAMING_SNAKE_CASE : Optional[Any] = 2 SCREAMING_SNAKE_CASE : List[str] = 64 SCREAMING_SNAKE_CASE : Union[str, Any] = 256 SCREAMING_SNAKE_CASE : Union[str, Any] = None SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : str = st.sidebar.checkbox("Generation options") if generate_options: SCREAMING_SNAKE_CASE : Any = "\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder's output probabilities.\n " st.sidebar.markdown(generate_info) SCREAMING_SNAKE_CASE : List[Any] = st.sidebar.selectbox("Would you like to use beam search or sample an answer?", ["beam", "sampled"]) SCREAMING_SNAKE_CASE : Tuple = st.sidebar.slider( "Minimum generation length", min_value=8, max_value=256, value=64, step=8, format=None, key=None ) SCREAMING_SNAKE_CASE : int = st.sidebar.slider( "Maximum generation length", min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": SCREAMING_SNAKE_CASE : int = st.sidebar.slider("Beam size", min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: SCREAMING_SNAKE_CASE : Union[str, Any] = st.sidebar.slider( "Nucleus sampling p", min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) SCREAMING_SNAKE_CASE : Any = st.sidebar.slider( "Temperature", min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) SCREAMING_SNAKE_CASE : str = None # start main text SCREAMING_SNAKE_CASE : List[str] = [ "<MY QUESTION>", "How do people make chocolate?", "Why do we get a fever when we are sick?", "How can different animals perceive different colors?", "What is natural language processing?", "What's the best way to treat a sunburn?", "What exactly are vitamins ?", "How does nuclear energy provide electricity?", "What's the difference between viruses and bacteria?", "Why are flutes classified as woodwinds when most of them are made out of metal ?", "Why do people like drinking coffee even though it tastes so bad?", "What happens when wine ages? How does it make the wine taste better?", "If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?", "How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?", "How does New Zealand have so many large bird predators?", ] SCREAMING_SNAKE_CASE : str = st.selectbox( "What would you like to ask? ---- select <MY QUESTION> to enter a new query", questions_list, index=1, ) if question_s == "<MY QUESTION>": SCREAMING_SNAKE_CASE : List[str] = st.text_input("Enter your question here:", "") else: SCREAMING_SNAKE_CASE : Optional[int] = question_s if st.button("Show me!"): if action in [0, 1, 3]: if index_type == "mixed": SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = make_support(question, source=wiki_source, method="dense", n_results=10) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = make_support(question, source=wiki_source, method="sparse", n_results=10) SCREAMING_SNAKE_CASE : Tuple = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] SCREAMING_SNAKE_CASE : Optional[Any] = support_list[:10] SCREAMING_SNAKE_CASE : int = "<P> " + " <P> ".join([res[-1] for res in support_list]) else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == "sampled"), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown("### The model generated answer is:") st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown("--- \n ### The model is drawing information from the following Wikipedia passages:") for i, res in enumerate(support_list): SCREAMING_SNAKE_CASE : Optional[Any] = "https://en.wikipedia.org/wiki/{}".format(res[0].replace(" ", "_")) SCREAMING_SNAKE_CASE : List[Any] = res[1].strip() if sec_titles == "": SCREAMING_SNAKE_CASE : Union[str, Any] = "[{}]({})".format(res[0], wiki_url) else: SCREAMING_SNAKE_CASE : Any = sec_titles.split(" & ") SCREAMING_SNAKE_CASE : List[Any] = " & ".join( ["[{}]({}#{})".format(sec.strip(), wiki_url, sec.strip().replace(" ", "_")) for sec in sec_list] ) st.markdown( "{0:02d} - **Article**: {1:<18} <br> _Section_: {2}".format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( "> <span style=\"font-family:arial; font-size:10pt;\">" + res[-1] + "</span>", unsafe_allow_html=True ) if action in [2, 3]: SCREAMING_SNAKE_CASE : str = find_nearest_training(question) SCREAMING_SNAKE_CASE : Any = nn_train_list[0] st.markdown( "--- \n ### The most similar question in the ELI5 training set was: \n\n {}".format(train_exple["title"]) ) SCREAMING_SNAKE_CASE : str = [ "{}. {}".format(i + 1, " \n".join([line.strip() for line in ans.split("\n") if line.strip() != ""])) for i, (ans, sc) in enumerate(zip(train_exple["answers"]["text"], train_exple["answers"]["score"])) if i == 0 or sc > 2 ] st.markdown("##### Its answers were: \n\n {}".format("\n".join(answers_st))) SCREAMING_SNAKE_CASE : Tuple = "\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n" st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
21
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE = 1_000_000 ) -> int: snake_case_ = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , _SCREAMING_SNAKE_CASE ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
347
0
'''simple docstring''' def UpperCAmelCase_ ( __lowercase : str , __lowercase : str ) -> bool: '''simple docstring''' _UpperCAmelCase = len(__lowercase ) + 1 _UpperCAmelCase = len(__lowercase ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. _UpperCAmelCase = [[0 for i in range(__lowercase )] for j in range(__lowercase )] # since string of zero length match pattern of zero length _UpperCAmelCase = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , __lowercase ): _UpperCAmelCase = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , __lowercase ): _UpperCAmelCase = dp[0][j - 2] if pattern[j - 1] == "*" else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , __lowercase ): for j in range(1 , __lowercase ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": _UpperCAmelCase = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: _UpperCAmelCase = 1 elif pattern[j - 2] in (input_string[i - 1], "."): _UpperCAmelCase = dp[i - 1][j] else: _UpperCAmelCase = 0 else: _UpperCAmelCase = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") __SCREAMING_SNAKE_CASE :str = '''aab''' __SCREAMING_SNAKE_CASE :Optional[Any] = '''c*a*b''' # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(F"{input_string} matches the given pattern {pattern}") else: print(F"{input_string} does not match with the given pattern {pattern}")
22
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: print(f"""Vertex\tShortest Distance from vertex {src}""" ) for i, d in enumerate(_SCREAMING_SNAKE_CASE ): print(f"""{i}\t\t{d}""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: for j in range(_SCREAMING_SNAKE_CASE ): snake_case_ , snake_case_ , snake_case_ = (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 _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[float]: snake_case_ = [float("""inf""" )] * vertex_count snake_case_ = 0.0 for _ in range(vertex_count - 1 ): for j in range(_SCREAMING_SNAKE_CASE ): snake_case_ , snake_case_ , snake_case_ = (graph[j][k] for k in ["""src""", """dst""", """weight"""]) if distance[u] != float("""inf""" ) and distance[u] + w < distance[v]: snake_case_ = distance[u] + w snake_case_ = check_negative_cycle(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if negative_cycle_exists: raise Exception("""Negative cycle found""" ) return distance if __name__ == "__main__": import doctest doctest.testmod() __SCREAMING_SNAKE_CASE : int = int(input('Enter number of vertices: ').strip()) __SCREAMING_SNAKE_CASE : Dict = 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 : List[str] = ( int(x) for x in input('Enter source, destination, weight: ').strip().split(' ') ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'src': src, 'dst': dest, 'weight': weight} __SCREAMING_SNAKE_CASE : Union[str, Any] = int(input('\nEnter shortest path source:').strip()) __SCREAMING_SNAKE_CASE : str = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
347
0
'''simple docstring''' from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def snake_case_ ( _lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : float = 1 / sqrt(2 ) ) -> IIRFilter: UpperCAmelCase : Optional[int] = tau * frequency / samplerate UpperCAmelCase : List[Any] = sin(_lowerCAmelCase ) UpperCAmelCase : Optional[Any] = cos(_lowerCAmelCase ) UpperCAmelCase : int = _sin / (2 * q_factor) UpperCAmelCase : Any = (1 - _cos) / 2 UpperCAmelCase : List[Any] = 1 - _cos UpperCAmelCase : Union[str, Any] = 1 + alpha UpperCAmelCase : Any = -2 * _cos UpperCAmelCase : Dict = 1 - alpha UpperCAmelCase : Union[str, Any] = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def snake_case_ ( _lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : float = 1 / sqrt(2 ) ) -> IIRFilter: UpperCAmelCase : Any = tau * frequency / samplerate UpperCAmelCase : Tuple = sin(_lowerCAmelCase ) UpperCAmelCase : Tuple = cos(_lowerCAmelCase ) UpperCAmelCase : Dict = _sin / (2 * q_factor) UpperCAmelCase : int = (1 + _cos) / 2 UpperCAmelCase : List[Any] = -1 - _cos UpperCAmelCase : Tuple = 1 + alpha UpperCAmelCase : List[str] = -2 * _cos UpperCAmelCase : Optional[Any] = 1 - alpha UpperCAmelCase : Tuple = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def snake_case_ ( _lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : float = 1 / sqrt(2 ) ) -> IIRFilter: UpperCAmelCase : Optional[int] = tau * frequency / samplerate UpperCAmelCase : Optional[int] = sin(_lowerCAmelCase ) UpperCAmelCase : Tuple = cos(_lowerCAmelCase ) UpperCAmelCase : Optional[int] = _sin / (2 * q_factor) UpperCAmelCase : Union[str, Any] = _sin / 2 UpperCAmelCase : Any = 0 UpperCAmelCase : int = -ba UpperCAmelCase : Optional[Any] = 1 + alpha UpperCAmelCase : List[Any] = -2 * _cos UpperCAmelCase : Optional[Any] = 1 - alpha UpperCAmelCase : int = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def snake_case_ ( _lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : float = 1 / sqrt(2 ) ) -> IIRFilter: UpperCAmelCase : List[str] = tau * frequency / samplerate UpperCAmelCase : Union[str, Any] = sin(_lowerCAmelCase ) UpperCAmelCase : str = cos(_lowerCAmelCase ) UpperCAmelCase : Optional[Any] = _sin / (2 * q_factor) UpperCAmelCase : List[str] = 1 - alpha UpperCAmelCase : Any = -2 * _cos UpperCAmelCase : Optional[int] = 1 + alpha UpperCAmelCase : Union[str, Any] = IIRFilter(2 ) filt.set_coefficients([ba, ba, ba] , [ba, ba, ba] ) return filt def snake_case_ ( _lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : float , _lowerCAmelCase : float = 1 / sqrt(2 ) , ) -> IIRFilter: UpperCAmelCase : Optional[Any] = tau * frequency / samplerate UpperCAmelCase : Union[str, Any] = sin(_lowerCAmelCase ) UpperCAmelCase : Optional[int] = cos(_lowerCAmelCase ) UpperCAmelCase : Dict = _sin / (2 * q_factor) UpperCAmelCase : str = 10 ** (gain_db / 40) UpperCAmelCase : int = 1 + alpha * big_a UpperCAmelCase : Union[str, Any] = -2 * _cos UpperCAmelCase : Optional[Any] = 1 - alpha * big_a UpperCAmelCase : Union[str, Any] = 1 + alpha / big_a UpperCAmelCase : Tuple = -2 * _cos UpperCAmelCase : Any = 1 - alpha / big_a UpperCAmelCase : Optional[Any] = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def snake_case_ ( _lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : float , _lowerCAmelCase : float = 1 / sqrt(2 ) , ) -> IIRFilter: UpperCAmelCase : Any = tau * frequency / samplerate UpperCAmelCase : Optional[int] = sin(_lowerCAmelCase ) UpperCAmelCase : Union[str, Any] = cos(_lowerCAmelCase ) UpperCAmelCase : str = _sin / (2 * q_factor) UpperCAmelCase : List[str] = 10 ** (gain_db / 40) UpperCAmelCase : Optional[int] = (big_a + 1) - (big_a - 1) * _cos UpperCAmelCase : int = (big_a + 1) + (big_a - 1) * _cos UpperCAmelCase : int = (big_a - 1) - (big_a + 1) * _cos UpperCAmelCase : Optional[int] = (big_a - 1) + (big_a + 1) * _cos UpperCAmelCase : str = 2 * sqrt(_lowerCAmelCase ) * alpha UpperCAmelCase : Dict = big_a * (pmc + aaa) UpperCAmelCase : Any = 2 * big_a * mpc UpperCAmelCase : Union[str, Any] = big_a * (pmc - aaa) UpperCAmelCase : Optional[int] = ppmc + aaa UpperCAmelCase : Optional[Any] = -2 * pmpc UpperCAmelCase : Optional[Any] = ppmc - aaa UpperCAmelCase : int = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def snake_case_ ( _lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : float , _lowerCAmelCase : float = 1 / sqrt(2 ) , ) -> IIRFilter: UpperCAmelCase : int = tau * frequency / samplerate UpperCAmelCase : Union[str, Any] = sin(_lowerCAmelCase ) UpperCAmelCase : Union[str, Any] = cos(_lowerCAmelCase ) UpperCAmelCase : Any = _sin / (2 * q_factor) UpperCAmelCase : int = 10 ** (gain_db / 40) UpperCAmelCase : List[str] = (big_a + 1) - (big_a - 1) * _cos UpperCAmelCase : Union[str, Any] = (big_a + 1) + (big_a - 1) * _cos UpperCAmelCase : Optional[Any] = (big_a - 1) - (big_a + 1) * _cos UpperCAmelCase : Union[str, Any] = (big_a - 1) + (big_a + 1) * _cos UpperCAmelCase : List[str] = 2 * sqrt(_lowerCAmelCase ) * alpha UpperCAmelCase : Any = big_a * (ppmc + aaa) UpperCAmelCase : str = -2 * big_a * pmpc UpperCAmelCase : List[Any] = big_a * (ppmc - aaa) UpperCAmelCase : Optional[Any] = pmc + aaa UpperCAmelCase : Any = 2 * mpc UpperCAmelCase : str = pmc - aaa UpperCAmelCase : Union[str, Any] = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt
23
"""simple docstring""" import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) __SCREAMING_SNAKE_CASE : List[str] = logging.getLogger(__name__) __SCREAMING_SNAKE_CASE : str = tf.data.AUTOTUNE def _a ( ) -> List[str]: snake_case_ = argparse.ArgumentParser(description="""Train a masked language model on TPU.""" ) parser.add_argument( """--pretrained_model_config""" , type=_SCREAMING_SNAKE_CASE , default="""roberta-base""" , help="""The model config to use. Note that we don't copy the model's weights, only the config!""" , ) parser.add_argument( """--tokenizer""" , type=_SCREAMING_SNAKE_CASE , default="""unigram-tokenizer-wikitext""" , help="""The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model's vocab size.""" , ) parser.add_argument( """--per_replica_batch_size""" , type=_SCREAMING_SNAKE_CASE , default=8 , help="""Batch size per TPU core.""" , ) parser.add_argument( """--no_tpu""" , action="""store_true""" , help="""If set, run on CPU and don't try to initialize a TPU. Useful for debugging on non-TPU instances.""" , ) parser.add_argument( """--tpu_name""" , type=_SCREAMING_SNAKE_CASE , help="""Name of TPU resource to initialize. Should be blank on Colab, and 'local' on TPU VMs.""" , default="""local""" , ) parser.add_argument( """--tpu_zone""" , type=_SCREAMING_SNAKE_CASE , help="""Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes.""" , ) parser.add_argument( """--gcp_project""" , type=_SCREAMING_SNAKE_CASE , help="""Google cloud project name. Only used for non-Colab TPU nodes.""" ) parser.add_argument( """--bfloat16""" , action="""store_true""" , help="""Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU.""" , ) parser.add_argument( """--train_dataset""" , type=_SCREAMING_SNAKE_CASE , help="""Path to training dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--shuffle_buffer_size""" , type=_SCREAMING_SNAKE_CASE , default=2**18 , help="""Size of the shuffle buffer (in samples)""" , ) parser.add_argument( """--eval_dataset""" , type=_SCREAMING_SNAKE_CASE , help="""Path to evaluation dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--num_epochs""" , type=_SCREAMING_SNAKE_CASE , default=1 , help="""Number of epochs to train for.""" , ) parser.add_argument( """--learning_rate""" , type=_SCREAMING_SNAKE_CASE , default=1E-4 , help="""Learning rate to use for training.""" , ) parser.add_argument( """--weight_decay_rate""" , type=_SCREAMING_SNAKE_CASE , default=1E-3 , help="""Weight decay rate to use for training.""" , ) parser.add_argument( """--max_length""" , type=_SCREAMING_SNAKE_CASE , default=512 , help="""Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py""" , ) parser.add_argument( """--mlm_probability""" , type=_SCREAMING_SNAKE_CASE , default=0.15 , help="""Fraction of tokens to mask during training.""" , ) parser.add_argument("""--output_dir""" , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help="""Path to save model checkpoints to.""" ) parser.add_argument("""--hub_model_id""" , type=_SCREAMING_SNAKE_CASE , help="""Model ID to upload to on the Hugging Face Hub.""" ) snake_case_ = parser.parse_args() return args def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: try: if args.tpu_name: snake_case_ = tf.distribute.cluster_resolver.TPUClusterResolver( args.tpu_name , zone=args.tpu_zone , project=args.gcp_project ) else: snake_case_ = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: raise RuntimeError( """Couldn't connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or """ """--gcp_project. When running on a TPU VM, use --tpu_name local.""" ) tf.config.experimental_connect_to_cluster(_SCREAMING_SNAKE_CASE ) tf.tpu.experimental.initialize_tpu_system(_SCREAMING_SNAKE_CASE ) return tpu def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = 0 for file in file_list: snake_case_ = file.split("""/""" )[-1] snake_case_ = re.search(r"""-\d+-(\d+)\.tfrecord""" , _SCREAMING_SNAKE_CASE ).group(1 ) snake_case_ = int(_SCREAMING_SNAKE_CASE ) num_samples += sample_count return num_samples def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Union[str, Any]: snake_case_ = count_samples(_SCREAMING_SNAKE_CASE ) snake_case_ = tf.data.Dataset.from_tensor_slices(_SCREAMING_SNAKE_CASE ) if shuffle: snake_case_ = dataset.shuffle(len(_SCREAMING_SNAKE_CASE ) ) snake_case_ = tf.data.TFRecordDataset(_SCREAMING_SNAKE_CASE , num_parallel_reads=_SCREAMING_SNAKE_CASE ) # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here snake_case_ = dataset.apply(tf.data.experimental.assert_cardinality(_SCREAMING_SNAKE_CASE ) ) snake_case_ = dataset.map(_SCREAMING_SNAKE_CASE , num_parallel_calls=_SCREAMING_SNAKE_CASE ) if shuffle: assert shuffle_buffer_size is not None snake_case_ = dataset.shuffle(args.shuffle_buffer_size ) snake_case_ = dataset.batch(_SCREAMING_SNAKE_CASE , drop_remainder=_SCREAMING_SNAKE_CASE ) snake_case_ = dataset.map(_SCREAMING_SNAKE_CASE , num_parallel_calls=_SCREAMING_SNAKE_CASE ) snake_case_ = dataset.prefetch(_SCREAMING_SNAKE_CASE ) return dataset def _a ( _SCREAMING_SNAKE_CASE ) -> List[Any]: if not args.no_tpu: snake_case_ = initialize_tpu(_SCREAMING_SNAKE_CASE ) snake_case_ = tf.distribute.TPUStrategy(_SCREAMING_SNAKE_CASE ) else: snake_case_ = tf.distribute.OneDeviceStrategy(device="""/gpu:0""" ) if args.bfloataa: tf.keras.mixed_precision.set_global_policy("""mixed_bfloat16""" ) snake_case_ = AutoTokenizer.from_pretrained(args.tokenizer ) snake_case_ = AutoConfig.from_pretrained(args.pretrained_model_config ) snake_case_ = tokenizer.vocab_size snake_case_ = tf.io.gfile.glob(os.path.join(args.train_dataset , """*.tfrecord""" ) ) if not training_records: raise ValueError(f"""No .tfrecord files found in {args.train_dataset}.""" ) snake_case_ = tf.io.gfile.glob(os.path.join(args.eval_dataset , """*.tfrecord""" ) ) if not eval_records: raise ValueError(f"""No .tfrecord files found in {args.eval_dataset}.""" ) snake_case_ = count_samples(_SCREAMING_SNAKE_CASE ) snake_case_ = num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync) snake_case_ = steps_per_epoch * args.num_epochs with strategy.scope(): snake_case_ = TFAutoModelForMaskedLM.from_config(_SCREAMING_SNAKE_CASE ) model(model.dummy_inputs ) # Pass some dummy inputs through the model to ensure all the weights are built snake_case_ , snake_case_ = create_optimizer( num_train_steps=_SCREAMING_SNAKE_CASE , num_warmup_steps=total_train_steps // 20 , init_lr=args.learning_rate , weight_decay_rate=args.weight_decay_rate , ) # Transformers models compute the right loss for their task by default when labels are passed, and will # use this for training unless you specify your own loss function in compile(). model.compile(optimizer=_SCREAMING_SNAKE_CASE , metrics=["""accuracy"""] ) def decode_fn(_SCREAMING_SNAKE_CASE ): snake_case_ = { """input_ids""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), """attention_mask""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), } return tf.io.parse_single_example(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can # use their methods in our data pipeline. snake_case_ = DataCollatorForLanguageModeling( tokenizer=_SCREAMING_SNAKE_CASE , mlm_probability=args.mlm_probability , mlm=_SCREAMING_SNAKE_CASE , return_tensors="""tf""" ) def mask_with_collator(_SCREAMING_SNAKE_CASE ): # TF really needs an isin() function snake_case_ = ( ~tf.cast(batch["""attention_mask"""] , tf.bool ) | (batch["""input_ids"""] == tokenizer.cls_token_id) | (batch["""input_ids"""] == tokenizer.sep_token_id) ) snake_case_ , snake_case_ = data_collator.tf_mask_tokens( batch["""input_ids"""] , vocab_size=len(_SCREAMING_SNAKE_CASE ) , mask_token_id=tokenizer.mask_token_id , special_tokens_mask=_SCREAMING_SNAKE_CASE , ) return batch snake_case_ = args.per_replica_batch_size * strategy.num_replicas_in_sync snake_case_ = prepare_dataset( _SCREAMING_SNAKE_CASE , decode_fn=_SCREAMING_SNAKE_CASE , mask_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , shuffle=_SCREAMING_SNAKE_CASE , shuffle_buffer_size=args.shuffle_buffer_size , ) snake_case_ = prepare_dataset( _SCREAMING_SNAKE_CASE , decode_fn=_SCREAMING_SNAKE_CASE , mask_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , shuffle=_SCREAMING_SNAKE_CASE , ) snake_case_ = [] if args.hub_model_id: callbacks.append( PushToHubCallback(output_dir=args.output_dir , hub_model_id=args.hub_model_id , tokenizer=_SCREAMING_SNAKE_CASE ) ) model.fit( _SCREAMING_SNAKE_CASE , validation_data=_SCREAMING_SNAKE_CASE , epochs=args.num_epochs , callbacks=_SCREAMING_SNAKE_CASE , ) model.save_pretrained(args.output_dir ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = parse_args() main(args)
347
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) snake_case_ = {'configuration_beit': ['BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BeitConfig', 'BeitOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = ['BeitFeatureExtractor'] snake_case_ = ['BeitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'BEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BeitForImageClassification', 'BeitForMaskedImageModeling', 'BeitForSemanticSegmentation', 'BeitModel', 'BeitPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'FlaxBeitForImageClassification', 'FlaxBeitForMaskedImageModeling', 'FlaxBeitModel', 'FlaxBeitPreTrainedModel', ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
24
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float: if density <= 0: raise ValueError("""Impossible fluid density""" ) if bulk_modulus <= 0: raise ValueError("""Impossible bulk modulus""" ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
347
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase__ : str = { 'configuration_xlm_roberta': [ 'XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMRobertaConfig', 'XLMRobertaOnnxConfig', ], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[int] = ['XLMRobertaTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[Any] = ['XLMRobertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Tuple = [ 'XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLMRobertaForCausalLM', 'XLMRobertaForMaskedLM', 'XLMRobertaForMultipleChoice', 'XLMRobertaForQuestionAnswering', 'XLMRobertaForSequenceClassification', 'XLMRobertaForTokenClassification', 'XLMRobertaModel', 'XLMRobertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Tuple = [ 'TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXLMRobertaForCausalLM', 'TFXLMRobertaForMaskedLM', 'TFXLMRobertaForMultipleChoice', 'TFXLMRobertaForQuestionAnswering', 'TFXLMRobertaForSequenceClassification', 'TFXLMRobertaForTokenClassification', 'TFXLMRobertaModel', 'TFXLMRobertaPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[int] = [ 'FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'FlaxXLMRobertaForMaskedLM', 'FlaxXLMRobertaForCausalLM', 'FlaxXLMRobertaForMultipleChoice', 'FlaxXLMRobertaForQuestionAnswering', 'FlaxXLMRobertaForSequenceClassification', 'FlaxXLMRobertaForTokenClassification', 'FlaxXLMRobertaModel', 'FlaxXLMRobertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaConfig, XLMRobertaOnnxConfig, ) try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta import XLMRobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta_fast import XLMRobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaForCausalLM, XLMRobertaForMaskedLM, XLMRobertaForMultipleChoice, XLMRobertaForQuestionAnswering, XLMRobertaForSequenceClassification, XLMRobertaForTokenClassification, XLMRobertaModel, XLMRobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm_roberta import ( TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMRobertaForCausalLM, TFXLMRobertaForMaskedLM, TFXLMRobertaForMultipleChoice, TFXLMRobertaForQuestionAnswering, TFXLMRobertaForSequenceClassification, TFXLMRobertaForTokenClassification, TFXLMRobertaModel, TFXLMRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xlm_roberta import ( FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxXLMRobertaForCausalLM, FlaxXLMRobertaForMaskedLM, FlaxXLMRobertaForMultipleChoice, FlaxXLMRobertaForQuestionAnswering, FlaxXLMRobertaForSequenceClassification, FlaxXLMRobertaForTokenClassification, FlaxXLMRobertaModel, FlaxXLMRobertaPreTrainedModel, ) else: import sys UpperCAmelCase__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
25
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if num < 0: return False snake_case_ = num snake_case_ = 0 while num > 0: snake_case_ = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
347
0
# Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position _snake_case = "2.13.1" import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse("3.7"): raise ImportWarning( "To use `datasets`, Python>=3.7 is required, and the current version of Python doesn't match this condition." ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( "To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn't match this condition.\n" "If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`." ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip _snake_case = concatenate_datasets _snake_case = DownloadConfig _snake_case = DownloadManager _snake_case = DownloadMode _snake_case = DownloadConfig _snake_case = DownloadMode _snake_case = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
26
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin __SCREAMING_SNAKE_CASE : Tuple = get_tests_dir('fixtures/test_sentencepiece_bpe_char.model') @require_sentencepiece @require_tokenizers class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Tuple = SpeechTaTokenizer __lowercase: int = False __lowercase: List[str] = True def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing snake_case_ = SpeechTaTokenizer(UpperCAmelCase_ ) snake_case_ = AddedToken("""<mask>""" , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) snake_case_ = mask_token tokenizer.add_special_tokens({"""mask_token""": mask_token} ) tokenizer.add_tokens(["""<ctc_blank>"""] ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = """this is a test""" snake_case_ = """this is a test""" return input_text, output_text def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Any=False , UpperCAmelCase_ : Tuple=20 , UpperCAmelCase_ : Dict=5 ) ->List[Any]: """simple docstring""" snake_case_ , snake_case_ = self.get_input_output_texts(UpperCAmelCase_ ) snake_case_ = tokenizer.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ ) snake_case_ = tokenizer.decode(UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ ) return text, ids def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" snake_case_ = """<pad>""" snake_case_ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_ ) , UpperCAmelCase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_ ) , UpperCAmelCase_ ) def lowerCAmelCase ( self : int ) ->str: """simple docstring""" snake_case_ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-4] , """œ""" ) self.assertEqual(vocab_keys[-2] , """<mask>""" ) self.assertEqual(vocab_keys[-1] , """<ctc_blank>""" ) self.assertEqual(len(UpperCAmelCase_ ) , 81 ) def lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = self.get_tokenizers(do_lower_case=UpperCAmelCase_ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case_ = tokenizer.vocab_size snake_case_ = len(UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) snake_case_ = ["""aaaaa bbbbbb""", """cccccccccdddddddd"""] snake_case_ = tokenizer.add_tokens(UpperCAmelCase_ ) snake_case_ = tokenizer.vocab_size snake_case_ = len(UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , 0 ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , len(UpperCAmelCase_ ) ) self.assertEqual(UpperCAmelCase_ , all_size + len(UpperCAmelCase_ ) ) snake_case_ = tokenizer.encode("""aaaaa bbbbbb low cccccccccdddddddd l""" , add_special_tokens=UpperCAmelCase_ ) self.assertGreaterEqual(len(UpperCAmelCase_ ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) snake_case_ = {"""eos_token""": """>>>>|||<||<<|<<""", """pad_token""": """<<<<<|||>|>>>>|>"""} snake_case_ = tokenizer.add_special_tokens(UpperCAmelCase_ ) snake_case_ = tokenizer.vocab_size snake_case_ = len(UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , 0 ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , len(UpperCAmelCase_ ) ) self.assertEqual(UpperCAmelCase_ , all_size_a + len(UpperCAmelCase_ ) ) snake_case_ = tokenizer.encode( """>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l""" , add_special_tokens=UpperCAmelCase_ ) self.assertGreaterEqual(len(UpperCAmelCase_ ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" pass def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" pass def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = self.get_tokenizer() snake_case_ = tokenizer.tokenize("""This is a test""" ) # fmt: off self.assertListEqual(UpperCAmelCase_ , [SPIECE_UNDERLINE, """T""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """a""", SPIECE_UNDERLINE, """t""", """e""", """s""", """t"""] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) snake_case_ = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( UpperCAmelCase_ , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """92000""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) snake_case_ = tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) # fmt: off self.assertListEqual(UpperCAmelCase_ , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on snake_case_ = tokenizer.convert_ids_to_tokens(UpperCAmelCase_ ) self.assertListEqual( UpperCAmelCase_ , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """<unk>""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) @slow def lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" snake_case_ = [ """Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides """ """general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural """ """Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained """ """models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.""", """BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly """ """conditioning on both left and right context in all layers.""", """The quick brown fox jumps over the lazy dog.""", ] # fmt: off snake_case_ = { """input_ids""": [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], """attention_mask""": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase_ , model_name="""microsoft/speecht5_asr""" , revision="""c5ef64c71905caeccde0e4462ef3f9077224c524""" , sequences=UpperCAmelCase_ , )
347
0
'''simple docstring''' import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __lowercase : str = logging.get_logger(__name__) __lowercase : int = {'vocab_file': 'spiece.model'} __lowercase : int = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } __lowercase : Union[str, Any] = { 'albert-base-v1': 5_12, 'albert-large-v1': 5_12, 'albert-xlarge-v1': 5_12, 'albert-xxlarge-v1': 5_12, 'albert-base-v2': 5_12, 'albert-large-v2': 5_12, 'albert-xlarge-v2': 5_12, 'albert-xxlarge-v2': 5_12, } __lowercase : Any = '▁' class __UpperCamelCase ( lowerCAmelCase_ ): A_ = VOCAB_FILES_NAMES A_ = PRETRAINED_VOCAB_FILES_MAP A_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , __a , __a=True , __a=True , __a=False , __a="[CLS]" , __a="[SEP]" , __a="<unk>" , __a="[SEP]" , __a="<pad>" , __a="[CLS]" , __a="[MASK]" , __a = None , **__a , ): '''simple docstring''' __a : List[str] = ( AddedToken(__a , lstrip=__a , rstrip=__a , normalized=__a ) if isinstance(__a , __a ) else mask_token ) __a : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__a , remove_space=__a , keep_accents=__a , bos_token=__a , eos_token=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) __a : Any = do_lower_case __a : Any = remove_space __a : Optional[Any] = keep_accents __a : Union[str, Any] = vocab_file __a : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__a ) @property def __UpperCAmelCase ( self ): '''simple docstring''' return len(self.sp_model ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = {self.convert_ids_to_tokens(__a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): '''simple docstring''' __a : List[Any] = self.__dict__.copy() __a : List[str] = None return state def __setstate__( self , __a ): '''simple docstring''' __a : Optional[Any] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __a : Optional[Any] = {} __a : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' if self.remove_space: __a : Union[str, Any] = ' '.join(inputs.strip().split() ) else: __a : Dict = inputs __a : Optional[Any] = outputs.replace('``' , '"' ).replace('\'\'' , '"' ) if not self.keep_accents: __a : Optional[Any] = unicodedata.normalize('NFKD' , __a ) __a : List[str] = ''.join([c for c in outputs if not unicodedata.combining(__a )] ) if self.do_lower_case: __a : Tuple = outputs.lower() return outputs def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Dict = self.preprocess_text(__a ) __a : Tuple = self.sp_model.encode(__a , out_type=__a ) __a : List[Any] = [] for piece in pieces: if len(__a ) > 1 and piece[-1] == str(',' ) and piece[-2].isdigit(): __a : List[str] = self.sp_model.EncodeAsPieces(piece[:-1].replace(__a , '' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: __a : int = cur_pieces[1:] else: __a : str = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__a ) else: new_pieces.append(__a ) return new_pieces def __UpperCAmelCase ( self , __a ): '''simple docstring''' return self.sp_model.PieceToId(__a ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' return self.sp_model.IdToPiece(__a ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Optional[int] = [] __a : List[Any] = '' __a : int = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__a ) + token __a : List[Any] = True __a : Union[str, Any] = [] else: current_sub_tokens.append(__a ) __a : Union[str, Any] = False out_string += self.sp_model.decode(__a ) return out_string.strip() def __UpperCAmelCase ( self , __a , __a = None ): '''simple docstring''' __a : Optional[int] = [self.sep_token_id] __a : Optional[int] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __UpperCAmelCase ( self , __a , __a = None , __a = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a ) if token_ids_a is not None: return [1] + ([0] * len(__a )) + [1] + ([0] * len(__a )) + [1] return [1] + ([0] * len(__a )) + [1] def __UpperCAmelCase ( self , __a , __a = None ): '''simple docstring''' __a : Dict = [self.sep_token_id] __a : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __UpperCAmelCase ( self , __a , __a = None ): '''simple docstring''' if not os.path.isdir(__a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __a : Tuple = os.path.join( __a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __a ) elif not os.path.isfile(self.vocab_file ): with open(__a , 'wb' ) as fi: __a : int = self.sp_model.serialized_model_proto() fi.write(__a ) return (out_vocab_file,)
27
"""simple docstring""" import datasets __SCREAMING_SNAKE_CASE : Tuple = '\\n@InProceedings{conneau2018xnli,\n author = "Conneau, Alexis\n and Rinott, Ruty\n and Lample, Guillaume\n and Williams, Adina\n and Bowman, Samuel R.\n and Schwenk, Holger\n and Stoyanov, Veselin",\n title = "XNLI: Evaluating Cross-lingual Sentence Representations",\n booktitle = "Proceedings of the 2018 Conference on Empirical Methods\n in Natural Language Processing",\n year = "2018",\n publisher = "Association for Computational Linguistics",\n location = "Brussels, Belgium",\n}\n' __SCREAMING_SNAKE_CASE : Dict = '\\nXNLI is a subset of a few thousand examples from MNLI which has been translated\ninto a 14 different languages (some low-ish resource). As with MNLI, the goal is\nto predict textual entailment (does sentence A imply/contradict/neither sentence\nB) and is a classification task (given two sentences, predict one of three\nlabels).\n' __SCREAMING_SNAKE_CASE : List[str] = '\nComputes XNLI score which is just simple accuracy.\nArgs:\n predictions: Predicted labels.\n references: Ground truth labels.\nReturns:\n \'accuracy\': accuracy\nExamples:\n\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> xnli_metric = datasets.load_metric("xnli")\n >>> results = xnli_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n' def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: return (preds == labels).mean() @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __A (datasets.Metric): '''simple docstring''' def lowerCAmelCase ( self : str ) ->Any: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), """references""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), } ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" , ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" return {"accuracy": simple_accuracy(UpperCAmelCase_ , UpperCAmelCase_ )}
347
0
'''simple docstring''' from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging if is_vision_available(): import PIL if is_torch_available(): import torch _lowerCamelCase : Dict = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" _SCREAMING_SNAKE_CASE = ["""pixel_values"""] def __init__( self : Optional[Any] , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 2_5_5 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = True , **UpperCamelCase__ : Tuple , ): """simple docstring""" super().__init__(**UpperCamelCase__ ) UpperCamelCase = size if size is not None else {'shortest_edge': 2_2_4} UpperCamelCase = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) UpperCamelCase = crop_size if crop_size is not None else {'height': 2_5_6, 'width': 2_5_6} UpperCamelCase = get_size_dict(UpperCamelCase__ , param_name='crop_size' ) UpperCamelCase = do_resize UpperCamelCase = size UpperCamelCase = resample UpperCamelCase = do_rescale UpperCamelCase = rescale_factor UpperCamelCase = do_center_crop UpperCamelCase = crop_size UpperCamelCase = do_flip_channel_order def A ( self : List[Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : PILImageResampling = PIL.Image.BILINEAR , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Union[str, Any] , ): """simple docstring""" UpperCamelCase = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) if "shortest_edge" not in size: raise ValueError(f"""The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}""" ) UpperCamelCase = get_resize_output_image_size(UpperCamelCase__ , size=size['shortest_edge'] , default_to_square=UpperCamelCase__ ) return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def A ( self : Dict , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : int , ): """simple docstring""" UpperCamelCase = get_size_dict(UpperCamelCase__ ) if "height" not in size or "width" not in size: raise ValueError(f"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}""" ) return center_crop(UpperCamelCase__ , size=(size['height'], size['width']) , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def A ( self : Optional[int] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[int, float] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Any , ): """simple docstring""" return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def A ( self : List[Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None ): """simple docstring""" return flip_channel_order(UpperCamelCase__ , data_format=UpperCamelCase__ ) def A ( self : List[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : float = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCamelCase__ : Union[str, Any] , ): """simple docstring""" UpperCamelCase = do_resize if do_resize is not None else self.do_resize UpperCamelCase = resample if resample is not None else self.resample UpperCamelCase = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) UpperCamelCase = size if size is not None else self.size UpperCamelCase = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) UpperCamelCase = crop_size if crop_size is not None else self.crop_size UpperCamelCase = get_size_dict(UpperCamelCase__ , param_name='crop_size' ) UpperCamelCase = make_list_of_images(UpperCamelCase__ ) if not valid_images(UpperCamelCase__ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) # All transformations expect numpy arrays. UpperCamelCase = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: UpperCamelCase = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_center_crop: UpperCamelCase = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images] if do_rescale: UpperCamelCase = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: UpperCamelCase = [self.flip_channel_order(image=UpperCamelCase__ ) for image in images] UpperCamelCase = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] UpperCamelCase = {'pixel_values': images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ ) def A ( self : Optional[Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : List[Tuple] = None ): """simple docstring""" UpperCamelCase = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCamelCase__ ) != len(UpperCamelCase__ ): raise ValueError( 'Make sure that you pass in as many target sizes as the batch dimension of the logits' ) if is_torch_tensor(UpperCamelCase__ ): UpperCamelCase = target_sizes.numpy() UpperCamelCase = [] for idx in range(len(UpperCamelCase__ ) ): UpperCamelCase = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='bilinear' , align_corners=UpperCamelCase__ ) UpperCamelCase = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCamelCase__ ) else: UpperCamelCase = logits.argmax(dim=1 ) UpperCamelCase = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
28
"""simple docstring""" from ..utils import DummyObject, requires_backends class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : List[str] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""sentencepiece"""] def __init__( self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Tuple ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : Any , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : List[Any] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Dict = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[str] = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : int ) ->List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Tuple , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Dict ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Union[str, Any] ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[Any] = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : Optional[Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""sentencepiece"""] def __init__( self : Optional[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : str , **UpperCAmelCase_ : int ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Optional[int] , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Tuple = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : List[Any] ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : List[str] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Tuple = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Optional[Any] ) ->str: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Optional[Any] ) ->int: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = ["""sentencepiece"""] def __init__( self : Optional[Any] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : Optional[Any] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Dict ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : List[str] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any] ) ->List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : Any , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Optional[Any] ) ->List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Dict = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Union[str, Any] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Optional[int] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = ["""sentencepiece"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : str ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""sentencepiece"""] def __init__( self : Tuple , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Optional[int] ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Dict = ["""sentencepiece"""] def __init__( self : Optional[int] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : List[str] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Optional[int] ) ->Any: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[str] = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Union[str, Any] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Optional[int] ) ->str: """simple docstring""" requires_backends(self , ["""sentencepiece"""] )
347
0
import multiprocessing import os from typing import BinaryIO, Optional, Union import fsspec from .. import Dataset, Features, NamedSplit, config from ..formatting import query_table from ..packaged_modules.json.json import Json from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class lowerCamelCase (_snake_case ): '''simple docstring''' def __init__( self , _UpperCamelCase , _UpperCamelCase = None , _UpperCamelCase = None , _UpperCamelCase = None , _UpperCamelCase = False , _UpperCamelCase = False , _UpperCamelCase = None , _UpperCamelCase = None , **_UpperCamelCase , ) -> Optional[int]: super().__init__( _UpperCamelCase , split=_UpperCamelCase , features=_UpperCamelCase , cache_dir=_UpperCamelCase , keep_in_memory=_UpperCamelCase , streaming=_UpperCamelCase , num_proc=_UpperCamelCase , **_UpperCamelCase , ) UpperCAmelCase_ : Any = field UpperCAmelCase_ : Tuple = path_or_paths if isinstance(_UpperCamelCase , _UpperCamelCase ) else {self.split: path_or_paths} UpperCAmelCase_ : int = Json( cache_dir=_UpperCamelCase , data_files=_UpperCamelCase , features=_UpperCamelCase , field=_UpperCamelCase , **_UpperCamelCase , ) def __UpperCAmelCase ( self ) -> List[Any]: # Build iterable dataset if self.streaming: UpperCAmelCase_ : Optional[Any] = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: UpperCAmelCase_ : Optional[int] = None UpperCAmelCase_ : List[Any] = None UpperCAmelCase_ : Any = None UpperCAmelCase_ : Any = None self.builder.download_and_prepare( download_config=_UpperCamelCase , download_mode=_UpperCamelCase , verification_mode=_UpperCamelCase , base_path=_UpperCamelCase , num_proc=self.num_proc , ) UpperCAmelCase_ : List[str] = self.builder.as_dataset( split=self.split , verification_mode=_UpperCamelCase , in_memory=self.keep_in_memory ) return dataset class lowerCamelCase : '''simple docstring''' def __init__( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = None , _UpperCamelCase = None , **_UpperCamelCase , ) -> Union[str, Any]: if num_proc is not None and num_proc <= 0: raise ValueError(f"num_proc {num_proc} must be an integer > 0." ) UpperCAmelCase_ : List[Any] = dataset UpperCAmelCase_ : Optional[int] = path_or_buf UpperCAmelCase_ : List[str] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE UpperCAmelCase_ : str = num_proc UpperCAmelCase_ : Optional[int] = 'utf-8' UpperCAmelCase_ : Optional[int] = to_json_kwargs def __UpperCAmelCase ( self ) -> int: UpperCAmelCase_ : Dict = self.to_json_kwargs.pop('path_or_buf' , _UpperCamelCase ) UpperCAmelCase_ : Union[str, Any] = self.to_json_kwargs.pop('orient' , 'records' ) UpperCAmelCase_ : Any = self.to_json_kwargs.pop('lines' , True if orient == 'records' else False ) UpperCAmelCase_ : str = self.to_json_kwargs.pop('index' , False if orient in ['split', 'table'] else True ) UpperCAmelCase_ : List[str] = self.to_json_kwargs.pop('compression' , _UpperCamelCase ) if compression not in [None, "infer", "gzip", "bz2", "xz"]: raise NotImplementedError(f"`datasets` currently does not support {compression} compression" ) if isinstance(self.path_or_buf , (str, bytes, os.PathLike) ): with fsspec.open(self.path_or_buf , 'wb' , compression=_UpperCamelCase ) as buffer: UpperCAmelCase_ : Any = self._write(file_obj=_UpperCamelCase , orient=_UpperCamelCase , lines=_UpperCamelCase , index=_UpperCamelCase , **self.to_json_kwargs ) else: if compression: raise NotImplementedError( f"The compression parameter is not supported when writing to a buffer, but compression={compression}" ' was passed. Please provide a local path instead.' ) UpperCAmelCase_ : Tuple = self._write( file_obj=self.path_or_buf , orient=_UpperCamelCase , lines=_UpperCamelCase , index=_UpperCamelCase , **self.to_json_kwargs ) return written def __UpperCAmelCase ( self , _UpperCamelCase ) -> List[Any]: UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[str] = args UpperCAmelCase_ : List[str] = query_table( table=self.dataset.data , key=slice(_UpperCamelCase , offset + self.batch_size ) , indices=self.dataset._indices , ) UpperCAmelCase_ : str = batch.to_pandas().to_json( path_or_buf=_UpperCamelCase , orient=_UpperCamelCase , lines=_UpperCamelCase , index=_UpperCamelCase , **_UpperCamelCase ) if not json_str.endswith('\n' ): json_str += "\n" return json_str.encode(self.encoding ) def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , **_UpperCamelCase , ) -> int: UpperCAmelCase_ : Any = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit='ba' , disable=not logging.is_progress_bar_enabled() , desc='Creating json from Arrow format' , ): UpperCAmelCase_ : List[Any] = self._batch_json((offset, orient, lines, index, to_json_kwargs) ) written += file_obj.write(_UpperCamelCase ) else: UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for json_str in logging.tqdm( pool.imap( self._batch_json , [(offset, orient, lines, index, to_json_kwargs) for offset in range(0 , _UpperCamelCase , _UpperCamelCase )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit='ba' , disable=not logging.is_progress_bar_enabled() , desc='Creating json from Arrow format' , ): written += file_obj.write(_UpperCamelCase ) return written
29
"""simple docstring""" import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor __SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) class __A (snake_case__): '''simple docstring''' def __init__( self : str , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int ) ->None: """simple docstring""" warnings.warn( """The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use MobileViTImageProcessor instead.""" , UpperCAmelCase_ , ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ )
347
0
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('TEST_SAGEMAKER' , 'False' ) ) is not True , reason='Skipping test because should only be run when releasing minor transformers version' , ) @pytest.mark.usefixtures('sm_env' ) @parameterized_class( [ { 'framework': 'pytorch', 'script': 'run_glue_model_parallelism.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1_600, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, { 'framework': 'pytorch', 'script': 'run_glue.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1_600, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, ] ) class lowercase__( unittest.TestCase ): """simple docstring""" def _lowercase ( self : str ) -> str: if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=SCREAMING_SNAKE_CASE_ , ) assert hasattr(self , '''env''' ) def _lowercase ( self : int , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Optional[int]: # configuration for running training on smdistributed Model Parallel lowercase_ = { '''enabled''': True, '''processes_per_host''': 8, } lowercase_ = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } lowercase_ = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} lowercase_ = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=SCREAMING_SNAKE_CASE_ , instance_type=self.instance_type , debugger_hook_config=SCREAMING_SNAKE_CASE_ , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 5_0_0, } , metric_definitions=self.env.metric_definitions , distribution=SCREAMING_SNAKE_CASE_ , py_version='''py36''' , ) def _lowercase ( self : int , SCREAMING_SNAKE_CASE_ : Tuple ) -> List[str]: TrainingJobAnalytics(SCREAMING_SNAKE_CASE_ ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def _lowercase ( self : int , SCREAMING_SNAKE_CASE_ : Any ) -> Any: # create estimator lowercase_ = self.create_estimator(SCREAMING_SNAKE_CASE_ ) # run training estimator.fit() # result dataframe lowercase_ = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis lowercase_ = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) lowercase_ = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping lowercase_ = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 9_9_9_9_9_9 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'''{estimator.latest_training_job.name}.json''' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , SCREAMING_SNAKE_CASE_ )
30
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Any: snake_case_ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"""blocks.{i}.norm1.weight""", f"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """vit.embeddings.cls_token"""), ("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" snake_case_ = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) return rename_keys def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Tuple: for i in range(config.num_hidden_layers ): if base_model: snake_case_ = """""" else: snake_case_ = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case_ = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" ) snake_case_ = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict snake_case_ = in_proj_weight[ : config.hidden_size, : ] snake_case_ = in_proj_bias[: config.hidden_size] snake_case_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case_ = in_proj_weight[ -config.hidden_size :, : ] snake_case_ = in_proj_bias[-config.hidden_size :] def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: snake_case_ = dct.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = val def _a ( ) -> Any: snake_case_ = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = ViTConfig() snake_case_ = False # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size if vit_name[-5:] == "in21k": snake_case_ = True snake_case_ = int(vit_name[-12:-10] ) snake_case_ = int(vit_name[-9:-6] ) else: snake_case_ = 1_000 snake_case_ = """huggingface/label-files""" snake_case_ = """imagenet-1k-id2label.json""" snake_case_ = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) snake_case_ = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} snake_case_ = idalabel snake_case_ = {v: k for k, v in idalabel.items()} snake_case_ = int(vit_name[-6:-4] ) snake_case_ = int(vit_name[-3:] ) # size of the architecture if "deit" in vit_name: if vit_name[9:].startswith("""tiny""" ): snake_case_ = 192 snake_case_ = 768 snake_case_ = 12 snake_case_ = 3 elif vit_name[9:].startswith("""small""" ): snake_case_ = 384 snake_case_ = 1_536 snake_case_ = 12 snake_case_ = 6 else: pass else: if vit_name[4:].startswith("""small""" ): snake_case_ = 768 snake_case_ = 2_304 snake_case_ = 8 snake_case_ = 8 elif vit_name[4:].startswith("""base""" ): pass elif vit_name[4:].startswith("""large""" ): snake_case_ = 1_024 snake_case_ = 4_096 snake_case_ = 24 snake_case_ = 16 elif vit_name[4:].startswith("""huge""" ): snake_case_ = 1_280 snake_case_ = 5_120 snake_case_ = 32 snake_case_ = 16 # load original model from timm snake_case_ = timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ) timm_model.eval() # load state_dict of original model, remove and rename some keys snake_case_ = timm_model.state_dict() if base_model: remove_classification_head_(_SCREAMING_SNAKE_CASE ) snake_case_ = create_rename_keys(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for src, dest in rename_keys: rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) read_in_q_k_v(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load HuggingFace model if vit_name[-5:] == "in21k": snake_case_ = ViTModel(_SCREAMING_SNAKE_CASE ).eval() else: snake_case_ = ViTForImageClassification(_SCREAMING_SNAKE_CASE ).eval() model.load_state_dict(_SCREAMING_SNAKE_CASE ) # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor if "deit" in vit_name: snake_case_ = DeiTImageProcessor(size=config.image_size ) else: snake_case_ = ViTImageProcessor(size=config.image_size ) snake_case_ = image_processor(images=prepare_img() , return_tensors="""pt""" ) snake_case_ = encoding["""pixel_values"""] snake_case_ = model(_SCREAMING_SNAKE_CASE ) if base_model: snake_case_ = timm_model.forward_features(_SCREAMING_SNAKE_CASE ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(_SCREAMING_SNAKE_CASE , outputs.pooler_output , atol=1E-3 ) else: snake_case_ = timm_model(_SCREAMING_SNAKE_CASE ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_SCREAMING_SNAKE_CASE , outputs.logits , atol=1E-3 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(f"""Saving model {vit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--vit_name', default='vit_base_patch16_224', type=str, help='Name of the ViT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) __SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
347
0
'''simple docstring''' # Function to print upper half of diamond (pyramid) def UpperCamelCase_ ( _UpperCAmelCase : Tuple ) -> Dict: """simple docstring""" for i in range(0 , _UpperCAmelCase ): for _ in range(0 , n - i - 1 ): # printing spaces print(" " , end="" ) for _ in range(0 , i + 1 ): # printing stars print("* " , end="" ) print() def UpperCamelCase_ ( _UpperCAmelCase : Optional[Any] ) -> List[Any]: """simple docstring""" for i in range(_UpperCAmelCase , 0 , -1 ): for _ in range(_UpperCAmelCase , 0 , -1 ): # printing stars print("* " , end="" ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(" " , end="" ) def UpperCamelCase_ ( _UpperCAmelCase : Tuple ) -> Dict: """simple docstring""" if n <= 0: print(" ... .... nothing printing :(" ) return floyd(_UpperCAmelCase ) # upper half reverse_floyd(_UpperCAmelCase ) # lower half if __name__ == "__main__": print(R"""| /\ | |- | |- |--| |\ /| |-""") print(R"""|/ \| |- |_ |_ |__| | \/ | |_""") __SCREAMING_SNAKE_CASE : str = 1 while K: __SCREAMING_SNAKE_CASE : Tuple = int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) __SCREAMING_SNAKE_CASE : Any = int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
31
"""simple docstring""" import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __A (unittest.TestCase): '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple=13 , UpperCAmelCase_ : List[Any]=7 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Dict=99 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : Tuple=5 , UpperCAmelCase_ : Union[str, Any]=4 , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : int="gelu" , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : Dict=512 , UpperCAmelCase_ : Optional[Any]=16 , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : str=0.02 , UpperCAmelCase_ : str=4 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_attention_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_choices def lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_attention_mask: snake_case_ = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = 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 , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Union[str, Any] = True __lowercase: int = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" snake_case_ = FlaxRoFormerModelTester(self ) @slow def lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=UpperCAmelCase_ ) snake_case_ = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCAmelCase_ ) @require_flax class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" snake_case_ = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) snake_case_ = jnp.array([[0, 1, 2, 3, 4, 5]] ) snake_case_ = model(UpperCAmelCase_ )[0] snake_case_ = 50_000 snake_case_ = (1, 6, vocab_size) self.assertEqual(output.shape , UpperCAmelCase_ ) snake_case_ = jnp.array( [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) )
347
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase_ : List[str] = logging.get_logger(__name__) UpperCAmelCase_ : Optional[Any] = { 'microsoft/table-transformer-detection': ( 'https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json' ), } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : int = '''table-transformer''' snake_case__ : Union[str, Any] = ['''past_key_values'''] snake_case__ : Optional[Any] = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : str=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : str=1_0_0 , SCREAMING_SNAKE_CASE__ : Optional[Any]=6 , SCREAMING_SNAKE_CASE__ : List[str]=2_0_4_8 , SCREAMING_SNAKE_CASE__ : List[str]=8 , SCREAMING_SNAKE_CASE__ : Dict=6 , SCREAMING_SNAKE_CASE__ : Tuple=2_0_4_8 , SCREAMING_SNAKE_CASE__ : List[str]=8 , SCREAMING_SNAKE_CASE__ : List[str]=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.0 , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : Optional[Any]="relu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=2_5_6 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.0 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : Tuple=1.0 , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : List[Any]="sine" , SCREAMING_SNAKE_CASE__ : Dict="resnet50" , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Dict=1 , SCREAMING_SNAKE_CASE__ : int=5 , SCREAMING_SNAKE_CASE__ : Dict=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=1 , SCREAMING_SNAKE_CASE__ : int=1 , SCREAMING_SNAKE_CASE__ : Any=5 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.1 , **SCREAMING_SNAKE_CASE__ : int , ) -> Tuple: if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) a_ : Dict = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): a_ : int = backbone_config.get('model_type' ) a_ : Any = CONFIG_MAPPING[backbone_model_type] a_ : Optional[int] = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) # set timm attributes to None a_ , a_ , a_ : Optional[int] = None, None, None a_ : Union[str, Any] = use_timm_backbone a_ : str = backbone_config a_ : str = num_channels a_ : Tuple = num_queries a_ : int = d_model a_ : Optional[int] = encoder_ffn_dim a_ : str = encoder_layers a_ : Optional[Any] = encoder_attention_heads a_ : Any = decoder_ffn_dim a_ : int = decoder_layers a_ : Dict = decoder_attention_heads a_ : Union[str, Any] = dropout a_ : Dict = attention_dropout a_ : Dict = activation_dropout a_ : Optional[Any] = activation_function a_ : List[str] = init_std a_ : Any = init_xavier_std a_ : Union[str, Any] = encoder_layerdrop a_ : Optional[int] = decoder_layerdrop a_ : Union[str, Any] = encoder_layers a_ : Dict = auxiliary_loss a_ : str = position_embedding_type a_ : Union[str, Any] = backbone a_ : Any = use_pretrained_backbone a_ : List[str] = dilation # Hungarian matcher a_ : Tuple = class_cost a_ : Optional[Any] = bbox_cost a_ : Any = giou_cost # Loss coefficients a_ : Optional[Any] = mask_loss_coefficient a_ : Union[str, Any] = dice_loss_coefficient a_ : Dict = bbox_loss_coefficient a_ : List[Any] = giou_loss_coefficient a_ : str = eos_coefficient super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def SCREAMING_SNAKE_CASE ( self : str ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self : str ) -> int: return self.d_model class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : int = version.parse('''1.11''' ) @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def SCREAMING_SNAKE_CASE ( self : Any ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE ( self : int ) -> int: return 1_2
32
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> bool: snake_case_ = get_failure_array(_SCREAMING_SNAKE_CASE ) # 2) Step through text searching for pattern snake_case_ , snake_case_ = 0, 0 # index into text, pattern while i < len(_SCREAMING_SNAKE_CASE ): if pattern[j] == text[i]: if j == (len(_SCREAMING_SNAKE_CASE ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: snake_case_ = failure[j - 1] continue i += 1 return False def _a ( _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = [0] snake_case_ = 0 snake_case_ = 1 while j < len(_SCREAMING_SNAKE_CASE ): if pattern[i] == pattern[j]: i += 1 elif i > 0: snake_case_ = failure[i - 1] continue j += 1 failure.append(_SCREAMING_SNAKE_CASE ) return failure if __name__ == "__main__": # Test 1) __SCREAMING_SNAKE_CASE : Optional[int] = 'abc1abc12' __SCREAMING_SNAKE_CASE : Optional[int] = 'alskfjaldsabc1abc1abc12k23adsfabcabc' __SCREAMING_SNAKE_CASE : List[str] = 'alskfjaldsk23adsfabcabc' assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) __SCREAMING_SNAKE_CASE : int = 'ABABX' __SCREAMING_SNAKE_CASE : Optional[Any] = 'ABABZABABYABABX' assert kmp(pattern, text) # Test 3) __SCREAMING_SNAKE_CASE : Any = 'AAAB' __SCREAMING_SNAKE_CASE : List[Any] = 'ABAAAAAB' assert kmp(pattern, text) # Test 4) __SCREAMING_SNAKE_CASE : Optional[int] = 'abcdabcy' __SCREAMING_SNAKE_CASE : str = 'abcxabcdabxabcdabcdabcy' assert kmp(pattern, text) # Test 5) __SCREAMING_SNAKE_CASE : Any = 'aabaabaaa' assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
347
0
"""simple docstring""" import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() __A : List[Any] = 2 class _UpperCAmelCase : def __init__( self : Tuple , *, # begin keyword-only arguments A : Tuple="<s>" , A : List[str]="<pad>" , A : Optional[Any]="</s>" , A : str="<unk>" , A : int=None , ) -> Union[str, Any]: lowercase_ , lowercase_ , lowercase_ , lowercase_ : List[str] = bos, unk, pad, eos lowercase_ : Tuple = [] lowercase_ : Union[str, Any] = [] lowercase_ : Dict = {} lowercase_ : List[Any] = self.add_symbol(A ) lowercase_ : Optional[Any] = self.add_symbol(A ) lowercase_ : Optional[Any] = self.add_symbol(A ) lowercase_ : str = self.add_symbol(A ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(A ) lowercase_ : int = len(self.symbols ) def __eq__( self : str , A : Tuple ) -> Any: return self.indices == other.indices def __getitem__( self : int , A : Tuple ) -> Any: if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : Any ) -> Union[str, Any]: return len(self.symbols ) def __contains__( self : Optional[Any] , A : Optional[int] ) -> Dict: return sym in self.indices @classmethod def A ( cls : Optional[int] , A : Dict ) -> Any: lowercase_ : Any = cls() d.add_from_file(A ) return d def A ( self : List[Any] , A : int , A : List[Any]=1 , A : List[str]=False ) -> Dict: if word in self.indices and not overwrite: lowercase_ : Optional[int] = self.indices[word] lowercase_ : Tuple = self.count[idx] + n return idx else: lowercase_ : Dict = len(self.symbols ) lowercase_ : int = idx self.symbols.append(A ) self.count.append(A ) return idx def A ( self : int , A : Tuple ) -> List[str]: return 0 def A ( self : str , A : str ) -> Tuple: if isinstance(A , A ): try: with open(A , '''r''' , encoding='''utf-8''' ) as fd: self.add_from_file(A ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception('''Incorrect encoding detected in {}, please rebuild the dataset'''.format(A ) ) return lowercase_ : Any = f.readlines() lowercase_ : int = self._load_meta(A ) for line in lines[indices_start_line:]: try: lowercase_ , lowercase_ : Any = line.rstrip().rsplit(''' ''' , 1 ) if field == "#fairseq:overwrite": lowercase_ : str = True lowercase_ , lowercase_ : Union[str, Any] = line.rsplit(''' ''' , 1 ) else: lowercase_ : Tuple = False lowercase_ : Optional[int] = int(A ) lowercase_ : Optional[int] = line if word in self and not overwrite: raise RuntimeError( '''Duplicate word found when loading Dictionary: \'{}\'. ''' '''Duplicate words can overwrite earlier ones by adding the ''' '''#fairseq:overwrite flag at the end of the corresponding row ''' '''in the dictionary file. If using the Camembert model, please ''' '''download an updated copy of the model file.'''.format(A ) ) self.add_symbol(A , n=A , overwrite=A ) except ValueError: raise ValueError('''Incorrect dictionary format, expected \'<token> <cnt> [flags]\'''' ) def lowercase ( __snake_case : Dict ): # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} lowercase_ : Dict = dict((re.sub(r'''@@$''' , '''''' , __snake_case ), v) if k.endswith('''@@''' ) else (re.sub(r'''$''' , '''</w>''' , __snake_case ), v) for k, v in d.items() ) lowercase_ : int = '''<s> <pad> </s> <unk>'''.split() # restore the special tokens for k in keep_keys: del da[F'''{k}</w>'''] lowercase_ : Union[str, Any] = d[k] # restore return da def lowercase ( __snake_case : Tuple , __snake_case : Any ): # prep if not os.path.exists(__snake_case ): raise ValueError(F'''path {biogpt_checkpoint_path} does not exist!''' ) os.makedirs(__snake_case , exist_ok=__snake_case ) print(F'''Writing results to {pytorch_dump_folder_path}''' ) # handle various types of models lowercase_ : Optional[Any] = os.path.join(__snake_case , '''checkpoint.pt''' ) if not os.path.isfile(__snake_case ): raise ValueError(F'''path to the file {checkpoint_file} does not exist!''' ) lowercase_ : Union[str, Any] = torch.load(__snake_case , map_location='''cpu''' ) lowercase_ : int = chkpt['''cfg''']['''model'''] # dicts lowercase_ : int = os.path.join(__snake_case , '''dict.txt''' ) if not os.path.isfile(__snake_case ): raise ValueError(F'''path to the file {dict_file} does not exist!''' ) lowercase_ : str = Dictionary.load(__snake_case ) lowercase_ : List[str] = rewrite_dict_keys(src_dict.indices ) lowercase_ : Dict = len(__snake_case ) lowercase_ : int = os.path.join(__snake_case , VOCAB_FILES_NAMES['''vocab_file'''] ) print(F'''Generating {src_vocab_file} of {src_vocab_size} records''' ) with open(__snake_case , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(__snake_case , ensure_ascii=__snake_case , indent=__snake_case ) ) # merges_file (bpecodes) lowercase_ : Optional[int] = os.path.join(__snake_case , '''bpecodes''' ) if not os.path.isfile(__snake_case ): raise ValueError(F'''path to the file {bpecodes_file} does not exist!''' ) lowercase_ : List[Any] = os.path.join(__snake_case , VOCAB_FILES_NAMES['''merges_file'''] ) shutil.copyfile(__snake_case , __snake_case ) # model config lowercase_ : Union[str, Any] = os.path.join(__snake_case , '''config.json''' ) lowercase_ : Dict = { '''activation_dropout''': args['''activation_dropout'''], '''architectures''': ['''BioGptForCausalLM'''], '''attention_probs_dropout_prob''': args['''attention_dropout'''], '''bos_token_id''': 0, '''eos_token_id''': 2, '''hidden_act''': args['''activation_fn'''], '''hidden_dropout_prob''': args['''dropout'''], '''hidden_size''': args['''decoder_embed_dim'''], '''initializer_range''': 0.02, '''intermediate_size''': args['''decoder_ffn_embed_dim'''], '''layer_norm_eps''': 1e-12, '''layerdrop''': args['''decoder_layerdrop'''], '''max_position_embeddings''': args['''max_target_positions'''], '''model_type''': '''biogpt''', '''num_attention_heads''': args['''decoder_attention_heads'''], '''num_hidden_layers''': args['''decoder_layers'''], '''pad_token_id''': 1, '''scale_embedding''': not args['''no_scale_embedding'''], '''tie_word_embeddings''': args['''share_decoder_input_output_embed'''], '''vocab_size''': src_vocab_size, } # good hparam defaults to start with print(F'''Generating {biogpt_model_config_file}''' ) with open(__snake_case , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(__snake_case , ensure_ascii=__snake_case , indent=__snake_case ) ) # tokenizer config lowercase_ : Optional[int] = os.path.join(__snake_case , __snake_case ) lowercase_ : str = { '''bos_token''': '''<s>''', '''eos_token''': '''</s>''', '''model_max_length''': 1_0_2_4, '''pad_token''': '''<pad>''', '''special_tokens_map_file''': None, '''tokenizer_class''': '''BioGptTokenizer''', '''unk_token''': '''<unk>''', } print(F'''Generating {biogpt_tokenizer_config_file}''' ) with open(__snake_case , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(__snake_case , ensure_ascii=__snake_case , indent=__snake_case ) ) # model lowercase_ : Tuple = chkpt['''model'''] # remove unneeded keys lowercase_ : Dict = [ '''decoder.version''', ] for k in ignore_keys: model_state_dict.pop(__snake_case , __snake_case ) lowercase_ : List[Any] = list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith('''output_projection.weight''' ): lowercase_ : Optional[int] = model_state_dict.pop(__snake_case ) else: lowercase_ : str = model_state_dict.pop(__snake_case ) lowercase_ : int = BioGptConfig.from_pretrained(__snake_case ) lowercase_ : int = BioGptForCausalLM(__snake_case ) # check that it loads ok model_new.load_state_dict(__snake_case ) # save lowercase_ : Optional[int] = os.path.join(__snake_case , __snake_case ) print(F'''Generating {pytorch_weights_dump_path}''' ) torch.save(__snake_case , __snake_case ) print('''Conversion is done!''' ) if __name__ == "__main__": __A : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--biogpt_checkpoint_path''', default=None, type=str, required=True, help=( '''Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,''' ''' bpecodes, etc.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) __A : Dict = parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
33
"""simple docstring""" from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class __A (snake_case__): '''simple docstring''' @slow @require_torch def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = EncoderDecoderModel.from_encoder_decoder_pretrained("""prajjwal1/bert-tiny""" , """prajjwal1/bert-tiny""" ) snake_case_ = BertTokenizer.from_pretrained("""bert-base-uncased""" ) snake_case_ = bertabert.config.encoder.vocab_size snake_case_ = tokenizer.sep_token_id snake_case_ = tokenizer.cls_token_id snake_case_ = 128 snake_case_ = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""train[:1%]""" ) snake_case_ = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""validation[:1%]""" ) snake_case_ = train_dataset.select(range(32 ) ) snake_case_ = val_dataset.select(range(16 ) ) snake_case_ = 4 def _map_to_encoder_decoder_inputs(UpperCAmelCase_ : int ): # Tokenizer will automatically set [BOS] <text> [EOS] snake_case_ = tokenizer(batch["""article"""] , padding="""max_length""" , truncation=UpperCAmelCase_ , max_length=512 ) snake_case_ = tokenizer(batch["""highlights"""] , padding="""max_length""" , truncation=UpperCAmelCase_ , max_length=128 ) snake_case_ = inputs.input_ids snake_case_ = inputs.attention_mask snake_case_ = outputs.input_ids snake_case_ = outputs.input_ids.copy() snake_case_ = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["""labels"""] ] snake_case_ = outputs.attention_mask assert all(len(UpperCAmelCase_ ) == 512 for x in inputs.input_ids ) assert all(len(UpperCAmelCase_ ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(UpperCAmelCase_ : Union[str, Any] ): snake_case_ = pred.label_ids snake_case_ = pred.predictions # all unnecessary tokens are removed snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = sum([int(pred_str[i] == label_str[i] ) for i in range(len(UpperCAmelCase_ ) )] ) / len(UpperCAmelCase_ ) return {"accuracy": accuracy} # map train dataset snake_case_ = train_dataset.map( _map_to_encoder_decoder_inputs , batched=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , remove_columns=["""article""", """highlights"""] , ) train_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) # same for validation dataset snake_case_ = val_dataset.map( _map_to_encoder_decoder_inputs , batched=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , remove_columns=["""article""", """highlights"""] , ) val_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) snake_case_ = self.get_auto_remove_tmp_dir() snake_case_ = SeqaSeqTrainingArguments( output_dir=UpperCAmelCase_ , per_device_train_batch_size=UpperCAmelCase_ , per_device_eval_batch_size=UpperCAmelCase_ , predict_with_generate=UpperCAmelCase_ , evaluation_strategy="""steps""" , do_train=UpperCAmelCase_ , do_eval=UpperCAmelCase_ , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer snake_case_ = SeqaSeqTrainer( model=UpperCAmelCase_ , args=UpperCAmelCase_ , compute_metrics=_compute_metrics , train_dataset=UpperCAmelCase_ , eval_dataset=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ , ) # start training trainer.train()
347
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A ={ 'configuration_groupvit': [ 'GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GroupViTConfig', 'GroupViTOnnxConfig', 'GroupViTTextConfig', 'GroupViTVisionConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A =[ 'GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'GroupViTModel', 'GroupViTPreTrainedModel', 'GroupViTTextModel', 'GroupViTVisionModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A =[ 'TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFGroupViTModel', 'TFGroupViTPreTrainedModel', 'TFGroupViTTextModel', 'TFGroupViTVisionModel', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
34
"""simple docstring""" # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys __SCREAMING_SNAKE_CASE : Tuple = subprocess.check_output('git merge-base main HEAD'.split()).decode('utf-8') __SCREAMING_SNAKE_CASE : Tuple = subprocess.check_output(f"""git diff --name-only {fork_point_sha}""".split()).decode('utf-8').split() __SCREAMING_SNAKE_CASE : Any = '|'.join(sys.argv[1:]) __SCREAMING_SNAKE_CASE : Optional[Any] = re.compile(Rf"""^({joined_dirs}).*?\.py$""") __SCREAMING_SNAKE_CASE : List[str] = [x for x in modified_files if regex.match(x)] print(' '.join(relevant_modified_files), end='')
347
0
'''simple docstring''' def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> bool: return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(_lowerCAmelCase ) ) def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> bool: # Base Case if index == len(_lowerCAmelCase ): return True # Recursive Step for i in range(_lowerCAmelCase ): if valid_coloring(graph[index] , _lowerCAmelCase , _lowerCAmelCase ): # Color current vertex snake_case__ : List[Any] = i # Validate coloring if util_color(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , index + 1 ): return True # Backtrack snake_case__ : Optional[Any] = -1 return False def __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> list[int]: snake_case__ : Dict = [-1] * len(_lowerCAmelCase ) if util_color(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , 0 ): return colored_vertices return []
35
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } __SCREAMING_SNAKE_CASE : List[Any] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = {} with open(_SCREAMING_SNAKE_CASE , """r""" ) as file: for line_number, line in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = line.strip() if line: snake_case_ = line.split() snake_case_ = line_number snake_case_ = words[0] snake_case_ = value return result def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: for attribute in key.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(_SCREAMING_SNAKE_CASE ): snake_case_ = PARAM_MAPPING[full_name.split(""".""" )[-1]] snake_case_ = """param""" if weight_type is not None and weight_type != "param": snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape elif weight_type is not None and weight_type == "param": snake_case_ = hf_pointer for attribute in hf_param_name.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = shape_pointer.shape # let's reduce dimension snake_case_ = value[0] else: snake_case_ = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": snake_case_ = value elif weight_type == "weight_g": snake_case_ = value elif weight_type == "weight_v": snake_case_ = value elif weight_type == "bias": snake_case_ = value elif weight_type == "param": for attribute in hf_param_name.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = value else: snake_case_ = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(_SCREAMING_SNAKE_CASE ): snake_case_ = PARAM_MAPPING[full_name.split(""".""" )[-1]] snake_case_ = """param""" if weight_type is not None and weight_type != "param": snake_case_ = """.""".join([key, weight_type] ) elif weight_type is not None and weight_type == "param": snake_case_ = """.""".join([key, hf_param_name] ) else: snake_case_ = key snake_case_ = value if """lm_head""" in full_key else value[0] __SCREAMING_SNAKE_CASE : int = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> List[str]: snake_case_ = False for key, mapped_key in MAPPING.items(): snake_case_ = """wav2vec2.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: snake_case_ = True if "*" in mapped_key: snake_case_ = name.split(_SCREAMING_SNAKE_CASE )[0].split(""".""" )[-2] snake_case_ = mapped_key.replace("""*""" , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: snake_case_ = """weight_g""" elif "weight_v" in name: snake_case_ = """weight_v""" elif "bias" in name: snake_case_ = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj snake_case_ = """weight""" else: snake_case_ = None if hf_dict is not None: rename_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return is_used return is_used def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = [] snake_case_ = fairseq_model.state_dict() snake_case_ = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): snake_case_ = False if "conv_layers" in name: load_conv_layer( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == """group""" , ) snake_case_ = True else: snake_case_ = load_wavaveca_layer(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(f"""Unused weights: {unused_weights}""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = full_name.split("""conv_layers.""" )[-1] snake_case_ = name.split(""".""" ) snake_case_ = int(items[0] ) snake_case_ = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_SCREAMING_SNAKE_CASE ) @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False ) -> int: if config_path is not None: snake_case_ = WavaVecaConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) else: snake_case_ = WavaVecaConfig() if is_seq_class: snake_case_ = read_txt_into_dict(_SCREAMING_SNAKE_CASE ) snake_case_ = idalabel snake_case_ = WavaVecaForSequenceClassification(_SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) elif is_finetuned: if dict_path: snake_case_ = Dictionary.load(_SCREAMING_SNAKE_CASE ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq snake_case_ = target_dict.pad_index snake_case_ = target_dict.bos_index snake_case_ = target_dict.eos_index snake_case_ = len(target_dict.symbols ) snake_case_ = os.path.join(_SCREAMING_SNAKE_CASE , """vocab.json""" ) if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) ) return os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) snake_case_ = target_dict.indices # fairseq has the <pad> and <s> switched snake_case_ = 0 snake_case_ = 1 with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaCTCTokenizer( _SCREAMING_SNAKE_CASE , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=_SCREAMING_SNAKE_CASE , ) snake_case_ = True if config.feat_extract_norm == """layer""" else False snake_case_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) snake_case_ = WavaVecaProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaForCTC(_SCREAMING_SNAKE_CASE ) else: snake_case_ = WavaVecaForPreTraining(_SCREAMING_SNAKE_CASE ) if is_finetuned or is_seq_class: snake_case_ , snake_case_ , snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: snake_case_ = argparse.Namespace(task="""audio_pretraining""" ) snake_case_ = fairseq.tasks.setup_task(_SCREAMING_SNAKE_CASE ) snake_case_ , snake_case_ , snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=_SCREAMING_SNAKE_CASE ) snake_case_ = model[0].eval() recursively_load_weights(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , not is_finetuned ) hf_wavavec.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) __SCREAMING_SNAKE_CASE : Any = parser.parse_args() __SCREAMING_SNAKE_CASE : List[Any] = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
347
0
import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from pathlib import Path from urllib.parse import urlparse from zipfile import ZipFile, is_zipfile import cva import numpy as np import requests import wget from filelock import FileLock from PIL import Image from tqdm.auto import tqdm from yaml import Loader, dump, load try: import torch _snake_case = True except ImportError: _snake_case = False try: from torch.hub import _get_torch_home _snake_case = _get_torch_home() except ImportError: _snake_case = os.path.expanduser( os.getenv("TORCH_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "torch")) ) _snake_case = os.path.join(torch_cache_home, "transformers") _snake_case = "https://cdn.huggingface.co" _snake_case = "https://s3.amazonaws.com/models.huggingface.co/bert" _snake_case = "/".join(str(Path(__file__).resolve()).split("/")[:-1]) _snake_case = os.path.join(PATH, "config.yaml") _snake_case = os.path.join(PATH, "attributes.txt") _snake_case = os.path.join(PATH, "objects.txt") _snake_case = os.getenv("PYTORCH_PRETRAINED_BERT_CACHE", default_cache_path) _snake_case = os.getenv("PYTORCH_TRANSFORMERS_CACHE", PYTORCH_PRETRAINED_BERT_CACHE) _snake_case = os.getenv("TRANSFORMERS_CACHE", PYTORCH_TRANSFORMERS_CACHE) _snake_case = "pytorch_model.bin" _snake_case = "config.yaml" def A ( _lowerCamelCase=OBJECTS , _lowerCamelCase=ATTRIBUTES ): '''simple docstring''' _lowerCAmelCase : Tuple = [] with open(_lowerCamelCase ) as f: for object in f.readlines(): vg_classes.append(object.split("," )[0].lower().strip() ) _lowerCAmelCase : Tuple = [] with open(_lowerCamelCase ) as f: for object in f.readlines(): vg_attrs.append(object.split("," )[0].lower().strip() ) return vg_classes, vg_attrs def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : str = OrderedDict() with open(_lowerCamelCase , "rb" ) as f: _lowerCAmelCase : Optional[int] = pkl.load(_lowerCamelCase )["model"] for k in copy.deepcopy(list(ckp.keys() ) ): _lowerCAmelCase : int = ckp.pop(_lowerCamelCase ) if isinstance(_lowerCamelCase , np.ndarray ): _lowerCAmelCase : Optional[int] = torch.tensor(_lowerCamelCase ) else: assert isinstance(_lowerCamelCase , torch.tensor ), type(_lowerCamelCase ) _lowerCAmelCase : int = v return r class UpperCAmelCase_ : lowerCamelCase__ = {} def __init__( self, __a, __a = "root", __a=0): '''simple docstring''' _lowerCAmelCase : str = name _lowerCAmelCase : List[Any] = level _lowerCAmelCase : List[str] = {} for k, v in dictionary.items(): if v is None: raise ValueError() _lowerCAmelCase : Union[str, Any] = copy.deepcopy(__a) _lowerCAmelCase : Tuple = copy.deepcopy(__a) if isinstance(__a, __a): _lowerCAmelCase : Any = Config(__a, name=__a, level=level + 1) _lowerCAmelCase : int = v setattr(self, __a, __a) _lowerCAmelCase : List[str] = d def __repr__( self): '''simple docstring''' return str(list((self._pointer.keys()))) def __setattr__( self, __a, __a): '''simple docstring''' _lowerCAmelCase : Any = val _lowerCAmelCase : int = val _lowerCAmelCase : Tuple = key.split(".") _lowerCAmelCase : Union[str, Any] = len(__a) - 1 _lowerCAmelCase : Any = self._pointer if len(__a) > 1: for i, l in enumerate(__a): if hasattr(self, __a) and isinstance(getattr(self, __a), __a): setattr(getattr(self, __a), ".".join(levels[i:]), __a) if l == last_level: _lowerCAmelCase : Optional[int] = val else: _lowerCAmelCase : str = pointer[l] def snake_case__ ( self): '''simple docstring''' return self._pointer def snake_case__ ( self, __a, __a): '''simple docstring''' with open(f"{file_name}", "w") as stream: dump(__a, __a) def snake_case__ ( self, __a, __a): '''simple docstring''' with open(f"{file_name}", "w") as stream: json.dump(__a, __a) @staticmethod def snake_case__ ( __a): '''simple docstring''' with open(__a) as stream: _lowerCAmelCase : Dict = load(__a, Loader=__a) return data def __str__( self): '''simple docstring''' _lowerCAmelCase : List[str] = " " if self._name != "root": _lowerCAmelCase : Dict = f"{t * (self._level-1)}{self._name}:\n" else: _lowerCAmelCase : str = "" _lowerCAmelCase : str = self._level for i, (k, v) in enumerate(self._pointer.items()): if isinstance(__a, __a): r += f"{t * (self._level)}{v}\n" self._level += 1 else: r += f"{t * (self._level)}{k}: {v} ({type(__a).__name__})\n" _lowerCAmelCase : Optional[int] = level return r[:-1] @classmethod def snake_case__ ( cls, __a, **__a): '''simple docstring''' _lowerCAmelCase , _lowerCAmelCase : Tuple = cls.get_config_dict(__a, **__a) return cls(__a) @classmethod def snake_case__ ( cls, __a, **__a): '''simple docstring''' _lowerCAmelCase : Optional[int] = kwargs.pop("cache_dir", __a) _lowerCAmelCase : str = kwargs.pop("force_download", __a) _lowerCAmelCase : Optional[Any] = kwargs.pop("resume_download", __a) _lowerCAmelCase : str = kwargs.pop("proxies", __a) _lowerCAmelCase : int = kwargs.pop("local_files_only", __a) if os.path.isdir(__a): _lowerCAmelCase : str = os.path.join(__a, __a) elif os.path.isfile(__a) or is_remote_url(__a): _lowerCAmelCase : List[str] = pretrained_model_name_or_path else: _lowerCAmelCase : int = hf_bucket_url(__a, filename=__a, use_cdn=__a) try: # Load from URL or cache if already cached _lowerCAmelCase : Optional[Any] = cached_path( __a, cache_dir=__a, force_download=__a, proxies=__a, resume_download=__a, local_files_only=__a, ) # Load config dict if resolved_config_file is None: raise EnvironmentError _lowerCAmelCase : Tuple = Config.load_yaml(__a) except EnvironmentError: _lowerCAmelCase : List[Any] = "Can't load config for" raise EnvironmentError(__a) if resolved_config_file == config_file: print("loading configuration file from path") else: print("loading configuration file cache") return Config.load_yaml(__a), kwargs def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Dict = torch.load("dump.pt" , map_location=in_tensor.device ) _lowerCAmelCase : List[str] = in_tensor.numpy() _lowerCAmelCase : Optional[Any] = out_tensor.numpy()[0] print(na.shape , na[0, 0, :5] ) print(na.shape , na[0, 0, :5] ) assert np.allclose(_lowerCamelCase , _lowerCamelCase , rtol=0.01 , atol=0.1 ), ( F"{sum([1 for x in np.isclose(_lowerCamelCase , _lowerCamelCase , rtol=0.01 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*100:.4f} %" " element-wise mismatch" ) raise Exception("tensors are all good" ) # Hugging face functions below def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : List[Any] = urlparse(_lowerCamelCase ) return parsed.scheme in ("http", "https") def A ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=True ): '''simple docstring''' _lowerCAmelCase : str = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX _lowerCAmelCase : Any = "/" not in model_id if legacy_format: return F"{endpoint}/{model_id}-{filename}" else: return F"{endpoint}/{model_id}/{filename}" def A ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=0 , _lowerCamelCase=None , ): '''simple docstring''' _lowerCAmelCase : Optional[int] = "python/{}".format(sys.version.split()[0] ) if _torch_available: ua += "; torch/{}".format(torch.__version__ ) if isinstance(_lowerCamelCase , _lowerCamelCase ): ua += "; " + "; ".join("{}/{}".format(_lowerCamelCase , _lowerCamelCase ) for k, v in user_agent.items() ) elif isinstance(_lowerCamelCase , _lowerCamelCase ): ua += "; " + user_agent _lowerCAmelCase : int = {"user-agent": ua} if resume_size > 0: _lowerCAmelCase : List[Any] = "bytes=%d-" % (resume_size,) _lowerCAmelCase : Tuple = requests.get(_lowerCamelCase , stream=_lowerCamelCase , proxies=_lowerCamelCase , headers=_lowerCamelCase ) if response.status_code == 416: # Range not satisfiable return _lowerCAmelCase : List[str] = response.headers.get("Content-Length" ) _lowerCAmelCase : Any = resume_size + int(_lowerCamelCase ) if content_length is not None else None _lowerCAmelCase : List[Any] = tqdm( unit="B" , unit_scale=_lowerCamelCase , total=_lowerCamelCase , initial=_lowerCamelCase , desc="Downloading" , ) for chunk in response.iter_content(chunk_size=1_024 ): if chunk: # filter out keep-alive new chunks progress.update(len(_lowerCamelCase ) ) temp_file.write(_lowerCamelCase ) progress.close() def A ( _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=False , _lowerCamelCase=None , _lowerCamelCase=10 , _lowerCamelCase=False , _lowerCamelCase=None , _lowerCamelCase=False , ): '''simple docstring''' if cache_dir is None: _lowerCAmelCase : int = TRANSFORMERS_CACHE if isinstance(_lowerCamelCase , _lowerCamelCase ): _lowerCAmelCase : Any = str(_lowerCamelCase ) os.makedirs(_lowerCamelCase , exist_ok=_lowerCamelCase ) _lowerCAmelCase : Union[str, Any] = None if not local_files_only: try: _lowerCAmelCase : List[Any] = requests.head(_lowerCamelCase , allow_redirects=_lowerCamelCase , proxies=_lowerCamelCase , timeout=_lowerCamelCase ) if response.status_code == 200: _lowerCAmelCase : Any = response.headers.get("ETag" ) except (EnvironmentError, requests.exceptions.Timeout): # etag is already None pass _lowerCAmelCase : int = url_to_filename(_lowerCamelCase , _lowerCamelCase ) # get cache path to put the file _lowerCAmelCase : Dict = os.path.join(_lowerCamelCase , _lowerCamelCase ) # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible. # try to get the last downloaded one if etag is None: if os.path.exists(_lowerCamelCase ): return cache_path else: _lowerCAmelCase : int = [ file for file in fnmatch.filter(os.listdir(_lowerCamelCase ) , filename + ".*" ) if not file.endswith(".json" ) and not file.endswith(".lock" ) ] if len(_lowerCamelCase ) > 0: return os.path.join(_lowerCamelCase , matching_files[-1] ) else: # If files cannot be found and local_files_only=True, # the models might've been found if local_files_only=False # Notify the user about that if local_files_only: raise ValueError( "Cannot find the requested files in the cached path and outgoing traffic has been" " disabled. To enable model look-ups and downloads online, set 'local_files_only'" " to False." ) return None # From now on, etag is not None. if os.path.exists(_lowerCamelCase ) and not force_download: return cache_path # Prevent parallel downloads of the same file with a lock. _lowerCAmelCase : int = cache_path + ".lock" with FileLock(_lowerCamelCase ): # If the download just completed while the lock was activated. if os.path.exists(_lowerCamelCase ) and not force_download: # Even if returning early like here, the lock will be released. return cache_path if resume_download: _lowerCAmelCase : List[str] = cache_path + ".incomplete" @contextmanager def _resumable_file_manager(): with open(_lowerCamelCase , "a+b" ) as f: yield f _lowerCAmelCase : Optional[int] = _resumable_file_manager if os.path.exists(_lowerCamelCase ): _lowerCAmelCase : str = os.stat(_lowerCamelCase ).st_size else: _lowerCAmelCase : Union[str, Any] = 0 else: _lowerCAmelCase : int = partial(tempfile.NamedTemporaryFile , dir=_lowerCamelCase , delete=_lowerCamelCase ) _lowerCAmelCase : List[str] = 0 # Download to temporary file, then copy to cache dir once finished. # Otherwise you get corrupt cache entries if the download gets interrupted. with temp_file_manager() as temp_file: print( "%s not found in cache or force_download set to True, downloading to %s" , _lowerCamelCase , temp_file.name , ) http_get( _lowerCamelCase , _lowerCamelCase , proxies=_lowerCamelCase , resume_size=_lowerCamelCase , user_agent=_lowerCamelCase , ) os.replace(temp_file.name , _lowerCamelCase ) _lowerCAmelCase : int = {"url": url, "etag": etag} _lowerCAmelCase : int = cache_path + ".json" with open(_lowerCamelCase , "w" ) as meta_file: json.dump(_lowerCamelCase , _lowerCamelCase ) return cache_path def A ( _lowerCamelCase , _lowerCamelCase=None ): '''simple docstring''' _lowerCAmelCase : List[Any] = url.encode("utf-8" ) _lowerCAmelCase : Union[str, Any] = shaaaa(_lowerCamelCase ) _lowerCAmelCase : str = url_hash.hexdigest() if etag: _lowerCAmelCase : Tuple = etag.encode("utf-8" ) _lowerCAmelCase : Optional[Any] = shaaaa(_lowerCamelCase ) filename += "." + etag_hash.hexdigest() if url.endswith(".h5" ): filename += ".h5" return filename def A ( _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=False , _lowerCamelCase=None , _lowerCamelCase=False , _lowerCamelCase=None , _lowerCamelCase=False , _lowerCamelCase=False , _lowerCamelCase=False , ): '''simple docstring''' if cache_dir is None: _lowerCAmelCase : Any = TRANSFORMERS_CACHE if isinstance(_lowerCamelCase , _lowerCamelCase ): _lowerCAmelCase : int = str(_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ): _lowerCAmelCase : int = str(_lowerCamelCase ) if is_remote_url(_lowerCamelCase ): # URL, so get it from the cache (downloading if necessary) _lowerCAmelCase : Tuple = get_from_cache( _lowerCamelCase , cache_dir=_lowerCamelCase , force_download=_lowerCamelCase , proxies=_lowerCamelCase , resume_download=_lowerCamelCase , user_agent=_lowerCamelCase , local_files_only=_lowerCamelCase , ) elif os.path.exists(_lowerCamelCase ): # File, and it exists. _lowerCAmelCase : str = url_or_filename elif urlparse(_lowerCamelCase ).scheme == "": # File, but it doesn't exist. raise EnvironmentError("file {} not found".format(_lowerCamelCase ) ) else: # Something unknown raise ValueError("unable to parse {} as a URL or as a local path".format(_lowerCamelCase ) ) if extract_compressed_file: if not is_zipfile(_lowerCamelCase ) and not tarfile.is_tarfile(_lowerCamelCase ): return output_path # Path where we extract compressed archives # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/" _lowerCAmelCase , _lowerCAmelCase : Tuple = os.path.split(_lowerCamelCase ) _lowerCAmelCase : Union[str, Any] = output_file.replace("." , "-" ) + "-extracted" _lowerCAmelCase : Optional[int] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isdir(_lowerCamelCase ) and os.listdir(_lowerCamelCase ) and not force_extract: return output_path_extracted # Prevent parallel extractions _lowerCAmelCase : Any = output_path + ".lock" with FileLock(_lowerCamelCase ): shutil.rmtree(_lowerCamelCase , ignore_errors=_lowerCamelCase ) os.makedirs(_lowerCamelCase ) if is_zipfile(_lowerCamelCase ): with ZipFile(_lowerCamelCase , "r" ) as zip_file: zip_file.extractall(_lowerCamelCase ) zip_file.close() elif tarfile.is_tarfile(_lowerCamelCase ): _lowerCAmelCase : List[Any] = tarfile.open(_lowerCamelCase ) tar_file.extractall(_lowerCamelCase ) tar_file.close() else: raise EnvironmentError("Archive format of {} could not be identified".format(_lowerCamelCase ) ) return output_path_extracted return output_path def A ( _lowerCamelCase , _lowerCamelCase="," ): '''simple docstring''' assert isinstance(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ): with open(_lowerCamelCase ) as f: _lowerCAmelCase : Optional[int] = eval(f.read() ) else: _lowerCAmelCase : Union[str, Any] = requests.get(_lowerCamelCase ) try: _lowerCAmelCase : str = requests.json() except Exception: _lowerCAmelCase : str = req.content.decode() assert data is not None, "could not connect" try: _lowerCAmelCase : Optional[Any] = eval(_lowerCamelCase ) except Exception: _lowerCAmelCase : int = data.split("\n" ) req.close() return data def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : str = requests.get(_lowerCamelCase ) _lowerCAmelCase : Any = np.array(Image.open(BytesIO(response.content ) ) ) return img def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : List[str] = url.split("/" )[-1] if fn not in os.listdir(os.getcwd() ): wget.download(_lowerCamelCase ) with open(_lowerCamelCase , "rb" ) as stream: _lowerCAmelCase : Any = pkl.load(_lowerCamelCase ) _lowerCAmelCase : Optional[Any] = weights.pop("model" ) _lowerCAmelCase : Any = {} for k, v in model.items(): _lowerCAmelCase : Union[str, Any] = torch.from_numpy(_lowerCamelCase ) if "running_var" in k: _lowerCAmelCase : str = torch.tensor([0] ) _lowerCAmelCase : str = k.replace("running_var" , "num_batches_tracked" ) _lowerCAmelCase : List[str] = zero return new def A ( ): '''simple docstring''' print(F"{os.path.abspath(os.path.join(_lowerCamelCase , os.pardir ) )}/demo.ipynb" ) def A ( _lowerCamelCase , _lowerCamelCase="RGB" ): '''simple docstring''' assert isinstance(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ): _lowerCAmelCase : List[str] = cva.imread(_lowerCamelCase ) else: _lowerCAmelCase : List[str] = get_image_from_url(_lowerCamelCase ) assert img is not None, F"could not connect to: {im}" _lowerCAmelCase : Optional[Any] = cva.cvtColor(_lowerCamelCase , cva.COLOR_BGR2RGB ) if input_format == "RGB": _lowerCAmelCase : Optional[Any] = img[:, :, ::-1] return img def A ( _lowerCamelCase , _lowerCamelCase=1 ): '''simple docstring''' return (images[i : i + batch] for i in range(0 , len(_lowerCamelCase ) , _lowerCamelCase ))
36
"""simple docstring""" import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class __A : '''simple docstring''' def __init__( self : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any=14 , UpperCAmelCase_ : Union[str, Any]=7 , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : str=99 , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : List[Any]=4 , UpperCAmelCase_ : Optional[int]=4 , UpperCAmelCase_ : int=4 , UpperCAmelCase_ : str=37 , UpperCAmelCase_ : Any="gelu" , UpperCAmelCase_ : str=0.1 , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : int=512 , UpperCAmelCase_ : Tuple=0.02 , ) ->List[str]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = rotary_dim snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = initializer_range snake_case_ = None snake_case_ = vocab_size - 1 snake_case_ = vocab_size - 1 snake_case_ = vocab_size - 1 def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_input_mask: snake_case_ = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=UpperCAmelCase_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""input_ids""": input_ids, """attention_mask""": attention_mask} return config, inputs_dict def lowerCAmelCase ( self : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict ) ->Tuple: """simple docstring""" snake_case_ = 20 snake_case_ = model_class_name(UpperCAmelCase_ ) snake_case_ = model.init_cache(input_ids.shape[0] , UpperCAmelCase_ ) snake_case_ = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) snake_case_ = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) snake_case_ = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) snake_case_ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="""i4""" ) snake_case_ = model( input_ids[:, -1:] , attention_mask=UpperCAmelCase_ , past_key_values=outputs_cache.past_key_values , position_ids=UpperCAmelCase_ , ) snake_case_ = model(UpperCAmelCase_ ) snake_case_ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = 20 snake_case_ = model_class_name(UpperCAmelCase_ ) snake_case_ = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) snake_case_ = model.init_cache(input_ids.shape[0] , UpperCAmelCase_ ) snake_case_ = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) snake_case_ = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) snake_case_ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="""i4""" ) snake_case_ = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) snake_case_ = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ ) snake_case_ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) @require_flax class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Any = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () __lowercase: List[str] = (FlaxGPTJForCausalLM,) if is_flax_available() else () def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = FlaxGPTJModelTester(self ) def lowerCAmelCase ( self : int ) ->List[Any]: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ , snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : List[str] ) ->Any: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ , snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) @tooslow def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" snake_case_ = GPTaTokenizer.from_pretrained("""gpt2""" , pad_token="""<|endoftext|>""" , padding_side="""left""" ) snake_case_ = tokenizer(["""Hello this is a long string""", """Hey"""] , return_tensors="""np""" , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ ) snake_case_ = FlaxGPTJForCausalLM.from_pretrained("""EleutherAI/gpt-j-6B""" ) snake_case_ = False snake_case_ = model.config.eos_token_id snake_case_ = jax.jit(model.generate ) snake_case_ = jit_generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , pad_token_id=tokenizer.pad_token_id ).sequences snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = [ """Hello this is a long string of text.\n\nI'm trying to get the text of the""", """Hey, I'm a little late to the party. I'm going to""", ] self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) @is_pt_flax_cross_test def lowerCAmelCase ( self : int ) ->str: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class snake_case_ = model_class.__name__[4:] # Skip the "Flax" at the beginning snake_case_ = getattr(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ , snake_case_ = pt_inputs["""input_ids"""].shape snake_case_ = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCAmelCase_ ): snake_case_ = 0 snake_case_ = 1 snake_case_ = 0 snake_case_ = 1 snake_case_ = pt_model_class(UpperCAmelCase_ ).eval() snake_case_ = model_class(UpperCAmelCase_ , dtype=jnp.floataa ) snake_case_ = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , UpperCAmelCase_ ) snake_case_ = fx_state with torch.no_grad(): snake_case_ = pt_model(**UpperCAmelCase_ ).to_tuple() snake_case_ = fx_model(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(UpperCAmelCase_ ) snake_case_ = model_class.from_pretrained(UpperCAmelCase_ , from_pt=UpperCAmelCase_ ) snake_case_ = fx_model_loaded(**UpperCAmelCase_ ).to_tuple() self.assertEqual( len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output_loaded, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class snake_case_ = model_class.__name__[4:] # Skip the "Flax" at the beginning snake_case_ = getattr(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = pt_model_class(UpperCAmelCase_ ).eval() snake_case_ = model_class(UpperCAmelCase_ , dtype=jnp.floataa ) snake_case_ = load_flax_weights_in_pytorch_model(UpperCAmelCase_ , fx_model.params ) snake_case_ , snake_case_ = pt_inputs["""input_ids"""].shape snake_case_ = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCAmelCase_ ): snake_case_ = 0 snake_case_ = 1 snake_case_ = 0 snake_case_ = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): snake_case_ = pt_model(**UpperCAmelCase_ ).to_tuple() snake_case_ = fx_model(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(UpperCAmelCase_ ) snake_case_ = pt_model_class.from_pretrained(UpperCAmelCase_ , from_flax=UpperCAmelCase_ ) with torch.no_grad(): snake_case_ = pt_model_loaded(**UpperCAmelCase_ ).to_tuple() self.assertEqual( len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ = model_class_name.from_pretrained("""EleutherAI/gpt-j-6B""" ) snake_case_ = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCAmelCase_ )
347
0
'''simple docstring''' import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCAmelCase_: '''simple docstring''' def __init__( self ,__UpperCAmelCase ,__UpperCAmelCase=13 ,__UpperCAmelCase=32 ,__UpperCAmelCase=2 ,__UpperCAmelCase=3 ,__UpperCAmelCase=16 ,__UpperCAmelCase=[1, 2, 1] ,__UpperCAmelCase=[2, 2, 4] ,__UpperCAmelCase=2 ,__UpperCAmelCase=2.0 ,__UpperCAmelCase=True ,__UpperCAmelCase=0.0 ,__UpperCAmelCase=0.0 ,__UpperCAmelCase=0.1 ,__UpperCAmelCase="gelu" ,__UpperCAmelCase=False ,__UpperCAmelCase=True ,__UpperCAmelCase=0.0_2 ,__UpperCAmelCase=1E-5 ,__UpperCAmelCase=True ,__UpperCAmelCase=None ,__UpperCAmelCase=True ,__UpperCAmelCase=10 ,__UpperCAmelCase=8 ,) -> List[Any]: lowerCAmelCase__ : Any = parent lowerCAmelCase__ : Any = batch_size lowerCAmelCase__ : Union[str, Any] = image_size lowerCAmelCase__ : int = patch_size lowerCAmelCase__ : Dict = num_channels lowerCAmelCase__ : Optional[int] = embed_dim lowerCAmelCase__ : List[str] = depths lowerCAmelCase__ : Union[str, Any] = num_heads lowerCAmelCase__ : str = window_size lowerCAmelCase__ : Union[str, Any] = mlp_ratio lowerCAmelCase__ : Dict = qkv_bias lowerCAmelCase__ : Union[str, Any] = hidden_dropout_prob lowerCAmelCase__ : Optional[Any] = attention_probs_dropout_prob lowerCAmelCase__ : Tuple = drop_path_rate lowerCAmelCase__ : Tuple = hidden_act lowerCAmelCase__ : Dict = use_absolute_embeddings lowerCAmelCase__ : List[str] = patch_norm lowerCAmelCase__ : Optional[int] = layer_norm_eps lowerCAmelCase__ : str = initializer_range lowerCAmelCase__ : str = is_training lowerCAmelCase__ : Tuple = scope lowerCAmelCase__ : Optional[Any] = use_labels lowerCAmelCase__ : Dict = type_sequence_label_size lowerCAmelCase__ : Optional[Any] = encoder_stride def UpperCAmelCase_ ( self ) -> List[Any]: lowerCAmelCase__ : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ : Dict = None if self.use_labels: lowerCAmelCase__ : Tuple = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) lowerCAmelCase__ : List[str] = self.get_config() return config, pixel_values, labels def UpperCAmelCase_ ( self ) -> int: return SwinvaConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,embed_dim=self.embed_dim ,depths=self.depths ,num_heads=self.num_heads ,window_size=self.window_size ,mlp_ratio=self.mlp_ratio ,qkv_bias=self.qkv_bias ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,drop_path_rate=self.drop_path_rate ,hidden_act=self.hidden_act ,use_absolute_embeddings=self.use_absolute_embeddings ,path_norm=self.patch_norm ,layer_norm_eps=self.layer_norm_eps ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,) def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> List[Any]: lowerCAmelCase__ : List[str] = SwinvaModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ : int = model(__UpperCAmelCase ) lowerCAmelCase__ : int = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) lowerCAmelCase__ : Tuple = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, expected_seq_len, expected_dim) ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> List[str]: lowerCAmelCase__ : int = SwinvaForMaskedImageModeling(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ : List[str] = model(__UpperCAmelCase ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images lowerCAmelCase__ : Optional[Any] = 1 lowerCAmelCase__ : int = SwinvaForMaskedImageModeling(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ : Optional[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCAmelCase__ : List[str] = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, 1, self.image_size, self.image_size) ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> Union[str, Any]: lowerCAmelCase__ : List[str] = self.type_sequence_label_size lowerCAmelCase__ : Dict = SwinvaForImageClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ : Tuple = model(__UpperCAmelCase ,labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def UpperCAmelCase_ ( self ) -> Optional[int]: lowerCAmelCase__ : Union[str, Any] = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ : Optional[Any] = config_and_inputs lowerCAmelCase__ : Any = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase_( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): '''simple docstring''' __lowercase : int = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) __lowercase : List[str] = ( {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification} if is_torch_available() else {} ) __lowercase : str = False __lowercase : List[str] = False __lowercase : Any = False __lowercase : Dict = False def UpperCAmelCase_ ( self ) -> Optional[int]: lowerCAmelCase__ : Dict = SwinvaModelTester(self ) lowerCAmelCase__ : List[str] = ConfigTester(self ,config_class=__UpperCAmelCase ,embed_dim=37 ) def UpperCAmelCase_ ( self ) -> Union[str, Any]: self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCAmelCase_ ( self ) -> str: lowerCAmelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" ) def UpperCAmelCase_ ( self ) -> int: pass @unittest.skip(reason="""Swinv2 does not use inputs_embeds""" ) def UpperCAmelCase_ ( self ) -> int: pass def UpperCAmelCase_ ( self ) -> Any: lowerCAmelCase__ , lowerCAmelCase__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ : Optional[int] = model_class(__UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) lowerCAmelCase__ : List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__UpperCAmelCase ,nn.Linear ) ) def UpperCAmelCase_ ( self ) -> str: lowerCAmelCase__ , lowerCAmelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ : Optional[Any] = model_class(__UpperCAmelCase ) lowerCAmelCase__ : Union[str, Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ : Optional[Any] = [*signature.parameters.keys()] lowerCAmelCase__ : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] ,__UpperCAmelCase ) def UpperCAmelCase_ ( self ) -> int: lowerCAmelCase__ , lowerCAmelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ : Any = True for model_class in self.all_model_classes: lowerCAmelCase__ : int = True lowerCAmelCase__ : Any = False lowerCAmelCase__ : List[Any] = True lowerCAmelCase__ : Optional[Any] = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): lowerCAmelCase__ : Tuple = model(**self._prepare_for_class(__UpperCAmelCase ,__UpperCAmelCase ) ) lowerCAmelCase__ : List[str] = outputs.attentions lowerCAmelCase__ : List[Any] = len(self.model_tester.depths ) self.assertEqual(len(__UpperCAmelCase ) ,__UpperCAmelCase ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ : int = True lowerCAmelCase__ : Dict = config.window_size**2 lowerCAmelCase__ : Optional[Any] = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): lowerCAmelCase__ : Optional[Any] = model(**self._prepare_for_class(__UpperCAmelCase ,__UpperCAmelCase ) ) lowerCAmelCase__ : List[str] = outputs.attentions self.assertEqual(len(__UpperCAmelCase ) ,__UpperCAmelCase ) self.assertListEqual( list(attentions[0].shape[-3:] ) ,[self.model_tester.num_heads[0], window_size_squared, window_size_squared] ,) lowerCAmelCase__ : List[str] = len(__UpperCAmelCase ) # Check attention is always last and order is fine lowerCAmelCase__ : Optional[int] = True lowerCAmelCase__ : Union[str, Any] = True lowerCAmelCase__ : Tuple = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): lowerCAmelCase__ : Any = model(**self._prepare_for_class(__UpperCAmelCase ,__UpperCAmelCase ) ) if hasattr(self.model_tester ,"""num_hidden_states_types""" ): lowerCAmelCase__ : int = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states lowerCAmelCase__ : Optional[int] = 2 self.assertEqual(out_len + added_hidden_states ,len(__UpperCAmelCase ) ) lowerCAmelCase__ : Any = outputs.attentions self.assertEqual(len(__UpperCAmelCase ) ,__UpperCAmelCase ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) ,[self.model_tester.num_heads[0], window_size_squared, window_size_squared] ,) def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> Tuple: lowerCAmelCase__ : Union[str, Any] = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): lowerCAmelCase__ : List[Any] = model(**self._prepare_for_class(__UpperCAmelCase ,__UpperCAmelCase ) ) lowerCAmelCase__ : Optional[int] = outputs.hidden_states lowerCAmelCase__ : str = getattr( self.model_tester ,"""expected_num_hidden_layers""" ,len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__UpperCAmelCase ) ,__UpperCAmelCase ) # Swinv2 has a different seq_length lowerCAmelCase__ : int = ( config.patch_size if isinstance(config.patch_size ,collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowerCAmelCase__ : Tuple = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) ,[num_patches, self.model_tester.embed_dim] ,) lowerCAmelCase__ : Union[str, Any] = outputs.reshaped_hidden_states self.assertEqual(len(__UpperCAmelCase ) ,__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ : int = reshaped_hidden_states[0].shape lowerCAmelCase__ : int = ( reshaped_hidden_states[0].view(__UpperCAmelCase ,__UpperCAmelCase ,height * width ).permute(0 ,2 ,1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) ,[num_patches, self.model_tester.embed_dim] ,) def UpperCAmelCase_ ( self ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ : Optional[int] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size ,collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: lowerCAmelCase__ : int = True self.check_hidden_states_output(__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ : Tuple = True self.check_hidden_states_output(__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) def UpperCAmelCase_ ( self ) -> Union[str, Any]: lowerCAmelCase__ , lowerCAmelCase__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ : int = 3 lowerCAmelCase__ : List[Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size ,collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) lowerCAmelCase__ : int = ( config.patch_size if isinstance(config.patch_size ,collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowerCAmelCase__ : Union[str, Any] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) lowerCAmelCase__ : Dict = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: lowerCAmelCase__ : Union[str, Any] = True self.check_hidden_states_output(__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,(padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ : int = True self.check_hidden_states_output(__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,(padded_height, padded_width) ) def UpperCAmelCase_ ( self ) -> int: lowerCAmelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__UpperCAmelCase ) def UpperCAmelCase_ ( self ) -> Tuple: lowerCAmelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase ) @slow def UpperCAmelCase_ ( self ) -> Any: for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ : List[Any] = SwinvaModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) def UpperCAmelCase_ ( self ) -> Any: lowerCAmelCase__ , lowerCAmelCase__ : str = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ : List[str] = _config_zero_init(__UpperCAmelCase ) for model_class in self.all_model_classes: lowerCAmelCase__ : Tuple = model_class(config=__UpperCAmelCase ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() ,[0.0, 1.0] ,msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" ,) @require_vision @require_torch class lowerCAmelCase_( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCAmelCase_ ( self ) -> Any: return ( AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ) if is_vision_available() else None ) @slow def UpperCAmelCase_ ( self ) -> List[str]: lowerCAmelCase__ : int = SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ).to( __UpperCAmelCase ) lowerCAmelCase__ : Tuple = self.default_image_processor lowerCAmelCase__ : int = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) lowerCAmelCase__ : Tuple = image_processor(images=__UpperCAmelCase ,return_tensors="""pt""" ).to(__UpperCAmelCase ) # forward pass with torch.no_grad(): lowerCAmelCase__ : Tuple = model(**__UpperCAmelCase ) # verify the logits lowerCAmelCase__ : str = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape ,__UpperCAmelCase ) lowerCAmelCase__ : List[str] = torch.tensor([-0.3_9_4_7, -0.4_3_0_6, 0.0_0_2_6] ).to(__UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,__UpperCAmelCase ,atol=1E-4 ) )
37
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING __SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) class __A (snake_case__): '''simple docstring''' __lowercase: int = """upernet""" def __init__( self : str , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : str=512 , UpperCAmelCase_ : int=0.02 , UpperCAmelCase_ : Optional[Any]=[1, 2, 3, 6] , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Tuple=0.4 , UpperCAmelCase_ : Tuple=384 , UpperCAmelCase_ : Union[str, Any]=256 , UpperCAmelCase_ : str=1 , UpperCAmelCase_ : Tuple=False , UpperCAmelCase_ : Tuple=255 , **UpperCAmelCase_ : Dict , ) ->Union[str, Any]: """simple docstring""" super().__init__(**UpperCAmelCase_ ) if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) snake_case_ = CONFIG_MAPPING["""resnet"""](out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = backbone_config.get("""model_type""" ) snake_case_ = CONFIG_MAPPING[backbone_model_type] snake_case_ = config_class.from_dict(UpperCAmelCase_ ) snake_case_ = backbone_config snake_case_ = hidden_size snake_case_ = initializer_range snake_case_ = pool_scales snake_case_ = use_auxiliary_head snake_case_ = auxiliary_loss_weight snake_case_ = auxiliary_in_channels snake_case_ = auxiliary_channels snake_case_ = auxiliary_num_convs snake_case_ = auxiliary_concat_input snake_case_ = loss_ignore_index def lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.backbone_config.to_dict() snake_case_ = self.__class__.model_type return output
347
0
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> bool: """simple docstring""" UpperCamelCase :Optional[Any] = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 5000 ) -> int: """simple docstring""" UpperCamelCase :Optional[int] = [(i * (3 * i - 1)) // 2 for i in range(1 , __magic_name__ )] for i, pentagonal_i in enumerate(__magic_name__ ): for j in range(__magic_name__ , len(__magic_name__ ) ): UpperCamelCase :List[str] = pentagonal_nums[j] UpperCamelCase :Dict = pentagonal_i + pentagonal_j UpperCamelCase :Optional[Any] = pentagonal_j - pentagonal_i if is_pentagonal(__magic_name__ ) and is_pentagonal(__magic_name__ ): return b return -1 if __name__ == "__main__": print(F'''{solution() = }''')
38
"""simple docstring""" import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = """ylacombe/bark-small""" snake_case_ = tempfile.mkdtemp() snake_case_ = """en_speaker_1""" snake_case_ = """This is a test string""" snake_case_ = """speaker_embeddings_path.json""" snake_case_ = """speaker_embeddings""" def lowerCAmelCase ( self : List[str] , **UpperCAmelCase_ : str ) ->Optional[int]: """simple docstring""" return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = self.get_tokenizer() snake_case_ = BarkProcessor(tokenizer=UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) snake_case_ = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def lowerCAmelCase ( self : Dict ) ->int: """simple docstring""" snake_case_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) snake_case_ = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) snake_case_ = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) snake_case_ = 35 snake_case_ = 2 snake_case_ = 8 snake_case_ = { """semantic_prompt""": np.ones(UpperCAmelCase_ ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset snake_case_ = processor(text=self.input_string , voice_preset=UpperCAmelCase_ ) snake_case_ = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([] ) ).tolist() ) # test loading voice preset from npz file snake_case_ = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(UpperCAmelCase_ , **UpperCAmelCase_ ) snake_case_ = processor(text=self.input_string , voice_preset=UpperCAmelCase_ ) snake_case_ = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([] ) ).tolist() ) # test loading voice preset from the hub snake_case_ = processor(text=self.input_string , voice_preset=self.voice_preset ) def lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" snake_case_ = self.get_tokenizer() snake_case_ = BarkProcessor(tokenizer=UpperCAmelCase_ ) snake_case_ = processor(text=self.input_string ) snake_case_ = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
347
0
import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def __A ( )-> str: """simple docstring""" with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(__lowerCAmelCase ): requests.request('GET' , 'https://huggingface.co' ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request('GET' , 'https://huggingface.co' , timeout=1.0 ) @pytest.mark.integration def __A ( )-> List[str]: """simple docstring""" with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request('GET' , 'https://huggingface.co' ) def __A ( )-> Tuple: """simple docstring""" with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(__lowerCAmelCase ): http_head('https://huggingface.co' )
39
"""simple docstring""" import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 __SCREAMING_SNAKE_CASE : int = sys.version_info >= (3, 10) def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: return field(default_factory=lambda: default , metadata=_SCREAMING_SNAKE_CASE ) @dataclass class __A : '''simple docstring''' __lowercase: int __lowercase: float __lowercase: str __lowercase: bool @dataclass class __A : '''simple docstring''' __lowercase: int = 42 __lowercase: str = field(default="""toto""" , metadata={"""help""": """help message"""}) @dataclass class __A : '''simple docstring''' __lowercase: bool = False __lowercase: bool = True __lowercase: Optional[bool] = None class __A (snake_case__): '''simple docstring''' __lowercase: str = """titi""" __lowercase: Any = """toto""" class __A (snake_case__): '''simple docstring''' __lowercase: int = """titi""" __lowercase: Optional[Any] = """toto""" __lowercase: List[Any] = 42 @dataclass class __A : '''simple docstring''' __lowercase: BasicEnum = "toto" def lowerCAmelCase ( self : int ) ->List[Any]: """simple docstring""" snake_case_ = BasicEnum(self.foo ) @dataclass class __A : '''simple docstring''' __lowercase: MixedTypeEnum = "toto" def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = MixedTypeEnum(self.foo ) @dataclass class __A : '''simple docstring''' __lowercase: Optional[int] = None __lowercase: Optional[float] = field(default=snake_case__ , metadata={"""help""": """help message"""}) __lowercase: Optional[str] = None __lowercase: Optional[List[str]] = list_field(default=[]) __lowercase: Optional[List[int]] = list_field(default=[]) @dataclass class __A : '''simple docstring''' __lowercase: List[int] = list_field(default=[]) __lowercase: List[int] = list_field(default=[1, 2, 3]) __lowercase: List[str] = list_field(default=["""Hallo""", """Bonjour""", """Hello"""]) __lowercase: List[float] = list_field(default=[0.1, 0.2, 0.3]) @dataclass class __A : '''simple docstring''' __lowercase: List[int] = field() __lowercase: str = field() __lowercase: BasicEnum = field() def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" snake_case_ = BasicEnum(self.required_enum ) @dataclass class __A : '''simple docstring''' __lowercase: int __lowercase: "BasicEnum" = field() __lowercase: "Optional[bool]" = None __lowercase: "str" = field(default="""toto""" , metadata={"""help""": """help message"""}) __lowercase: "List[str]" = list_field(default=["""Hallo""", """Bonjour""", """Hello"""]) if is_python_no_less_than_3_10: @dataclass class __A : '''simple docstring''' __lowercase: bool = False __lowercase: bool = True __lowercase: bool | None = None @dataclass class __A : '''simple docstring''' __lowercase: int | None = None __lowercase: float | None = field(default=snake_case__ , metadata={"""help""": """help message"""}) __lowercase: str | None = None __lowercase: list[str] | None = list_field(default=[]) __lowercase: list[int] | None = list_field(default=[]) class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : argparse.ArgumentParser , UpperCAmelCase_ : argparse.ArgumentParser ) ->Optional[int]: """simple docstring""" self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): snake_case_ = {k: v for k, v in vars(UpperCAmelCase_ ).items() if k != """container"""} snake_case_ = {k: v for k, v in vars(UpperCAmelCase_ ).items() if k != """container"""} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("""choices""" , UpperCAmelCase_ ) and yy.get("""choices""" , UpperCAmelCase_ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["""type"""](UpperCAmelCase_ ) , yy["""type"""](UpperCAmelCase_ ) ) del xx["type"], yy["type"] self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : int ) ->Any: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--bar""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--baz""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--flag""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ , const=UpperCAmelCase_ , nargs="""?""" ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = ["""--foo""", """1""", """--baz""", """quux""", """--bar""", """0.5"""] ((snake_case_) , ) = parser.parse_args_into_dataclasses(UpperCAmelCase_ , look_for_args_file=UpperCAmelCase_ ) self.assertFalse(example.flag ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=42 , type=UpperCAmelCase_ ) expected.add_argument("""--baz""" , default="""toto""" , type=UpperCAmelCase_ , help="""help message""" ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ , const=UpperCAmelCase_ , nargs="""?""" ) expected.add_argument("""--baz""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ , const=UpperCAmelCase_ , nargs="""?""" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("""--no_baz""" , action="""store_false""" , default=UpperCAmelCase_ , dest="""baz""" ) expected.add_argument("""--opt""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ ) snake_case_ = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(UpperCAmelCase_ ) for dataclass_type in dataclass_types: snake_case_ = HfArgumentParser(UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """--no_baz"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """--baz"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """True""", """--baz""", """True""", """--opt""", """True"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """False""", """--baz""", """False""", """--opt""", """False"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) def lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=["""titi""", """toto""", 42] , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) snake_case_ = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) snake_case_ = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) snake_case_ = parser.parse_args_into_dataclasses(["""--foo""", """titi"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) snake_case_ = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) snake_case_ = parser.parse_args_into_dataclasses(["""--foo""", """42"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" @dataclass class __A : '''simple docstring''' __lowercase: Literal["titi", "toto", 42] = "toto" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=("""titi""", """toto""", 42) , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) snake_case_ = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) snake_case_ = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo_int""" , nargs="""+""" , default=[] , type=UpperCAmelCase_ ) expected.add_argument("""--bar_int""" , nargs="""+""" , default=[1, 2, 3] , type=UpperCAmelCase_ ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=UpperCAmelCase_ ) expected.add_argument("""--foo_float""" , nargs="""+""" , default=[0.1, 0.2, 0.3] , type=UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual( UpperCAmelCase_ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["""Hallo""", """Bonjour""", """Hello"""] , foo_float=[0.1, 0.2, 0.3] ) , ) snake_case_ = parser.parse_args("""--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7""".split() ) self.assertEqual(UpperCAmelCase_ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["""a""", """b""", """c"""] , foo_float=[0.1, 0.7] ) ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=UpperCAmelCase_ , type=UpperCAmelCase_ ) expected.add_argument("""--bar""" , default=UpperCAmelCase_ , type=UpperCAmelCase_ , help="""help message""" ) expected.add_argument("""--baz""" , default=UpperCAmelCase_ , type=UpperCAmelCase_ ) expected.add_argument("""--ces""" , nargs="""+""" , default=[] , type=UpperCAmelCase_ ) expected.add_argument("""--des""" , nargs="""+""" , default=[] , type=UpperCAmelCase_ ) snake_case_ = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(UpperCAmelCase_ ) for dataclass_type in dataclass_types: snake_case_ = HfArgumentParser(UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , bar=UpperCAmelCase_ , baz=UpperCAmelCase_ , ces=[] , des=[] ) ) snake_case_ = parser.parse_args("""--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3""".split() ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=12 , bar=3.14 , baz="""42""" , ces=["""a""", """b""", """c"""] , des=[1, 2, 3] ) ) def lowerCAmelCase ( self : Optional[Any] ) ->Optional[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--required_list""" , nargs="""+""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--required_str""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=UpperCAmelCase_ , ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=UpperCAmelCase_ , ) expected.add_argument("""--opt""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ ) expected.add_argument("""--baz""" , default="""toto""" , type=UpperCAmelCase_ , help="""help message""" ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } snake_case_ = parser.parse_dict(UpperCAmelCase_ )[0] snake_case_ = BasicExample(**UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, """extra""": 42, } self.assertRaises(UpperCAmelCase_ , parser.parse_dict , UpperCAmelCase_ , allow_extra_keys=UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = os.path.join(UpperCAmelCase_ , """temp_json""" ) os.mkdir(UpperCAmelCase_ ) with open(temp_local_path + """.json""" , """w+""" ) as f: json.dump(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_yaml_file(Path(temp_local_path + """.json""" ) )[0] snake_case_ = BasicExample(**UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = os.path.join(UpperCAmelCase_ , """temp_yaml""" ) os.mkdir(UpperCAmelCase_ ) with open(temp_local_path + """.yaml""" , """w+""" ) as f: yaml.dump(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_yaml_file(Path(temp_local_path + """.yaml""" ) )[0] snake_case_ = BasicExample(**UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ )
347
0
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class _A ( _a ): """simple docstring""" UpperCAmelCase : str = """naver-clova-ix/donut-base-finetuned-docvqa""" UpperCAmelCase : Tuple = ( """This is a tool that answers a question about an document (pdf). It takes an input named `document` which """ """should be the document containing the information, as well as a `question` that is the question about the """ """document. It returns a text that contains the answer to the question.""" ) UpperCAmelCase : List[str] = """document_qa""" UpperCAmelCase : str = AutoProcessor UpperCAmelCase : Optional[int] = VisionEncoderDecoderModel UpperCAmelCase : int = ["""image""", """text"""] UpperCAmelCase : int = ["""text"""] def __init__( self : Tuple , *__UpperCAmelCase : Union[str, Any] , **__UpperCAmelCase : Any): if not is_vision_available(): raise ValueError("Pillow must be installed to use the DocumentQuestionAnsweringTool.") super().__init__(*__UpperCAmelCase , **__UpperCAmelCase) def __snake_case ( self : Tuple , __UpperCAmelCase : "Image" , __UpperCAmelCase : str): a : Any = "<s_docvqa><s_question>{user_input}</s_question><s_answer>" a : Union[str, Any] = task_prompt.replace("{user_input}" , __UpperCAmelCase) a : Optional[Any] = self.pre_processor.tokenizer( __UpperCAmelCase , add_special_tokens=__UpperCAmelCase , return_tensors="pt").input_ids a : Any = self.pre_processor(__UpperCAmelCase , return_tensors="pt").pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def __snake_case ( self : int , __UpperCAmelCase : int): return self.model.generate( inputs["pixel_values"].to(self.device) , decoder_input_ids=inputs["decoder_input_ids"].to(self.device) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=__UpperCAmelCase , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=__UpperCAmelCase , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=__UpperCAmelCase , ).sequences def __snake_case ( self : str , __UpperCAmelCase : List[Any]): a : Union[str, Any] = self.pre_processor.batch_decode(__UpperCAmelCase)[0] a : Optional[Any] = sequence.replace(self.pre_processor.tokenizer.eos_token , "") a : Any = sequence.replace(self.pre_processor.tokenizer.pad_token , "") a : Optional[Any] = re.sub(r"<.*?>" , "" , __UpperCAmelCase , count=1).strip() # remove first task start token a : List[str] = self.pre_processor.tokenajson(__UpperCAmelCase) return sequence["answer"]
40
"""simple docstring""" import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy __SCREAMING_SNAKE_CASE : Any = logging.getLogger(__name__) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , ) -> Optional[Any]: snake_case_ = bnb_quantization_config.load_in_abit snake_case_ = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( """You have a version of `bitsandbytes` that is not compatible with 8bit quantization,""" """ make sure you have the latest version of `bitsandbytes` installed.""" ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( """You have a version of `bitsandbytes` that is not compatible with 4bit quantization,""" """make sure you have the latest version of `bitsandbytes` installed.""" ) snake_case_ = [] # custom device map if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(device_map.keys() ) > 1: snake_case_ = [key for key, value in device_map.items() if value in ["""disk""", """cpu"""]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: snake_case_ = get_keys_to_not_convert(_SCREAMING_SNAKE_CASE ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(_SCREAMING_SNAKE_CASE ) snake_case_ = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: snake_case_ = [] snake_case_ = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(_SCREAMING_SNAKE_CASE ) # compatibility with peft snake_case_ = load_in_abit snake_case_ = load_in_abit snake_case_ = get_parameter_device(_SCREAMING_SNAKE_CASE ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( """It is not recommended to quantize a loaded model. """ """The model should be instantiated under the `init_empty_weights` context manager.""" ) snake_case_ = replace_with_bnb_layers(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE ) # convert param to the right dtype snake_case_ = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: snake_case_ = name.replace(""".weight""" , """""" ).replace(""".bias""" , """""" ) snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(_SCREAMING_SNAKE_CASE ): param.to(_SCREAMING_SNAKE_CASE ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info( f"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" """We move the model to cuda.""" ) return model elif weights_location is None: raise RuntimeError( f"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): snake_case_ = replace_with_bnb_layers( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE ) snake_case_ = get_quantized_model_device_map( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_memory=_SCREAMING_SNAKE_CASE , no_split_module_classes=_SCREAMING_SNAKE_CASE , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): snake_case_ = True snake_case_ = any(x in list(device_map.values() ) for x in ["""cpu""", """disk"""] ) load_checkpoint_in_model( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=bnb_quantization_config.torch_dtype , offload_folder=_SCREAMING_SNAKE_CASE , offload_state_dict=_SCREAMING_SNAKE_CASE , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(_SCREAMING_SNAKE_CASE , device_map=_SCREAMING_SNAKE_CASE , offload_dir=_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: if device_map is None: if torch.cuda.is_available(): snake_case_ = {"""""": torch.cuda.current_device()} else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info("""The device_map was not initialized.""" """Setting device_map to `{'':torch.cuda.current_device()}`.""" ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( """If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or """ """'sequential'.""" ) snake_case_ = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) snake_case_ = {} snake_case_ = special_dtypes snake_case_ = no_split_module_classes snake_case_ = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": snake_case_ = get_balanced_memory( _SCREAMING_SNAKE_CASE , low_zero=(device_map == """balanced_low_0""") , max_memory=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) snake_case_ = max_memory snake_case_ = infer_auto_device_map(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # check if don't have any quantized module on the cpu snake_case_ = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules snake_case_ = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( """ Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules in `torch_dtype`, you need to pass a custom `device_map` to `load_and_quantize_model`. Check https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk for more details. """ ) else: logger.info( """Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit""" ) del device_map_without_some_modules return device_map def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: if modules_to_not_convert is None: snake_case_ = [] snake_case_ , snake_case_ = _replace_with_bnb_layers( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , ) -> List[Any]: snake_case_ = False for name, module in model.named_children(): if current_key_name is None: snake_case_ = [] current_key_name.append(_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` snake_case_ = """.""".join(_SCREAMING_SNAKE_CASE ) snake_case_ = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: snake_case_ = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: snake_case_ = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=_SCREAMING_SNAKE_CASE , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: snake_case_ = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("""load_in_8bit and load_in_4bit can't be both False""" ) snake_case_ = module.weight.data if module.bias is not None: snake_case_ = module.bias.data bnb_module.requires_grad_(_SCREAMING_SNAKE_CASE ) setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = True if len(list(module.children() ) ) > 0: snake_case_ , snake_case_ = _replace_with_bnb_layers( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def _a ( _SCREAMING_SNAKE_CASE ) -> Any: # Create a copy of the model with init_empty_weights(): snake_case_ = deepcopy(_SCREAMING_SNAKE_CASE ) # this has 0 cost since it is done inside `init_empty_weights` context manager` snake_case_ = find_tied_parameters(_SCREAMING_SNAKE_CASE ) # For compatibility with Accelerate < 0.18 if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: snake_case_ = sum(_SCREAMING_SNAKE_CASE , [] ) snake_case_ = len(_SCREAMING_SNAKE_CASE ) > 0 # Check if it is a base model snake_case_ = False if hasattr(_SCREAMING_SNAKE_CASE , """base_model_prefix""" ): snake_case_ = not hasattr(_SCREAMING_SNAKE_CASE , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head snake_case_ = list(model.named_children() ) snake_case_ = [list_modules[-1][0]] # add last module together with tied weights snake_case_ = set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE ) snake_case_ = list(set(_SCREAMING_SNAKE_CASE ) ) + list(_SCREAMING_SNAKE_CASE ) # remove ".weight" from the keys snake_case_ = [""".weight""", """.bias"""] snake_case_ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: snake_case_ = name.replace(_SCREAMING_SNAKE_CASE , """""" ) filtered_module_names.append(_SCREAMING_SNAKE_CASE ) return filtered_module_names def _a ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: for m in model.modules(): if isinstance(_SCREAMING_SNAKE_CASE , bnb.nn.Linearabit ): return True return False def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: return next(parameter.parameters() ).device def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: # if it is not quantized, we quantize and offload the quantized weights and the SCB stats if fpaa_statistics is None: set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 0 , dtype=_SCREAMING_SNAKE_CASE , value=_SCREAMING_SNAKE_CASE ) snake_case_ = param_name snake_case_ = model if "." in tensor_name: snake_case_ = tensor_name.split(""".""" ) for split in splits[:-1]: snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if new_module is None: raise ValueError(f"""{module} has no attribute {split}.""" ) snake_case_ = new_module snake_case_ = splits[-1] # offload weights snake_case_ = False offload_weight(module._parameters[tensor_name] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) if hasattr(module._parameters[tensor_name] , """SCB""" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("""weight""" , """SCB""" ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE , ) else: offload_weight(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) offload_weight(_SCREAMING_SNAKE_CASE , param_name.replace("""weight""" , """SCB""" ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , """meta""" , dtype=_SCREAMING_SNAKE_CASE , value=torch.empty(*param.size() ) )
347
0
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> int: assert column_title.isupper() lowerCamelCase__ : Dict = 0 lowerCamelCase__ : str = len(UpperCamelCase ) - 1 lowerCamelCase__ : str = 0 while index >= 0: lowerCamelCase__ : List[str] = (ord(column_title[index] ) - 64) * pow(26 , UpperCamelCase ) answer += value power += 1 index -= 1 return answer if __name__ == "__main__": from doctest import testmod testmod()
41
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple = { 'microsoft/beit-base-patch16-224-pt22k': ( 'https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json' ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __A (snake_case__): '''simple docstring''' __lowercase: Optional[int] = """beit""" def __init__( self : List[str] , UpperCAmelCase_ : List[Any]=8_192 , UpperCAmelCase_ : Dict=768 , UpperCAmelCase_ : int=12 , UpperCAmelCase_ : Tuple=12 , UpperCAmelCase_ : List[Any]=3_072 , UpperCAmelCase_ : Tuple="gelu" , UpperCAmelCase_ : Dict=0.0 , UpperCAmelCase_ : List[str]=0.0 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : Optional[Any]=1E-12 , UpperCAmelCase_ : int=224 , UpperCAmelCase_ : Tuple=16 , UpperCAmelCase_ : List[str]=3 , UpperCAmelCase_ : int=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Tuple=False , UpperCAmelCase_ : int=False , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Dict=[3, 5, 7, 11] , UpperCAmelCase_ : Tuple=[1, 2, 3, 6] , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[Any]=0.4 , UpperCAmelCase_ : Optional[Any]=256 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : int=False , UpperCAmelCase_ : Tuple=255 , **UpperCAmelCase_ : List[str] , ) ->Optional[Any]: """simple docstring""" super().__init__(**UpperCAmelCase_ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = use_mask_token snake_case_ = use_absolute_position_embeddings snake_case_ = use_relative_position_bias snake_case_ = use_shared_relative_position_bias snake_case_ = layer_scale_init_value snake_case_ = drop_path_rate snake_case_ = use_mean_pooling # decode head attributes (semantic segmentation) snake_case_ = out_indices snake_case_ = pool_scales # auxiliary head attributes (semantic segmentation) snake_case_ = use_auxiliary_head snake_case_ = auxiliary_loss_weight snake_case_ = auxiliary_channels snake_case_ = auxiliary_num_convs snake_case_ = auxiliary_concat_input snake_case_ = semantic_loss_ignore_index class __A (snake_case__): '''simple docstring''' __lowercase: List[Any] = version.parse("""1.11""") @property def lowerCAmelCase ( self : Dict ) ->Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def lowerCAmelCase ( self : Any ) ->float: """simple docstring""" return 1E-4
347
0
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class __UpperCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowerCamelCase ( self ): """simple docstring""" torch.manual_seed(0 ) _snake_case = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return model @property def lowerCamelCase ( self ): """simple docstring""" torch.manual_seed(0 ) _snake_case = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , cross_attention_dim=10 , ) return model @property def lowerCamelCase ( self ): """simple docstring""" torch.manual_seed(0 ) _snake_case = AutoencoderKL( sample_size=(1_28, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') , ) _snake_case = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return vqvae, unet @slow def lowerCamelCase ( self ): """simple docstring""" _snake_case = 'cpu' # ensure determinism for the device-dependent torch.Generator _snake_case = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) _snake_case = DDPMScheduler() _snake_case = AudioDiffusionPipeline(vqvae=lowerCAmelCase_ , unet=self.dummy_unet , mel=lowerCAmelCase_ , scheduler=lowerCAmelCase_ ) _snake_case = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _snake_case = torch.Generator(device=lowerCAmelCase_ ).manual_seed(42 ) _snake_case = pipe(generator=lowerCAmelCase_ , steps=4 ) _snake_case = output.audios[0] _snake_case = output.images[0] _snake_case = torch.Generator(device=lowerCAmelCase_ ).manual_seed(42 ) _snake_case = pipe(generator=lowerCAmelCase_ , steps=4 , return_dict=lowerCAmelCase_ ) _snake_case = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) _snake_case = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] _snake_case = np.frombuffer(image_from_tuple.tobytes() , dtype='uint8' )[:10] _snake_case = np.array([69, 2_55, 2_55, 2_55, 0, 0, 77, 1_81, 12, 1_27] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 _snake_case = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) _snake_case = DDIMScheduler() _snake_case = self.dummy_vqvae_and_unet _snake_case = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=lowerCAmelCase_ , scheduler=lowerCAmelCase_ ) _snake_case = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) np.random.seed(0 ) _snake_case = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) _snake_case = torch.Generator(device=lowerCAmelCase_ ).manual_seed(42 ) _snake_case = pipe(raw_audio=lowerCAmelCase_ , generator=lowerCAmelCase_ , start_step=5 , steps=10 ) _snake_case = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) _snake_case = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] _snake_case = np.array([1_20, 1_17, 1_10, 1_09, 1_38, 1_67, 1_38, 1_48, 1_32, 1_21] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 _snake_case = self.dummy_unet_condition _snake_case = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=lowerCAmelCase_ , mel=lowerCAmelCase_ , scheduler=lowerCAmelCase_ ) _snake_case = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) np.random.seed(0 ) _snake_case = torch.rand((1, 1, 10) ) _snake_case = pipe(generator=lowerCAmelCase_ , encoding=lowerCAmelCase_ ) _snake_case = output.images[0] _snake_case = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] _snake_case = np.array([1_07, 1_03, 1_20, 1_27, 1_42, 1_22, 1_13, 1_22, 97, 1_11] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class __UpperCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase ( self ): """simple docstring""" _snake_case = torch_device _snake_case = DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256' ) _snake_case = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _snake_case = torch.Generator(device=lowerCAmelCase_ ).manual_seed(42 ) _snake_case = pipe(generator=lowerCAmelCase_ ) _snake_case = output.audios[0] _snake_case = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] _snake_case = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] _snake_case = np.array([1_51, 1_67, 1_54, 1_44, 1_22, 1_34, 1_21, 1_05, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
42
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : List[Any] = {'vocab_file': 'spiece.model'} __SCREAMING_SNAKE_CASE : int = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', } } # TODO(PVP) - this should be removed in Transformers v5 __SCREAMING_SNAKE_CASE : Dict = { 't5-small': 512, 't5-base': 512, 't5-large': 512, 't5-3b': 512, 't5-11b': 512, } __SCREAMING_SNAKE_CASE : Optional[int] = '▁' class __A (snake_case__): '''simple docstring''' __lowercase: Optional[int] = VOCAB_FILES_NAMES __lowercase: Any = PRETRAINED_VOCAB_FILES_MAP __lowercase: Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase: List[str] = ["""input_ids""", """attention_mask"""] def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any]="</s>" , UpperCAmelCase_ : Optional[Any]="<unk>" , UpperCAmelCase_ : Any="<pad>" , UpperCAmelCase_ : Tuple=100 , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , UpperCAmelCase_ : Optional[int]=True , **UpperCAmelCase_ : Dict , ) ->None: """simple docstring""" if extra_ids > 0 and additional_special_tokens is None: snake_case_ = [F"""<extra_id_{i}>""" for i in range(UpperCAmelCase_ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens snake_case_ = len(set(filter(lambda UpperCAmelCase_ : bool("""extra_id""" in str(UpperCAmelCase_ ) ) , UpperCAmelCase_ ) ) ) if extra_tokens != extra_ids: raise ValueError( F"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are""" """ provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids""" """ tokens""" ) if legacy: logger.warning_once( F"""You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to""" """ read the related pull request available at https://github.com/huggingface/transformers/pull/24565""" ) snake_case_ = legacy snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , extra_ids=UpperCAmelCase_ , additional_special_tokens=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , legacy=UpperCAmelCase_ , **UpperCAmelCase_ , ) snake_case_ = vocab_file snake_case_ = extra_ids snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) @staticmethod def lowerCAmelCase ( UpperCAmelCase_ : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any] ) ->Union[str, Any]: """simple docstring""" if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: snake_case_ = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( """This tokenizer was incorrectly instantiated with a model max length of""" F""" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this""" """ behavior is kept to avoid breaking backwards compatibility when padding/encoding with""" """ `truncation is True`.\n- Be aware that you SHOULD NOT rely on""" F""" {pretrained_model_name_or_path} automatically truncating your input to""" F""" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences""" F""" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with""" """ `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please""" """ instantiate this tokenizer with `model_max_length` set to your preferred value.""" , UpperCAmelCase_ , ) return max_model_length @property def lowerCAmelCase ( self : Optional[Any] ) ->Optional[Any]: """simple docstring""" return self.sp_model.get_piece_size() + self._extra_ids def lowerCAmelCase ( self : Any ) ->Optional[int]: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(UpperCAmelCase_ )) + [1] return ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" return list( set(filter(lambda UpperCAmelCase_ : bool(re.search(R"""<extra_id_\d+>""" , UpperCAmelCase_ ) ) is not None , self.additional_special_tokens ) ) ) def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" return [self._convert_token_to_id(UpperCAmelCase_ ) for token in self.get_sentinel_tokens()] def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[int] ) ->List[int]: """simple docstring""" if len(UpperCAmelCase_ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F"""This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated""" """ eos tokens being added.""" ) return token_ids else: return token_ids + [self.eos_token_id] def lowerCAmelCase ( self : str , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = self._add_eos_if_not_present(UpperCAmelCase_ ) if token_ids_a is None: return token_ids_a else: snake_case_ = self._add_eos_if_not_present(UpperCAmelCase_ ) return token_ids_a + token_ids_a def __getstate__( self : Optional[Any] ) ->Tuple: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Optional[Any] , UpperCAmelCase_ : List[Any] ) ->List[Any]: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : "TextInput" , **UpperCAmelCase_ : Tuple ) ->List[str]: """simple docstring""" if not self.legacy: snake_case_ = SPIECE_UNDERLINE + text.replace(UpperCAmelCase_ , """ """ ) return super().tokenize(UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Any ) ->Tuple: """simple docstring""" if not self.legacy: snake_case_ = text.startswith(UpperCAmelCase_ ) if is_first: snake_case_ = text[1:] snake_case_ = self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) if not self.legacy and not is_first and not text.startswith(""" """ ) and tokens[0].startswith(UpperCAmelCase_ ): snake_case_ = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" if token.startswith("""<extra_id_""" ): snake_case_ = re.match(R"""<extra_id_(\d+)>""" , UpperCAmelCase_ ) snake_case_ = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(UpperCAmelCase_ ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" if index < self.sp_model.get_piece_size(): snake_case_ = self.sp_model.IdToPiece(UpperCAmelCase_ ) else: snake_case_ = F"""<extra_id_{self.vocab_size - 1 - index}>""" return token def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[str] ) ->Optional[Any]: """simple docstring""" snake_case_ = [] snake_case_ = """""" snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase_ ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(UpperCAmelCase_ ) snake_case_ = False out_string += self.sp_model.decode(UpperCAmelCase_ ) return out_string.strip() def lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,)
347
0
def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError('''multiplicative_persistence() only accepts integral values''' ) if num < 0: raise ValueError('''multiplicative_persistence() does not accept negative values''' ) __UpperCamelCase :int = 0 __UpperCamelCase :List[Any] = str(SCREAMING_SNAKE_CASE ) while len(SCREAMING_SNAKE_CASE ) != 1: __UpperCamelCase :List[Any] = [int(SCREAMING_SNAKE_CASE ) for i in num_string] __UpperCamelCase :Tuple = 1 for i in range(0 , len(SCREAMING_SNAKE_CASE ) ): total *= numbers[i] __UpperCamelCase :Any = str(SCREAMING_SNAKE_CASE ) steps += 1 return steps def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError('''additive_persistence() only accepts integral values''' ) if num < 0: raise ValueError('''additive_persistence() does not accept negative values''' ) __UpperCamelCase :Optional[int] = 0 __UpperCamelCase :Optional[int] = str(SCREAMING_SNAKE_CASE ) while len(SCREAMING_SNAKE_CASE ) != 1: __UpperCamelCase :Optional[int] = [int(SCREAMING_SNAKE_CASE ) for i in num_string] __UpperCamelCase :Tuple = 0 for i in range(0 , len(SCREAMING_SNAKE_CASE ) ): total += numbers[i] __UpperCamelCase :Any = str(SCREAMING_SNAKE_CASE ) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
43
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE = 1_000_000 ) -> int: snake_case_ = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , _SCREAMING_SNAKE_CASE ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
347
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _a : Tuple = { 'configuration_wav2vec2': ['WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Wav2Vec2Config'], 'feature_extraction_wav2vec2': ['Wav2Vec2FeatureExtractor'], 'processing_wav2vec2': ['Wav2Vec2Processor'], 'tokenization_wav2vec2': ['Wav2Vec2CTCTokenizer', 'Wav2Vec2Tokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Any = [ 'WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST', 'Wav2Vec2ForAudioFrameClassification', 'Wav2Vec2ForCTC', 'Wav2Vec2ForMaskedLM', 'Wav2Vec2ForPreTraining', 'Wav2Vec2ForSequenceClassification', 'Wav2Vec2ForXVector', 'Wav2Vec2Model', 'Wav2Vec2PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = [ 'TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFWav2Vec2ForCTC', 'TFWav2Vec2Model', 'TFWav2Vec2PreTrainedModel', 'TFWav2Vec2ForSequenceClassification', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = [ 'FlaxWav2Vec2ForCTC', 'FlaxWav2Vec2ForPreTraining', 'FlaxWav2Vec2Model', 'FlaxWav2Vec2PreTrainedModel', ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys _a : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
44
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: print(f"""Vertex\tShortest Distance from vertex {src}""" ) for i, d in enumerate(_SCREAMING_SNAKE_CASE ): print(f"""{i}\t\t{d}""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: for j in range(_SCREAMING_SNAKE_CASE ): snake_case_ , snake_case_ , snake_case_ = (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 _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[float]: snake_case_ = [float("""inf""" )] * vertex_count snake_case_ = 0.0 for _ in range(vertex_count - 1 ): for j in range(_SCREAMING_SNAKE_CASE ): snake_case_ , snake_case_ , snake_case_ = (graph[j][k] for k in ["""src""", """dst""", """weight"""]) if distance[u] != float("""inf""" ) and distance[u] + w < distance[v]: snake_case_ = distance[u] + w snake_case_ = check_negative_cycle(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if negative_cycle_exists: raise Exception("""Negative cycle found""" ) return distance if __name__ == "__main__": import doctest doctest.testmod() __SCREAMING_SNAKE_CASE : int = int(input('Enter number of vertices: ').strip()) __SCREAMING_SNAKE_CASE : Dict = 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 : List[str] = ( int(x) for x in input('Enter source, destination, weight: ').strip().split(' ') ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'src': src, 'dst': dest, 'weight': weight} __SCREAMING_SNAKE_CASE : Union[str, Any] = int(input('\nEnter shortest path source:').strip()) __SCREAMING_SNAKE_CASE : str = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
347
0
"""simple docstring""" class __lowerCAmelCase : # Public class to implement a graph '''simple docstring''' def __init__( self , _a , _a , _a ): __a = row __a = col __a = graph def __UpperCAmelCase ( self , _a , _a , _a ): return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def __UpperCAmelCase ( self , _a , _a , _a ): # Checking all 8 elements surrounding nth element __a = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order __a = [-1, 0, 1, -1, 1, -1, 0, 1] __a = True # Make those cells visited for k in range(8 ): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , _a ): self.diffs(i + row_nbr[k] , j + col_nbr[k] , _a ) def __UpperCAmelCase ( self ): # And finally, count all islands. __a = [[False for j in range(self.COL )] for i in range(self.ROW )] __a = 0 for i in range(self.ROW ): for j in range(self.COL ): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(_a , _a , _a ) count += 1 return count
45
"""simple docstring""" import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) __SCREAMING_SNAKE_CASE : List[str] = logging.getLogger(__name__) __SCREAMING_SNAKE_CASE : str = tf.data.AUTOTUNE def _a ( ) -> List[str]: snake_case_ = argparse.ArgumentParser(description="""Train a masked language model on TPU.""" ) parser.add_argument( """--pretrained_model_config""" , type=_SCREAMING_SNAKE_CASE , default="""roberta-base""" , help="""The model config to use. Note that we don't copy the model's weights, only the config!""" , ) parser.add_argument( """--tokenizer""" , type=_SCREAMING_SNAKE_CASE , default="""unigram-tokenizer-wikitext""" , help="""The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model's vocab size.""" , ) parser.add_argument( """--per_replica_batch_size""" , type=_SCREAMING_SNAKE_CASE , default=8 , help="""Batch size per TPU core.""" , ) parser.add_argument( """--no_tpu""" , action="""store_true""" , help="""If set, run on CPU and don't try to initialize a TPU. Useful for debugging on non-TPU instances.""" , ) parser.add_argument( """--tpu_name""" , type=_SCREAMING_SNAKE_CASE , help="""Name of TPU resource to initialize. Should be blank on Colab, and 'local' on TPU VMs.""" , default="""local""" , ) parser.add_argument( """--tpu_zone""" , type=_SCREAMING_SNAKE_CASE , help="""Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes.""" , ) parser.add_argument( """--gcp_project""" , type=_SCREAMING_SNAKE_CASE , help="""Google cloud project name. Only used for non-Colab TPU nodes.""" ) parser.add_argument( """--bfloat16""" , action="""store_true""" , help="""Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU.""" , ) parser.add_argument( """--train_dataset""" , type=_SCREAMING_SNAKE_CASE , help="""Path to training dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--shuffle_buffer_size""" , type=_SCREAMING_SNAKE_CASE , default=2**18 , help="""Size of the shuffle buffer (in samples)""" , ) parser.add_argument( """--eval_dataset""" , type=_SCREAMING_SNAKE_CASE , help="""Path to evaluation dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--num_epochs""" , type=_SCREAMING_SNAKE_CASE , default=1 , help="""Number of epochs to train for.""" , ) parser.add_argument( """--learning_rate""" , type=_SCREAMING_SNAKE_CASE , default=1E-4 , help="""Learning rate to use for training.""" , ) parser.add_argument( """--weight_decay_rate""" , type=_SCREAMING_SNAKE_CASE , default=1E-3 , help="""Weight decay rate to use for training.""" , ) parser.add_argument( """--max_length""" , type=_SCREAMING_SNAKE_CASE , default=512 , help="""Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py""" , ) parser.add_argument( """--mlm_probability""" , type=_SCREAMING_SNAKE_CASE , default=0.15 , help="""Fraction of tokens to mask during training.""" , ) parser.add_argument("""--output_dir""" , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help="""Path to save model checkpoints to.""" ) parser.add_argument("""--hub_model_id""" , type=_SCREAMING_SNAKE_CASE , help="""Model ID to upload to on the Hugging Face Hub.""" ) snake_case_ = parser.parse_args() return args def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: try: if args.tpu_name: snake_case_ = tf.distribute.cluster_resolver.TPUClusterResolver( args.tpu_name , zone=args.tpu_zone , project=args.gcp_project ) else: snake_case_ = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: raise RuntimeError( """Couldn't connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or """ """--gcp_project. When running on a TPU VM, use --tpu_name local.""" ) tf.config.experimental_connect_to_cluster(_SCREAMING_SNAKE_CASE ) tf.tpu.experimental.initialize_tpu_system(_SCREAMING_SNAKE_CASE ) return tpu def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = 0 for file in file_list: snake_case_ = file.split("""/""" )[-1] snake_case_ = re.search(r"""-\d+-(\d+)\.tfrecord""" , _SCREAMING_SNAKE_CASE ).group(1 ) snake_case_ = int(_SCREAMING_SNAKE_CASE ) num_samples += sample_count return num_samples def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Union[str, Any]: snake_case_ = count_samples(_SCREAMING_SNAKE_CASE ) snake_case_ = tf.data.Dataset.from_tensor_slices(_SCREAMING_SNAKE_CASE ) if shuffle: snake_case_ = dataset.shuffle(len(_SCREAMING_SNAKE_CASE ) ) snake_case_ = tf.data.TFRecordDataset(_SCREAMING_SNAKE_CASE , num_parallel_reads=_SCREAMING_SNAKE_CASE ) # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here snake_case_ = dataset.apply(tf.data.experimental.assert_cardinality(_SCREAMING_SNAKE_CASE ) ) snake_case_ = dataset.map(_SCREAMING_SNAKE_CASE , num_parallel_calls=_SCREAMING_SNAKE_CASE ) if shuffle: assert shuffle_buffer_size is not None snake_case_ = dataset.shuffle(args.shuffle_buffer_size ) snake_case_ = dataset.batch(_SCREAMING_SNAKE_CASE , drop_remainder=_SCREAMING_SNAKE_CASE ) snake_case_ = dataset.map(_SCREAMING_SNAKE_CASE , num_parallel_calls=_SCREAMING_SNAKE_CASE ) snake_case_ = dataset.prefetch(_SCREAMING_SNAKE_CASE ) return dataset def _a ( _SCREAMING_SNAKE_CASE ) -> List[Any]: if not args.no_tpu: snake_case_ = initialize_tpu(_SCREAMING_SNAKE_CASE ) snake_case_ = tf.distribute.TPUStrategy(_SCREAMING_SNAKE_CASE ) else: snake_case_ = tf.distribute.OneDeviceStrategy(device="""/gpu:0""" ) if args.bfloataa: tf.keras.mixed_precision.set_global_policy("""mixed_bfloat16""" ) snake_case_ = AutoTokenizer.from_pretrained(args.tokenizer ) snake_case_ = AutoConfig.from_pretrained(args.pretrained_model_config ) snake_case_ = tokenizer.vocab_size snake_case_ = tf.io.gfile.glob(os.path.join(args.train_dataset , """*.tfrecord""" ) ) if not training_records: raise ValueError(f"""No .tfrecord files found in {args.train_dataset}.""" ) snake_case_ = tf.io.gfile.glob(os.path.join(args.eval_dataset , """*.tfrecord""" ) ) if not eval_records: raise ValueError(f"""No .tfrecord files found in {args.eval_dataset}.""" ) snake_case_ = count_samples(_SCREAMING_SNAKE_CASE ) snake_case_ = num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync) snake_case_ = steps_per_epoch * args.num_epochs with strategy.scope(): snake_case_ = TFAutoModelForMaskedLM.from_config(_SCREAMING_SNAKE_CASE ) model(model.dummy_inputs ) # Pass some dummy inputs through the model to ensure all the weights are built snake_case_ , snake_case_ = create_optimizer( num_train_steps=_SCREAMING_SNAKE_CASE , num_warmup_steps=total_train_steps // 20 , init_lr=args.learning_rate , weight_decay_rate=args.weight_decay_rate , ) # Transformers models compute the right loss for their task by default when labels are passed, and will # use this for training unless you specify your own loss function in compile(). model.compile(optimizer=_SCREAMING_SNAKE_CASE , metrics=["""accuracy"""] ) def decode_fn(_SCREAMING_SNAKE_CASE ): snake_case_ = { """input_ids""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), """attention_mask""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), } return tf.io.parse_single_example(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can # use their methods in our data pipeline. snake_case_ = DataCollatorForLanguageModeling( tokenizer=_SCREAMING_SNAKE_CASE , mlm_probability=args.mlm_probability , mlm=_SCREAMING_SNAKE_CASE , return_tensors="""tf""" ) def mask_with_collator(_SCREAMING_SNAKE_CASE ): # TF really needs an isin() function snake_case_ = ( ~tf.cast(batch["""attention_mask"""] , tf.bool ) | (batch["""input_ids"""] == tokenizer.cls_token_id) | (batch["""input_ids"""] == tokenizer.sep_token_id) ) snake_case_ , snake_case_ = data_collator.tf_mask_tokens( batch["""input_ids"""] , vocab_size=len(_SCREAMING_SNAKE_CASE ) , mask_token_id=tokenizer.mask_token_id , special_tokens_mask=_SCREAMING_SNAKE_CASE , ) return batch snake_case_ = args.per_replica_batch_size * strategy.num_replicas_in_sync snake_case_ = prepare_dataset( _SCREAMING_SNAKE_CASE , decode_fn=_SCREAMING_SNAKE_CASE , mask_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , shuffle=_SCREAMING_SNAKE_CASE , shuffle_buffer_size=args.shuffle_buffer_size , ) snake_case_ = prepare_dataset( _SCREAMING_SNAKE_CASE , decode_fn=_SCREAMING_SNAKE_CASE , mask_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , shuffle=_SCREAMING_SNAKE_CASE , ) snake_case_ = [] if args.hub_model_id: callbacks.append( PushToHubCallback(output_dir=args.output_dir , hub_model_id=args.hub_model_id , tokenizer=_SCREAMING_SNAKE_CASE ) ) model.fit( _SCREAMING_SNAKE_CASE , validation_data=_SCREAMING_SNAKE_CASE , epochs=args.num_epochs , callbacks=_SCREAMING_SNAKE_CASE , ) model.save_pretrained(args.output_dir ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = parse_args() main(args)
347
0
"""simple docstring""" from math import pow def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int , ): '''simple docstring''' if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 return current_sum, solutions_count lowerCAmelCase = int(pow(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) if current_sum + i_to_n <= needed_sum: # If the sum of the powers is less than needed_sum, then continue adding powers. current_sum += i_to_n lowerCAmelCase , lowerCAmelCase = backtrack( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , current_number + 1 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) current_sum -= i_to_n if i_to_n < needed_sum: # If the power of i is less than needed_sum, then try with the next power. lowerCAmelCase , lowerCAmelCase = backtrack( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , current_number + 1 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return current_sum, solutions_count def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): '''simple docstring''' if not (1 <= needed_sum <= 10_00 and 2 <= power <= 10): raise ValueError( """Invalid input\n""" """needed_sum must be between 1 and 1000, power between 2 and 10.""" ) return backtrack(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 , 0 , 0 )[1] # Return the solutions_count if __name__ == "__main__": import doctest doctest.testmod()
46
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float: if density <= 0: raise ValueError("""Impossible fluid density""" ) if bulk_modulus <= 0: raise ValueError("""Impossible bulk modulus""" ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
347
0
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class A__ ( A__ ): A__ = (DEISMultistepScheduler,) A__ = (('num_inference_steps', 25),) def A ( self : Optional[int] , **_a : str ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE ={ 'num_train_timesteps': 1000, 'beta_start': 0.00_01, 'beta_end': 0.02, 'beta_schedule': 'linear', 'solver_order': 2, } config.update(**_a ) return config def A ( self : Union[str, Any] , _a : Optional[Any]=0 , **_a : Any ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =dict(self.forward_default_kwargs ) _SCREAMING_SNAKE_CASE =kwargs.pop('num_inference_steps' , _a ) _SCREAMING_SNAKE_CASE =self.dummy_sample _SCREAMING_SNAKE_CASE =0.1 * sample _SCREAMING_SNAKE_CASE =[residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: _SCREAMING_SNAKE_CASE =self.get_scheduler_config(**_a ) _SCREAMING_SNAKE_CASE =scheduler_class(**_a ) scheduler.set_timesteps(_a ) # copy over dummy past residuals _SCREAMING_SNAKE_CASE =dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(_a ) _SCREAMING_SNAKE_CASE =scheduler_class.from_pretrained(_a ) new_scheduler.set_timesteps(_a ) # copy over dummy past residuals _SCREAMING_SNAKE_CASE =dummy_past_residuals[: new_scheduler.config.solver_order] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =sample, sample for t in range(_a , time_step + scheduler.config.solver_order + 1 ): _SCREAMING_SNAKE_CASE =scheduler.step(_a , _a , _a , **_a ).prev_sample _SCREAMING_SNAKE_CASE =new_scheduler.step(_a , _a , _a , **_a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def A ( self : Union[str, Any] ) -> Any: '''simple docstring''' pass def A ( self : Optional[int] , _a : List[Any]=0 , **_a : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =dict(self.forward_default_kwargs ) _SCREAMING_SNAKE_CASE =kwargs.pop('num_inference_steps' , _a ) _SCREAMING_SNAKE_CASE =self.dummy_sample _SCREAMING_SNAKE_CASE =0.1 * sample _SCREAMING_SNAKE_CASE =[residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: _SCREAMING_SNAKE_CASE =self.get_scheduler_config() _SCREAMING_SNAKE_CASE =scheduler_class(**_a ) scheduler.set_timesteps(_a ) # copy over dummy past residuals (must be after setting timesteps) _SCREAMING_SNAKE_CASE =dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(_a ) _SCREAMING_SNAKE_CASE =scheduler_class.from_pretrained(_a ) # copy over dummy past residuals new_scheduler.set_timesteps(_a ) # copy over dummy past residual (must be after setting timesteps) _SCREAMING_SNAKE_CASE =dummy_past_residuals[: new_scheduler.config.solver_order] _SCREAMING_SNAKE_CASE =scheduler.step(_a , _a , _a , **_a ).prev_sample _SCREAMING_SNAKE_CASE =new_scheduler.step(_a , _a , _a , **_a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def A ( self : int , _a : Optional[Any]=None , **_a : Any ) -> Optional[int]: '''simple docstring''' if scheduler is None: _SCREAMING_SNAKE_CASE =self.scheduler_classes[0] _SCREAMING_SNAKE_CASE =self.get_scheduler_config(**_a ) _SCREAMING_SNAKE_CASE =scheduler_class(**_a ) _SCREAMING_SNAKE_CASE =self.scheduler_classes[0] _SCREAMING_SNAKE_CASE =self.get_scheduler_config(**_a ) _SCREAMING_SNAKE_CASE =scheduler_class(**_a ) _SCREAMING_SNAKE_CASE =10 _SCREAMING_SNAKE_CASE =self.dummy_model() _SCREAMING_SNAKE_CASE =self.dummy_sample_deter scheduler.set_timesteps(_a ) for i, t in enumerate(scheduler.timesteps ): _SCREAMING_SNAKE_CASE =model(_a , _a ) _SCREAMING_SNAKE_CASE =scheduler.step(_a , _a , _a ).prev_sample return sample def A ( self : Tuple ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =dict(self.forward_default_kwargs ) _SCREAMING_SNAKE_CASE =kwargs.pop('num_inference_steps' , _a ) for scheduler_class in self.scheduler_classes: _SCREAMING_SNAKE_CASE =self.get_scheduler_config() _SCREAMING_SNAKE_CASE =scheduler_class(**_a ) _SCREAMING_SNAKE_CASE =self.dummy_sample _SCREAMING_SNAKE_CASE =0.1 * sample if num_inference_steps is not None and hasattr(_a , 'set_timesteps' ): scheduler.set_timesteps(_a ) elif num_inference_steps is not None and not hasattr(_a , 'set_timesteps' ): _SCREAMING_SNAKE_CASE =num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) _SCREAMING_SNAKE_CASE =[residual + 0.2, residual + 0.15, residual + 0.10] _SCREAMING_SNAKE_CASE =dummy_past_residuals[: scheduler.config.solver_order] _SCREAMING_SNAKE_CASE =scheduler.timesteps[5] _SCREAMING_SNAKE_CASE =scheduler.timesteps[6] _SCREAMING_SNAKE_CASE =scheduler.step(_a , _a , _a , **_a ).prev_sample _SCREAMING_SNAKE_CASE =scheduler.step(_a , _a , _a , **_a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def A ( self : Dict ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =DEISMultistepScheduler(**self.get_scheduler_config() ) _SCREAMING_SNAKE_CASE =self.full_loop(scheduler=_a ) _SCREAMING_SNAKE_CASE =torch.mean(torch.abs(_a ) ) assert abs(result_mean.item() - 0.2_39_16 ) < 1e-3 _SCREAMING_SNAKE_CASE =DPMSolverSinglestepScheduler.from_config(scheduler.config ) _SCREAMING_SNAKE_CASE =DPMSolverMultistepScheduler.from_config(scheduler.config ) _SCREAMING_SNAKE_CASE =UniPCMultistepScheduler.from_config(scheduler.config ) _SCREAMING_SNAKE_CASE =DEISMultistepScheduler.from_config(scheduler.config ) _SCREAMING_SNAKE_CASE =self.full_loop(scheduler=_a ) _SCREAMING_SNAKE_CASE =torch.mean(torch.abs(_a ) ) assert abs(result_mean.item() - 0.2_39_16 ) < 1e-3 def A ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=_a ) def A ( self : Optional[int] ) -> Dict: '''simple docstring''' self.check_over_configs(thresholding=_a ) for order in [1, 2, 3]: for solver_type in ["logrho"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=_a , prediction_type=_a , sample_max_value=_a , algorithm_type='deis' , solver_order=_a , solver_type=_a , ) def A ( self : int ) -> List[Any]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_a ) def A ( self : List[Any] ) -> Tuple: '''simple docstring''' for algorithm_type in ["deis"]: for solver_type in ["logrho"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=_a , solver_type=_a , prediction_type=_a , algorithm_type=_a , ) _SCREAMING_SNAKE_CASE =self.full_loop( solver_order=_a , solver_type=_a , prediction_type=_a , algorithm_type=_a , ) assert not torch.isnan(_a ).any(), "Samples have nan numbers" def A ( self : Any ) -> str: '''simple docstring''' self.check_over_configs(lower_order_final=_a ) self.check_over_configs(lower_order_final=_a ) def A ( self : List[str] ) -> List[Any]: '''simple docstring''' for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=_a , time_step=0 ) def A ( self : List[Any] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.full_loop() _SCREAMING_SNAKE_CASE =torch.mean(torch.abs(_a ) ) assert abs(result_mean.item() - 0.2_39_16 ) < 1e-3 def A ( self : Optional[Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.full_loop(prediction_type='v_prediction' ) _SCREAMING_SNAKE_CASE =torch.mean(torch.abs(_a ) ) assert abs(result_mean.item() - 0.0_91 ) < 1e-3 def A ( self : Tuple ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.scheduler_classes[0] _SCREAMING_SNAKE_CASE =self.get_scheduler_config(thresholding=_a , dynamic_thresholding_ratio=0 ) _SCREAMING_SNAKE_CASE =scheduler_class(**_a ) _SCREAMING_SNAKE_CASE =10 _SCREAMING_SNAKE_CASE =self.dummy_model() _SCREAMING_SNAKE_CASE =self.dummy_sample_deter.half() scheduler.set_timesteps(_a ) for i, t in enumerate(scheduler.timesteps ): _SCREAMING_SNAKE_CASE =model(_a , _a ) _SCREAMING_SNAKE_CASE =scheduler.step(_a , _a , _a ).prev_sample assert sample.dtype == torch.floataa
47
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if num < 0: return False snake_case_ = num snake_case_ = 0 while num > 0: snake_case_ = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
347
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available SCREAMING_SNAKE_CASE__ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = ['BartphoTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys SCREAMING_SNAKE_CASE__ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
48
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin __SCREAMING_SNAKE_CASE : Tuple = get_tests_dir('fixtures/test_sentencepiece_bpe_char.model') @require_sentencepiece @require_tokenizers class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Tuple = SpeechTaTokenizer __lowercase: int = False __lowercase: List[str] = True def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing snake_case_ = SpeechTaTokenizer(UpperCAmelCase_ ) snake_case_ = AddedToken("""<mask>""" , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) snake_case_ = mask_token tokenizer.add_special_tokens({"""mask_token""": mask_token} ) tokenizer.add_tokens(["""<ctc_blank>"""] ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = """this is a test""" snake_case_ = """this is a test""" return input_text, output_text def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Any=False , UpperCAmelCase_ : Tuple=20 , UpperCAmelCase_ : Dict=5 ) ->List[Any]: """simple docstring""" snake_case_ , snake_case_ = self.get_input_output_texts(UpperCAmelCase_ ) snake_case_ = tokenizer.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ ) snake_case_ = tokenizer.decode(UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ ) return text, ids def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" snake_case_ = """<pad>""" snake_case_ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_ ) , UpperCAmelCase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_ ) , UpperCAmelCase_ ) def lowerCAmelCase ( self : int ) ->str: """simple docstring""" snake_case_ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-4] , """œ""" ) self.assertEqual(vocab_keys[-2] , """<mask>""" ) self.assertEqual(vocab_keys[-1] , """<ctc_blank>""" ) self.assertEqual(len(UpperCAmelCase_ ) , 81 ) def lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = self.get_tokenizers(do_lower_case=UpperCAmelCase_ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case_ = tokenizer.vocab_size snake_case_ = len(UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) snake_case_ = ["""aaaaa bbbbbb""", """cccccccccdddddddd"""] snake_case_ = tokenizer.add_tokens(UpperCAmelCase_ ) snake_case_ = tokenizer.vocab_size snake_case_ = len(UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , 0 ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , len(UpperCAmelCase_ ) ) self.assertEqual(UpperCAmelCase_ , all_size + len(UpperCAmelCase_ ) ) snake_case_ = tokenizer.encode("""aaaaa bbbbbb low cccccccccdddddddd l""" , add_special_tokens=UpperCAmelCase_ ) self.assertGreaterEqual(len(UpperCAmelCase_ ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) snake_case_ = {"""eos_token""": """>>>>|||<||<<|<<""", """pad_token""": """<<<<<|||>|>>>>|>"""} snake_case_ = tokenizer.add_special_tokens(UpperCAmelCase_ ) snake_case_ = tokenizer.vocab_size snake_case_ = len(UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , 0 ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , len(UpperCAmelCase_ ) ) self.assertEqual(UpperCAmelCase_ , all_size_a + len(UpperCAmelCase_ ) ) snake_case_ = tokenizer.encode( """>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l""" , add_special_tokens=UpperCAmelCase_ ) self.assertGreaterEqual(len(UpperCAmelCase_ ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" pass def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" pass def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = self.get_tokenizer() snake_case_ = tokenizer.tokenize("""This is a test""" ) # fmt: off self.assertListEqual(UpperCAmelCase_ , [SPIECE_UNDERLINE, """T""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """a""", SPIECE_UNDERLINE, """t""", """e""", """s""", """t"""] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) snake_case_ = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( UpperCAmelCase_ , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """92000""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) snake_case_ = tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) # fmt: off self.assertListEqual(UpperCAmelCase_ , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on snake_case_ = tokenizer.convert_ids_to_tokens(UpperCAmelCase_ ) self.assertListEqual( UpperCAmelCase_ , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """<unk>""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) @slow def lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" snake_case_ = [ """Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides """ """general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural """ """Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained """ """models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.""", """BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly """ """conditioning on both left and right context in all layers.""", """The quick brown fox jumps over the lazy dog.""", ] # fmt: off snake_case_ = { """input_ids""": [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], """attention_mask""": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase_ , model_name="""microsoft/speecht5_asr""" , revision="""c5ef64c71905caeccde0e4462ef3f9077224c524""" , sequences=UpperCAmelCase_ , )
347
0
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import PoolFormerImageProcessor class _A ( unittest.TestCase ): def __init__( self : Optional[int] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Tuple=7 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3 , __SCREAMING_SNAKE_CASE : str=30 , __SCREAMING_SNAKE_CASE : Union[str, Any]=400 , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : List[Any]=0.9 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[Any]=True , __SCREAMING_SNAKE_CASE : List[str]=[0.5, 0.5, 0.5] , __SCREAMING_SNAKE_CASE : Dict=[0.5, 0.5, 0.5] , ): '''simple docstring''' __a = size if size is not None else {'''shortest_edge''': 30} __a = crop_size if crop_size is not None else {'''height''': 30, '''width''': 30} __a = parent __a = batch_size __a = num_channels __a = min_resolution __a = max_resolution __a = do_resize_and_center_crop __a = size __a = crop_pct __a = crop_size __a = do_normalize __a = image_mean __a = image_std def _lowerCamelCase ( self : Any): '''simple docstring''' return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class _A ( __UpperCAmelCase ,unittest.TestCase ): UpperCamelCase__ : Union[str, Any] = PoolFormerImageProcessor if is_vision_available() else None def _lowerCamelCase ( self : Dict): '''simple docstring''' __a = PoolFormerImageProcessingTester(self) @property def _lowerCamelCase ( self : List[Any]): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _lowerCamelCase ( self : List[Any]): '''simple docstring''' __a = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''do_resize_and_center_crop''')) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''size''')) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''crop_pct''')) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''do_normalize''')) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''image_mean''')) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''image_std''')) def _lowerCamelCase ( self : Optional[int]): '''simple docstring''' __a = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'''shortest_edge''': 30}) self.assertEqual(image_processor.crop_size , {'''height''': 30, '''width''': 30}) __a = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84) self.assertEqual(image_processor.size , {'''shortest_edge''': 42}) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84}) def _lowerCamelCase ( self : List[str]): '''simple docstring''' pass def _lowerCamelCase ( self : Any): '''simple docstring''' __a = self.image_processing_class(**self.image_processor_dict) # create random PIL images __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , Image.Image) # Test not batched input __a = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __a = image_processing(__SCREAMING_SNAKE_CASE , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def _lowerCamelCase ( self : int): '''simple docstring''' __a = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , numpify=__SCREAMING_SNAKE_CASE) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , np.ndarray) # Test not batched input __a = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __a = image_processing(__SCREAMING_SNAKE_CASE , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def _lowerCamelCase ( self : str): '''simple docstring''' __a = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , torchify=__SCREAMING_SNAKE_CASE) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , torch.Tensor) # Test not batched input __a = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __a = image_processing(__SCREAMING_SNAKE_CASE , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
49
"""simple docstring""" import datasets __SCREAMING_SNAKE_CASE : Tuple = '\\n@InProceedings{conneau2018xnli,\n author = "Conneau, Alexis\n and Rinott, Ruty\n and Lample, Guillaume\n and Williams, Adina\n and Bowman, Samuel R.\n and Schwenk, Holger\n and Stoyanov, Veselin",\n title = "XNLI: Evaluating Cross-lingual Sentence Representations",\n booktitle = "Proceedings of the 2018 Conference on Empirical Methods\n in Natural Language Processing",\n year = "2018",\n publisher = "Association for Computational Linguistics",\n location = "Brussels, Belgium",\n}\n' __SCREAMING_SNAKE_CASE : Dict = '\\nXNLI is a subset of a few thousand examples from MNLI which has been translated\ninto a 14 different languages (some low-ish resource). As with MNLI, the goal is\nto predict textual entailment (does sentence A imply/contradict/neither sentence\nB) and is a classification task (given two sentences, predict one of three\nlabels).\n' __SCREAMING_SNAKE_CASE : List[str] = '\nComputes XNLI score which is just simple accuracy.\nArgs:\n predictions: Predicted labels.\n references: Ground truth labels.\nReturns:\n \'accuracy\': accuracy\nExamples:\n\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> xnli_metric = datasets.load_metric("xnli")\n >>> results = xnli_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n' def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: return (preds == labels).mean() @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __A (datasets.Metric): '''simple docstring''' def lowerCAmelCase ( self : str ) ->Any: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), """references""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), } ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" , ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" return {"accuracy": simple_accuracy(UpperCAmelCase_ , UpperCAmelCase_ )}
347
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 SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> Tuple: lowerCamelCase__ : Optional[Any] = XCLIPTextConfig() # derive patch size from model name lowerCamelCase__ : Optional[Any] = model_name.find('patch' ) lowerCamelCase__ : Tuple = int(model_name[start_idx + len('patch' ) : start_idx + len('patch' ) + 2] ) lowerCamelCase__ : str = XCLIPVisionConfig(patch_size=_UpperCAmelCase , num_frames=_UpperCAmelCase ) if "large" in model_name: lowerCamelCase__ : int = 768 lowerCamelCase__ : Dict = 3072 lowerCamelCase__ : Optional[Any] = 12 lowerCamelCase__ : List[str] = 1024 lowerCamelCase__ : str = 4096 lowerCamelCase__ : Dict = 16 lowerCamelCase__ : int = 24 lowerCamelCase__ : List[Any] = 768 lowerCamelCase__ : int = 3072 if model_name == "xclip-large-patch14-16-frames": lowerCamelCase__ : Optional[Any] = 336 lowerCamelCase__ : List[Any] = XCLIPConfig.from_text_vision_configs(_UpperCAmelCase , _UpperCAmelCase ) if "large" in model_name: lowerCamelCase__ : List[str] = 768 return config def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> Any: # text encoder if name == "token_embedding.weight": lowerCamelCase__ : int = name.replace('token_embedding.weight' , 'text_model.embeddings.token_embedding.weight' ) if name == "positional_embedding": lowerCamelCase__ : List[Any] = name.replace('positional_embedding' , 'text_model.embeddings.position_embedding.weight' ) if "ln_1" in name: lowerCamelCase__ : Dict = name.replace('ln_1' , 'layer_norm1' ) if "ln_2" in name: lowerCamelCase__ : Any = name.replace('ln_2' , 'layer_norm2' ) if "c_fc" in name: lowerCamelCase__ : str = name.replace('c_fc' , 'fc1' ) if "c_proj" in name: lowerCamelCase__ : int = name.replace('c_proj' , 'fc2' ) if name.startswith('transformer.resblocks' ): lowerCamelCase__ : Any = name.replace('transformer.resblocks' , 'text_model.encoder.layers' ) if "attn.out_proj" in name and "message" not in name: lowerCamelCase__ : Union[str, Any] = name.replace('attn.out_proj' , 'self_attn.out_proj' ) if "ln_final" in name: lowerCamelCase__ : List[Any] = name.replace('ln_final' , 'text_model.final_layer_norm' ) # visual encoder if name == "visual.class_embedding": lowerCamelCase__ : List[str] = name.replace('visual.class_embedding' , 'vision_model.embeddings.class_embedding' ) if name == "visual.positional_embedding": lowerCamelCase__ : Tuple = name.replace('visual.positional_embedding' , 'vision_model.embeddings.position_embedding.weight' ) if name.startswith('visual.transformer.resblocks' ): lowerCamelCase__ : List[Any] = name.replace('visual.transformer.resblocks' , 'vision_model.encoder.layers' ) if "visual.conv1" in name: lowerCamelCase__ : str = name.replace('visual.conv1' , 'vision_model.embeddings.patch_embedding' ) if "visual.ln_pre" in name: lowerCamelCase__ : Tuple = name.replace('visual.ln_pre' , 'vision_model.pre_layernorm' ) if "visual.ln_post" in name: lowerCamelCase__ : List[str] = name.replace('visual.ln_post' , 'vision_model.post_layernorm' ) if "visual.proj" in name: lowerCamelCase__ : str = name.replace('visual.proj' , 'visual_projection.weight' ) if "text_projection" in name: lowerCamelCase__ : Optional[Any] = name.replace('text_projection' , 'text_projection.weight' ) # things on top if "prompts_visual_proj" in name: lowerCamelCase__ : Union[str, Any] = name.replace('prompts_visual_proj' , 'prompts_visual_projection' ) if "prompts_visual_ln" in name: lowerCamelCase__ : Any = name.replace('prompts_visual_ln' , 'prompts_visual_layernorm' ) # mit if name == "mit.positional_embedding": lowerCamelCase__ : Any = name.replace('positional' , 'position' ) if name.startswith('mit.resblocks' ): lowerCamelCase__ : Optional[Any] = name.replace('mit.resblocks' , 'mit.encoder.layers' ) # prompts generator if name.startswith('prompts_generator.norm' ): lowerCamelCase__ : Tuple = name.replace('prompts_generator.norm' , 'prompts_generator.layernorm' ) return name def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> Optional[Any]: for key in orig_state_dict.copy().keys(): lowerCamelCase__ : Tuple = orig_state_dict.pop(_UpperCAmelCase ) if "attn.in_proj" in key: lowerCamelCase__ : Union[str, Any] = key.split('.' ) if key.startswith('visual' ): lowerCamelCase__ : Optional[Any] = key_split[3] lowerCamelCase__ : Tuple = config.vision_config.hidden_size if "message_attn" in key: if "weight" in key: lowerCamelCase__ : Optional[int] = val[ :dim, : ] lowerCamelCase__ : Optional[Any] = val[ dim : dim * 2, : ] lowerCamelCase__ : int = val[ -dim:, : ] else: lowerCamelCase__ : List[Any] = val[ :dim ] lowerCamelCase__ : Optional[Any] = val[ dim : dim * 2 ] lowerCamelCase__ : Optional[int] = val[ -dim: ] else: if "weight" in key: lowerCamelCase__ : int = val[ :dim, : ] lowerCamelCase__ : Dict = val[ dim : dim * 2, : ] lowerCamelCase__ : int = val[ -dim:, : ] else: lowerCamelCase__ : Optional[int] = val[:dim] lowerCamelCase__ : str = val[ dim : dim * 2 ] lowerCamelCase__ : Optional[Any] = val[-dim:] elif key.startswith('mit' ): lowerCamelCase__ : List[str] = key_split[2] lowerCamelCase__ : int = config.vision_config.mit_hidden_size if "weight" in key: lowerCamelCase__ : List[str] = val[:dim, :] lowerCamelCase__ : str = val[dim : dim * 2, :] lowerCamelCase__ : Union[str, Any] = val[-dim:, :] else: lowerCamelCase__ : Optional[Any] = val[:dim] lowerCamelCase__ : List[str] = val[dim : dim * 2] lowerCamelCase__ : Any = val[-dim:] else: lowerCamelCase__ : Optional[int] = key_split[2] lowerCamelCase__ : Dict = config.text_config.hidden_size if "weight" in key: lowerCamelCase__ : Optional[int] = val[:dim, :] lowerCamelCase__ : int = val[ dim : dim * 2, : ] lowerCamelCase__ : Any = val[-dim:, :] else: lowerCamelCase__ : Any = val[:dim] lowerCamelCase__ : List[Any] = val[ dim : dim * 2 ] lowerCamelCase__ : str = val[-dim:] else: lowerCamelCase__ : Optional[int] = rename_key(_UpperCAmelCase ) if new_key_name in ["visual_projection.weight", "text_projection.weight"]: lowerCamelCase__ : List[Any] = val.T lowerCamelCase__ : Optional[Any] = val return orig_state_dict def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> Tuple: if num_frames == 8: lowerCamelCase__ : Any = 'eating_spaghetti_8_frames.npy' elif num_frames == 16: lowerCamelCase__ : Union[str, Any] = 'eating_spaghetti.npy' elif num_frames == 32: lowerCamelCase__ : str = 'eating_spaghetti_32_frames.npy' lowerCamelCase__ : Dict = hf_hub_download( repo_id='hf-internal-testing/spaghetti-video' , filename=_UpperCAmelCase , repo_type='dataset' , ) lowerCamelCase__ : str = np.load(_UpperCAmelCase ) return list(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=False ) -> Union[str, Any]: lowerCamelCase__ : 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', } lowerCamelCase__ : List[Any] = model_to_url[model_name] lowerCamelCase__ : Optional[Any] = 8 if "16-frames" in model_name: lowerCamelCase__ : Union[str, Any] = 16 elif "shot" in model_name: lowerCamelCase__ : Optional[int] = 32 lowerCamelCase__ : Tuple = get_xclip_config(_UpperCAmelCase , _UpperCAmelCase ) lowerCamelCase__ : List[Any] = XCLIPModel(_UpperCAmelCase ) model.eval() if "drive" in checkpoint_url: lowerCamelCase__ : Dict = 'pytorch_model.bin' gdown.cached_download(_UpperCAmelCase , _UpperCAmelCase , quiet=_UpperCAmelCase ) lowerCamelCase__ : Any = torch.load(_UpperCAmelCase , map_location='cpu' )['model'] else: lowerCamelCase__ : Tuple = torch.hub.load_state_dict_from_url(_UpperCAmelCase )['model'] lowerCamelCase__ : Any = convert_state_dict(_UpperCAmelCase , _UpperCAmelCase ) lowerCamelCase__ : List[Any] = XCLIPModel(_UpperCAmelCase ) lowerCamelCase__ , lowerCamelCase__ : List[Any] = model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase ) assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"] model.eval() lowerCamelCase__ : Any = 336 if model_name == 'xclip-large-patch14-16-frames' else 224 lowerCamelCase__ : List[str] = VideoMAEImageProcessor(size=_UpperCAmelCase ) lowerCamelCase__ : str = CLIPTokenizer.from_pretrained('openai/clip-vit-base-patch32' ) lowerCamelCase__ : List[Any] = CLIPTokenizerFast.from_pretrained('openai/clip-vit-base-patch32' ) lowerCamelCase__ : Optional[int] = XCLIPProcessor(image_processor=_UpperCAmelCase , tokenizer=_UpperCAmelCase ) lowerCamelCase__ : int = prepare_video(_UpperCAmelCase ) lowerCamelCase__ : Tuple = processor( text=['playing sports', 'eating spaghetti', 'go shopping'] , videos=_UpperCAmelCase , return_tensors='pt' , padding=_UpperCAmelCase ) print('Shape of pixel values:' , inputs.pixel_values.shape ) with torch.no_grad(): lowerCamelCase__ : List[Any] = model(**_UpperCAmelCase ) # Verify outputs lowerCamelCase__ : str = outputs.logits_per_video lowerCamelCase__ : Union[str, Any] = logits_per_video.softmax(dim=1 ) print('Probs:' , _UpperCAmelCase ) # kinetics-400 if model_name == "xclip-base-patch32": lowerCamelCase__ : Optional[Any] = torch.tensor([[0.0_019, 0.9_951, 0.0_030]] ) elif model_name == "xclip-base-patch32-16-frames": lowerCamelCase__ : Union[str, Any] = torch.tensor([[7.0_999e-04, 9.9_883e-01, 4.5_580e-04]] ) elif model_name == "xclip-base-patch16": lowerCamelCase__ : int = torch.tensor([[0.0_083, 0.9_681, 0.0_236]] ) elif model_name == "xclip-base-patch16-16-frames": lowerCamelCase__ : Any = torch.tensor([[7.6_937e-04, 9.9_728e-01, 1.9_473e-03]] ) elif model_name == "xclip-large-patch14": lowerCamelCase__ : Tuple = torch.tensor([[0.0_062, 0.9_864, 0.0_075]] ) elif model_name == "xclip-large-patch14-16-frames": lowerCamelCase__ : Optional[int] = torch.tensor([[3.3_877e-04, 9.9_937e-01, 2.8_888e-04]] ) # kinetics-600 elif model_name == "xclip-base-patch16-kinetics-600": lowerCamelCase__ : Tuple = torch.tensor([[0.0_555, 0.8_914, 0.0_531]] ) elif model_name == "xclip-base-patch16-kinetics-600-16-frames": lowerCamelCase__ : Tuple = torch.tensor([[3.8_554e-04, 9.9_929e-01, 3.2_754e-04]] ) elif model_name == "xclip-large-patch14-kinetics-600": lowerCamelCase__ : List[Any] = torch.tensor([[0.0_036, 0.9_920, 0.0_045]] ) # few shot elif model_name == "xclip-base-patch16-hmdb-2-shot": lowerCamelCase__ : Tuple = torch.tensor([[7.1_890e-06, 9.9_994e-01, 5.6_559e-05]] ) elif model_name == "xclip-base-patch16-hmdb-4-shot": lowerCamelCase__ : Any = torch.tensor([[1.0_320e-05, 9.9_993e-01, 6.2_435e-05]] ) elif model_name == "xclip-base-patch16-hmdb-8-shot": lowerCamelCase__ : Optional[Any] = torch.tensor([[4.1_377e-06, 9.9_990e-01, 9.8_386e-05]] ) elif model_name == "xclip-base-patch16-hmdb-16-shot": lowerCamelCase__ : Optional[int] = torch.tensor([[4.1_347e-05, 9.9_962e-01, 3.3_411e-04]] ) elif model_name == "xclip-base-patch16-ucf-2-shot": lowerCamelCase__ : int = torch.tensor([[8.5_857e-05, 9.9_928e-01, 6.3_291e-04]] ) elif model_name == "xclip-base-patch16-ucf-4-shot": lowerCamelCase__ : Dict = torch.tensor([[8.5_857e-05, 9.9_928e-01, 6.3_291e-04]] ) elif model_name == "xclip-base-patch16-ucf-8-shot": lowerCamelCase__ : List[Any] = torch.tensor([[0.0_027, 0.9_904, 0.0_070]] ) elif model_name == "xclip-base-patch16-ucf-16-shot": lowerCamelCase__ : Union[str, Any] = torch.tensor([[9.8_219e-04, 9.9_593e-01, 3.0_863e-03]] ) # zero shot elif model_name == "xclip-base-patch16-zero-shot": lowerCamelCase__ : int = torch.tensor([[3.5_082e-04, 9.9_785e-01, 1.7_966e-03]] ) else: raise ValueError(F"""Model name {model_name} not supported""" ) assert torch.allclose(_UpperCAmelCase , _UpperCAmelCase , 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(_UpperCAmelCase ) if push_to_hub: print('Pushing model, processor and slow tokenizer files to the hub...' ) model.push_to_hub(_UpperCAmelCase , organization='nielsr' ) processor.push_to_hub(_UpperCAmelCase , organization='nielsr' ) slow_tokenizer.push_to_hub(_UpperCAmelCase , organization='nielsr' ) if __name__ == "__main__": _UpperCAmelCase : List[str] = 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.""" ) _UpperCAmelCase : List[str] = parser.parse_args() convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
50
"""simple docstring""" from ..utils import DummyObject, requires_backends class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : List[str] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""sentencepiece"""] def __init__( self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Tuple ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : Any , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : List[Any] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Dict = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[str] = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : int ) ->List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Tuple , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Dict ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Union[str, Any] ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[Any] = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : Optional[Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""sentencepiece"""] def __init__( self : Optional[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : str , **UpperCAmelCase_ : int ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Optional[int] , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Tuple = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : List[Any] ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : List[str] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Tuple = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Optional[Any] ) ->str: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Optional[Any] ) ->int: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = ["""sentencepiece"""] def __init__( self : Optional[Any] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : Optional[Any] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Dict ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : List[str] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any] ) ->List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : Any , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Optional[Any] ) ->List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Dict = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Union[str, Any] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Optional[int] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = ["""sentencepiece"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : str ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""sentencepiece"""] def __init__( self : Tuple , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Optional[int] ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Dict = ["""sentencepiece"""] def __init__( self : Optional[int] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : List[str] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Optional[int] ) ->Any: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[str] = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Union[str, Any] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Optional[int] ) ->str: """simple docstring""" requires_backends(self , ["""sentencepiece"""] )
347
0
from collections.abc import Iterable from typing import Any class __snake_case : def __init__( self : Tuple , _snake_case : int | None = None): """simple docstring""" UpperCAmelCase_ = value UpperCAmelCase_ = None # Added in order to delete a node easier UpperCAmelCase_ = None UpperCAmelCase_ = None def __repr__( self : Dict): """simple docstring""" from pprint import pformat if self.left is None and self.right is None: return str(self.value) return pformat({F"""{self.value}""": (self.left, self.right)} , indent=1) class __snake_case : def __init__( self : int , _snake_case : Node | None = None): """simple docstring""" UpperCAmelCase_ = root def __str__( self : List[str]): """simple docstring""" return str(self.root) def lowerCamelCase ( self : Any , _snake_case : Node , _snake_case : Node | None): """simple docstring""" if new_children is not None: # reset its kids UpperCAmelCase_ = node.parent if node.parent is not None: # reset its parent if self.is_right(_snake_case): # If it is the right children UpperCAmelCase_ = new_children else: UpperCAmelCase_ = new_children else: UpperCAmelCase_ = new_children def lowerCamelCase ( self : int , _snake_case : Node): """simple docstring""" if node.parent and node.parent.right: return node == node.parent.right return False def lowerCamelCase ( self : Optional[Any]): """simple docstring""" return self.root is None def lowerCamelCase ( self : Any , _snake_case : str): """simple docstring""" UpperCAmelCase_ = Node(_snake_case) # create a new Node if self.empty(): # if Tree is empty UpperCAmelCase_ = new_node # set its root else: # Tree is not empty UpperCAmelCase_ = self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: UpperCAmelCase_ = new_node # We insert the new node in a leaf break else: UpperCAmelCase_ = parent_node.left else: if parent_node.right is None: UpperCAmelCase_ = new_node break else: UpperCAmelCase_ = parent_node.right UpperCAmelCase_ = parent_node def lowerCamelCase ( self : Any , *_snake_case : Union[str, Any]): """simple docstring""" for value in values: self.__insert(_snake_case) def lowerCamelCase ( self : Any , _snake_case : List[str]): """simple docstring""" if self.empty(): raise IndexError('''Warning: Tree is empty! please use another.''') else: UpperCAmelCase_ = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: UpperCAmelCase_ = node.left if value < node.value else node.right return node def lowerCamelCase ( self : List[Any] , _snake_case : Node | None = None): """simple docstring""" if node is None: if self.root is None: return None UpperCAmelCase_ = self.root if not self.empty(): while node.right is not None: UpperCAmelCase_ = node.right return node def lowerCamelCase ( self : Any , _snake_case : Node | None = None): """simple docstring""" if node is None: UpperCAmelCase_ = self.root if self.root is None: return None if not self.empty(): UpperCAmelCase_ = self.root while node.left is not None: UpperCAmelCase_ = node.left return node def lowerCamelCase ( self : Dict , _snake_case : int): """simple docstring""" UpperCAmelCase_ = self.search(_snake_case) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(_snake_case , _snake_case) elif node.left is None: # Has only right children self.__reassign_nodes(_snake_case , node.right) elif node.right is None: # Has only left children self.__reassign_nodes(_snake_case , node.left) else: UpperCAmelCase_ = self.get_max( node.left) # Gets the max value of the left branch self.remove(tmp_node.value) # type: ignore UpperCAmelCase_ = ( tmp_node.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def lowerCamelCase ( self : Tuple , _snake_case : Node | None): """simple docstring""" if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left) yield from self.preorder_traverse(node.right) def lowerCamelCase ( self : Optional[int] , _snake_case : str=None): """simple docstring""" if traversal_function is None: return self.preorder_traverse(self.root) else: return traversal_function(self.root) def lowerCamelCase ( self : Union[str, Any] , _snake_case : list , _snake_case : Node | None): """simple docstring""" if node: self.inorder(_snake_case , node.left) arr.append(node.value) self.inorder(_snake_case , node.right) def lowerCamelCase ( self : Union[str, Any] , _snake_case : int , _snake_case : Node): """simple docstring""" UpperCAmelCase_ = [] self.inorder(_snake_case , _snake_case) # append all values to list using inorder traversal return arr[k - 1] def A (__A : Node | None ) -> list[Node]: """simple docstring""" UpperCAmelCase_ = [] if curr_node is not None: UpperCAmelCase_ = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node] return node_list def A () -> None: """simple docstring""" UpperCAmelCase_ = (8, 3, 6, 1, 10, 14, 13, 4, 7) UpperCAmelCase_ = BinarySearchTree() for i in testlist: t.insert(__A ) # Prints all the elements of the list in order traversal print(__A ) if t.search(6 ) is not None: print('''The value 6 exists''' ) else: print('''The value 6 doesn\'t exist''' ) if t.search(-1 ) is not None: print('''The value -1 exists''' ) else: print('''The value -1 doesn\'t exist''' ) if not t.empty(): print('''Max Value: ''' , t.get_max().value ) # type: ignore print('''Min Value: ''' , t.get_min().value ) # type: ignore for i in testlist: t.remove(__A ) print(__A ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
51
"""simple docstring""" import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor __SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) class __A (snake_case__): '''simple docstring''' def __init__( self : str , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int ) ->None: """simple docstring""" warnings.warn( """The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use MobileViTImageProcessor instead.""" , UpperCAmelCase_ , ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ )
347
0
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss __lowerCamelCase : Union[str, Any] = pytest.mark.integration @require_faiss class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = Dataset.from_dict({"filename": ["my_name-train" + "_" + str(A_ ) for x in np.arange(30 ).tolist()]} ) return dset def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dataset = self._create_dummy_dataset() UpperCamelCase : List[Any] = dset.map( lambda A_ , A_ : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=A_ , keep_in_memory=A_ ) UpperCamelCase : List[str] = dset.add_faiss_index("vecs" , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) UpperCamelCase , UpperCamelCase : Tuple = dset.get_nearest_examples("vecs" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) dset.drop_index("vecs" ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) UpperCamelCase , UpperCamelCase : int = dset.get_nearest_examples("vecs" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=A_ ) as tmp_file: dset.save_faiss_index("vecs" , tmp_file.name ) dset.load_faiss_index("vecs2" , tmp_file.name ) os.unlink(tmp_file.name ) UpperCamelCase , UpperCamelCase : List[str] = dset.get_nearest_examples("vecs2" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" ) dset.drop_index("vecs" ) self.assertRaises(A_ , partial(dset.get_nearest_examples , "vecs2" , np.ones(5 , dtype=np.floataa ) ) ) def __UpperCamelCase( self ): '''simple docstring''' from elasticsearch import Elasticsearch UpperCamelCase : Dataset = self._create_dummy_dataset() with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: UpperCamelCase : List[str] = {"acknowledged": True} mocked_bulk.return_value([(True, None)] * 30 ) UpperCamelCase : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 29}]}} UpperCamelCase : Optional[Any] = Elasticsearch() dset.add_elasticsearch_index("filename" , es_client=A_ ) UpperCamelCase , UpperCamelCase : List[str] = dset.get_nearest_examples("filename" , "my_name-train_29" ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) @require_faiss class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Optional[int] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query UpperCamelCase : Any = np.zeros(5 , dtype=np.floataa ) UpperCamelCase : Optional[Any] = 1 UpperCamelCase , UpperCamelCase : Optional[Any] = index.search(A_ ) self.assertRaises(A_ , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries UpperCamelCase : Optional[int] = np.eye(5 , dtype=np.floataa )[::-1] UpperCamelCase , UpperCamelCase : Tuple = index.search_batch(A_ ) self.assertRaises(A_ , index.search_batch , queries[0] ) UpperCamelCase : Optional[int] = [scores[0] for scores in total_scores] UpperCamelCase : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(A_ ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , A_ ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : List[str] = FaissIndex(string_factory="Flat" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) UpperCamelCase : List[str] = FaissIndex(string_factory="LSH" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(A_ ): UpperCamelCase : List[str] = FaissIndex(string_factory="Flat" , custom_index=faiss.IndexFlat(5 ) ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dict = faiss.IndexFlat(5 ) UpperCamelCase : Union[str, Any] = FaissIndex(custom_index=A_ ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : str = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=A_ ) as tmp_file: index.save(tmp_file.name ) UpperCamelCase : int = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) UpperCamelCase : str = np.zeros(5 , dtype=np.floataa ) UpperCamelCase : int = 1 UpperCamelCase , UpperCamelCase : Dict = index.search(A_ ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def A_ ( _lowerCAmelCase ) -> Optional[int]: import faiss UpperCamelCase : Union[str, Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) UpperCamelCase : List[Any] = "index.faiss" UpperCamelCase : List[str] = F"""mock://{index_name}""" index.save(_lowerCAmelCase , storage_options=mockfs.storage_options ) UpperCamelCase : List[str] = FaissIndex.load(_lowerCAmelCase , storage_options=mockfs.storage_options ) UpperCamelCase : List[str] = np.zeros(5 , dtype=np.floataa ) UpperCamelCase : Optional[int] = 1 UpperCamelCase , UpperCamelCase : List[str] = index.search(_lowerCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' from elasticsearch import Elasticsearch with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: UpperCamelCase : List[str] = Elasticsearch() UpperCamelCase : Union[str, Any] = {"acknowledged": True} UpperCamelCase : Union[str, Any] = ElasticSearchIndex(es_client=A_ ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(["foo", "bar", "foobar"] ) # single query UpperCamelCase : str = "foo" UpperCamelCase : Dict = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} UpperCamelCase , UpperCamelCase : Tuple = index.search(A_ ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout UpperCamelCase : Dict = "foo" UpperCamelCase : Optional[Any] = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} UpperCamelCase , UpperCamelCase : str = index.search(A_ , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries UpperCamelCase : Dict = ["foo", "bar", "foobar"] UpperCamelCase : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} UpperCamelCase , UpperCamelCase : Optional[int] = index.search_batch(A_ ) UpperCamelCase : str = [scores[0] for scores in total_scores] UpperCamelCase : Optional[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(A_ ) , 0 ) self.assertListEqual([1, 1, 1] , A_ ) # batched queries with timeout UpperCamelCase : int = ["foo", "bar", "foobar"] UpperCamelCase : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} UpperCamelCase , UpperCamelCase : Union[str, Any] = index.search_batch(A_ , request_timeout=30 ) UpperCamelCase : Union[str, Any] = [scores[0] for scores in total_scores] UpperCamelCase : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(A_ ) , 0 ) self.assertListEqual([1, 1, 1] , A_ )
52
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Any: snake_case_ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"""blocks.{i}.norm1.weight""", f"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """vit.embeddings.cls_token"""), ("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" snake_case_ = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) return rename_keys def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Tuple: for i in range(config.num_hidden_layers ): if base_model: snake_case_ = """""" else: snake_case_ = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case_ = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" ) snake_case_ = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict snake_case_ = in_proj_weight[ : config.hidden_size, : ] snake_case_ = in_proj_bias[: config.hidden_size] snake_case_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case_ = in_proj_weight[ -config.hidden_size :, : ] snake_case_ = in_proj_bias[-config.hidden_size :] def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: snake_case_ = dct.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = val def _a ( ) -> Any: snake_case_ = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = ViTConfig() snake_case_ = False # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size if vit_name[-5:] == "in21k": snake_case_ = True snake_case_ = int(vit_name[-12:-10] ) snake_case_ = int(vit_name[-9:-6] ) else: snake_case_ = 1_000 snake_case_ = """huggingface/label-files""" snake_case_ = """imagenet-1k-id2label.json""" snake_case_ = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) snake_case_ = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} snake_case_ = idalabel snake_case_ = {v: k for k, v in idalabel.items()} snake_case_ = int(vit_name[-6:-4] ) snake_case_ = int(vit_name[-3:] ) # size of the architecture if "deit" in vit_name: if vit_name[9:].startswith("""tiny""" ): snake_case_ = 192 snake_case_ = 768 snake_case_ = 12 snake_case_ = 3 elif vit_name[9:].startswith("""small""" ): snake_case_ = 384 snake_case_ = 1_536 snake_case_ = 12 snake_case_ = 6 else: pass else: if vit_name[4:].startswith("""small""" ): snake_case_ = 768 snake_case_ = 2_304 snake_case_ = 8 snake_case_ = 8 elif vit_name[4:].startswith("""base""" ): pass elif vit_name[4:].startswith("""large""" ): snake_case_ = 1_024 snake_case_ = 4_096 snake_case_ = 24 snake_case_ = 16 elif vit_name[4:].startswith("""huge""" ): snake_case_ = 1_280 snake_case_ = 5_120 snake_case_ = 32 snake_case_ = 16 # load original model from timm snake_case_ = timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ) timm_model.eval() # load state_dict of original model, remove and rename some keys snake_case_ = timm_model.state_dict() if base_model: remove_classification_head_(_SCREAMING_SNAKE_CASE ) snake_case_ = create_rename_keys(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for src, dest in rename_keys: rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) read_in_q_k_v(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load HuggingFace model if vit_name[-5:] == "in21k": snake_case_ = ViTModel(_SCREAMING_SNAKE_CASE ).eval() else: snake_case_ = ViTForImageClassification(_SCREAMING_SNAKE_CASE ).eval() model.load_state_dict(_SCREAMING_SNAKE_CASE ) # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor if "deit" in vit_name: snake_case_ = DeiTImageProcessor(size=config.image_size ) else: snake_case_ = ViTImageProcessor(size=config.image_size ) snake_case_ = image_processor(images=prepare_img() , return_tensors="""pt""" ) snake_case_ = encoding["""pixel_values"""] snake_case_ = model(_SCREAMING_SNAKE_CASE ) if base_model: snake_case_ = timm_model.forward_features(_SCREAMING_SNAKE_CASE ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(_SCREAMING_SNAKE_CASE , outputs.pooler_output , atol=1E-3 ) else: snake_case_ = timm_model(_SCREAMING_SNAKE_CASE ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_SCREAMING_SNAKE_CASE , outputs.logits , atol=1E-3 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(f"""Saving model {vit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--vit_name', default='vit_base_patch16_224', type=str, help='Name of the ViT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) __SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
347
0
'''simple docstring''' import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap a__ : Union[str, Any] ='''Usage of script: script_name <size_of_canvas:int>''' a__ : Tuple =[0] * 100 + [1] * 10 random.shuffle(choice) def lowercase__ ( __lowercase : int ) -> list[list[bool]]: """simple docstring""" __UpperCamelCase = [[False for i in range(__lowercase )] for j in range(__lowercase )] return canvas def lowercase__ ( __lowercase : list[list[bool]] ) -> None: """simple docstring""" for i, row in enumerate(__lowercase ): for j, _ in enumerate(__lowercase ): __UpperCamelCase = bool(random.getrandbits(1 ) ) def lowercase__ ( __lowercase : list[list[bool]] ) -> list[list[bool]]: """simple docstring""" __UpperCamelCase = np.array(__lowercase ) __UpperCamelCase = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(__lowercase ): for c, pt in enumerate(__lowercase ): __UpperCamelCase = __judge_point( __lowercase , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) __UpperCamelCase = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. __UpperCamelCase = current_canvas.tolist() return return_canvas def lowercase__ ( __lowercase : bool , __lowercase : list[list[bool]] ) -> bool: """simple docstring""" __UpperCamelCase = 0 __UpperCamelCase = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. __UpperCamelCase = pt if pt: if alive < 2: __UpperCamelCase = False elif alive == 2 or alive == 3: __UpperCamelCase = True elif alive > 3: __UpperCamelCase = False else: if alive == 3: __UpperCamelCase = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) a__ : Union[str, Any] =int(sys.argv[1]) # main working structure of this module. a__ : Any =create_canvas(canvas_size) seed(c) a__ , a__ : Union[str, Any] =plt.subplots() fig.show() a__ : Tuple =ListedColormap(['''w''', '''k''']) try: while True: a__ : int =run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
53
"""simple docstring""" import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __A (unittest.TestCase): '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple=13 , UpperCAmelCase_ : List[Any]=7 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Dict=99 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : Tuple=5 , UpperCAmelCase_ : Union[str, Any]=4 , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : int="gelu" , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : Dict=512 , UpperCAmelCase_ : Optional[Any]=16 , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : str=0.02 , UpperCAmelCase_ : str=4 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_attention_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_choices def lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_attention_mask: snake_case_ = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = 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 , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Union[str, Any] = True __lowercase: int = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" snake_case_ = FlaxRoFormerModelTester(self ) @slow def lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=UpperCAmelCase_ ) snake_case_ = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCAmelCase_ ) @require_flax class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" snake_case_ = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) snake_case_ = jnp.array([[0, 1, 2, 3, 4, 5]] ) snake_case_ = model(UpperCAmelCase_ )[0] snake_case_ = 50_000 snake_case_ = (1, 6, vocab_size) self.assertEqual(output.shape , UpperCAmelCase_ ) snake_case_ = jnp.array( [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) )
347
0
"""simple docstring""" import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : List[str] ) -> Optional[Any]: debug_launcher(test_script.main ) def UpperCAmelCase_ ( self : List[Any] ) -> Any: debug_launcher(test_ops.main )
54
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> bool: snake_case_ = get_failure_array(_SCREAMING_SNAKE_CASE ) # 2) Step through text searching for pattern snake_case_ , snake_case_ = 0, 0 # index into text, pattern while i < len(_SCREAMING_SNAKE_CASE ): if pattern[j] == text[i]: if j == (len(_SCREAMING_SNAKE_CASE ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: snake_case_ = failure[j - 1] continue i += 1 return False def _a ( _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = [0] snake_case_ = 0 snake_case_ = 1 while j < len(_SCREAMING_SNAKE_CASE ): if pattern[i] == pattern[j]: i += 1 elif i > 0: snake_case_ = failure[i - 1] continue j += 1 failure.append(_SCREAMING_SNAKE_CASE ) return failure if __name__ == "__main__": # Test 1) __SCREAMING_SNAKE_CASE : Optional[int] = 'abc1abc12' __SCREAMING_SNAKE_CASE : Optional[int] = 'alskfjaldsabc1abc1abc12k23adsfabcabc' __SCREAMING_SNAKE_CASE : List[str] = 'alskfjaldsk23adsfabcabc' assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) __SCREAMING_SNAKE_CASE : int = 'ABABX' __SCREAMING_SNAKE_CASE : Optional[Any] = 'ABABZABABYABABX' assert kmp(pattern, text) # Test 3) __SCREAMING_SNAKE_CASE : Any = 'AAAB' __SCREAMING_SNAKE_CASE : List[Any] = 'ABAAAAAB' assert kmp(pattern, text) # Test 4) __SCREAMING_SNAKE_CASE : Optional[int] = 'abcdabcy' __SCREAMING_SNAKE_CASE : str = 'abcxabcdabxabcdabcdabcy' assert kmp(pattern, text) # Test 5) __SCREAMING_SNAKE_CASE : Any = 'aabaabaaa' assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
347
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() a_ : Tuple = logging.get_logger(__name__) def __snake_case ( UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str]=False ): lowerCamelCase_ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''blocks.{i}.norm1.weight''', F'''vit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''blocks.{i}.norm1.bias''', F'''vit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((F'''blocks.{i}.attn.proj.weight''', F'''vit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.attn.proj.bias''', F'''vit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((F'''blocks.{i}.norm2.weight''', F'''vit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''blocks.{i}.norm2.bias''', F'''vit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.weight''', F'''vit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.bias''', F'''vit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.weight''', F'''vit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.bias''', F'''vit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ ("cls_token", "vit.embeddings.cls_token"), ("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight"), ("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias"), ("pos_embed", "vit.embeddings.position_embeddings"), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" lowerCamelCase_ = [(pair[0], pair[1][4:]) if pair[1].startswith("vit" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("norm.weight", "vit.layernorm.weight"), ("norm.bias", "vit.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) return rename_keys def __snake_case ( UpperCAmelCase_ : str , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int]=False ): for i in range(config.num_hidden_layers ): if base_model: lowerCamelCase_ = "" else: lowerCamelCase_ = "vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowerCamelCase_ = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' ) lowerCamelCase_ = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict lowerCamelCase_ = in_proj_weight[ : config.hidden_size, : ] lowerCamelCase_ = in_proj_bias[: config.hidden_size] lowerCamelCase_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowerCamelCase_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowerCamelCase_ = in_proj_weight[ -config.hidden_size :, : ] lowerCamelCase_ = in_proj_bias[-config.hidden_size :] def __snake_case ( UpperCAmelCase_ : List[Any] ): lowerCamelCase_ = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(UpperCAmelCase_ , UpperCAmelCase_ ) def __snake_case ( UpperCAmelCase_ : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] ): lowerCamelCase_ = dct.pop(UpperCAmelCase_ ) lowerCamelCase_ = val def __snake_case ( ): lowerCamelCase_ = "http://images.cocodataset.org/val2017/000000039769.jpg" lowerCamelCase_ = Image.open(requests.get(UpperCAmelCase_ , stream=UpperCAmelCase_ ).raw ) return im @torch.no_grad() def __snake_case ( UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str]=True ): lowerCamelCase_ = ViTConfig() # patch_size if model_name[-1] == "8": lowerCamelCase_ = 8 # set labels if required if not base_model: lowerCamelCase_ = 1000 lowerCamelCase_ = "huggingface/label-files" lowerCamelCase_ = "imagenet-1k-id2label.json" lowerCamelCase_ = json.load(open(hf_hub_download(UpperCAmelCase_ , UpperCAmelCase_ , repo_type="dataset" ) , "r" ) ) lowerCamelCase_ = {int(UpperCAmelCase_ ): v for k, v in idalabel.items()} lowerCamelCase_ = idalabel lowerCamelCase_ = {v: k for k, v in idalabel.items()} # size of the architecture if model_name in ["dino_vits8", "dino_vits16"]: lowerCamelCase_ = 384 lowerCamelCase_ = 1536 lowerCamelCase_ = 12 lowerCamelCase_ = 6 # load original model from torch hub lowerCamelCase_ = torch.hub.load("facebookresearch/dino:main" , UpperCAmelCase_ ) original_model.eval() # load state_dict of original model, remove and rename some keys lowerCamelCase_ = original_model.state_dict() if base_model: remove_classification_head_(UpperCAmelCase_ ) lowerCamelCase_ = create_rename_keys(UpperCAmelCase_ , base_model=UpperCAmelCase_ ) for src, dest in rename_keys: rename_key(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) read_in_q_k_v(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # load HuggingFace model if base_model: lowerCamelCase_ = ViTModel(UpperCAmelCase_ , add_pooling_layer=UpperCAmelCase_ ).eval() else: lowerCamelCase_ = ViTForImageClassification(UpperCAmelCase_ ).eval() model.load_state_dict(UpperCAmelCase_ ) # Check outputs on an image, prepared by ViTImageProcessor lowerCamelCase_ = ViTImageProcessor() lowerCamelCase_ = image_processor(images=prepare_img() , return_tensors="pt" ) lowerCamelCase_ = encoding["pixel_values"] lowerCamelCase_ = model(UpperCAmelCase_ ) if base_model: lowerCamelCase_ = original_model(UpperCAmelCase_ ) assert torch.allclose(UpperCAmelCase_ , outputs.last_hidden_state[:, 0, :] , atol=1E-1 ) else: lowerCamelCase_ = original_model(UpperCAmelCase_ ) assert logits.shape == outputs.logits.shape assert torch.allclose(UpperCAmelCase_ , outputs.logits , atol=1E-3 ) Path(UpperCAmelCase_ ).mkdir(exist_ok=UpperCAmelCase_ ) print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCAmelCase_ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCAmelCase_ ) if __name__ == "__main__": a_ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""dino_vitb16""", type=str, help="""Name of the model trained with DINO you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--base_model""", action="""store_true""", help="""Whether to only convert the base model (no projection head weights).""", ) parser.set_defaults(base_model=True) a_ : Optional[Any] = parser.parse_args() convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)
55
"""simple docstring""" from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class __A (snake_case__): '''simple docstring''' @slow @require_torch def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = EncoderDecoderModel.from_encoder_decoder_pretrained("""prajjwal1/bert-tiny""" , """prajjwal1/bert-tiny""" ) snake_case_ = BertTokenizer.from_pretrained("""bert-base-uncased""" ) snake_case_ = bertabert.config.encoder.vocab_size snake_case_ = tokenizer.sep_token_id snake_case_ = tokenizer.cls_token_id snake_case_ = 128 snake_case_ = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""train[:1%]""" ) snake_case_ = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""validation[:1%]""" ) snake_case_ = train_dataset.select(range(32 ) ) snake_case_ = val_dataset.select(range(16 ) ) snake_case_ = 4 def _map_to_encoder_decoder_inputs(UpperCAmelCase_ : int ): # Tokenizer will automatically set [BOS] <text> [EOS] snake_case_ = tokenizer(batch["""article"""] , padding="""max_length""" , truncation=UpperCAmelCase_ , max_length=512 ) snake_case_ = tokenizer(batch["""highlights"""] , padding="""max_length""" , truncation=UpperCAmelCase_ , max_length=128 ) snake_case_ = inputs.input_ids snake_case_ = inputs.attention_mask snake_case_ = outputs.input_ids snake_case_ = outputs.input_ids.copy() snake_case_ = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["""labels"""] ] snake_case_ = outputs.attention_mask assert all(len(UpperCAmelCase_ ) == 512 for x in inputs.input_ids ) assert all(len(UpperCAmelCase_ ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(UpperCAmelCase_ : Union[str, Any] ): snake_case_ = pred.label_ids snake_case_ = pred.predictions # all unnecessary tokens are removed snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = sum([int(pred_str[i] == label_str[i] ) for i in range(len(UpperCAmelCase_ ) )] ) / len(UpperCAmelCase_ ) return {"accuracy": accuracy} # map train dataset snake_case_ = train_dataset.map( _map_to_encoder_decoder_inputs , batched=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , remove_columns=["""article""", """highlights"""] , ) train_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) # same for validation dataset snake_case_ = val_dataset.map( _map_to_encoder_decoder_inputs , batched=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , remove_columns=["""article""", """highlights"""] , ) val_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) snake_case_ = self.get_auto_remove_tmp_dir() snake_case_ = SeqaSeqTrainingArguments( output_dir=UpperCAmelCase_ , per_device_train_batch_size=UpperCAmelCase_ , per_device_eval_batch_size=UpperCAmelCase_ , predict_with_generate=UpperCAmelCase_ , evaluation_strategy="""steps""" , do_train=UpperCAmelCase_ , do_eval=UpperCAmelCase_ , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer snake_case_ = SeqaSeqTrainer( model=UpperCAmelCase_ , args=UpperCAmelCase_ , compute_metrics=_compute_metrics , train_dataset=UpperCAmelCase_ , eval_dataset=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ , ) # start training trainer.train()
347
0
'''simple docstring''' import warnings warnings.warn( 'memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: ' '`from accelerate import find_executable_batch_size` to avoid this warning.', FutureWarning, )
56
"""simple docstring""" # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys __SCREAMING_SNAKE_CASE : Tuple = subprocess.check_output('git merge-base main HEAD'.split()).decode('utf-8') __SCREAMING_SNAKE_CASE : Tuple = subprocess.check_output(f"""git diff --name-only {fork_point_sha}""".split()).decode('utf-8').split() __SCREAMING_SNAKE_CASE : Any = '|'.join(sys.argv[1:]) __SCREAMING_SNAKE_CASE : Optional[Any] = re.compile(Rf"""^({joined_dirs}).*?\.py$""") __SCREAMING_SNAKE_CASE : List[str] = [x for x in modified_files if regex.match(x)] print(' '.join(relevant_modified_files), end='')
347
0
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [0] * len(_UpperCamelCase ) for i in range(1 , len(_UpperCamelCase ) ): # use last results for better performance - dynamic programming __lowerCAmelCase = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: __lowerCAmelCase = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 __lowerCAmelCase = j return prefix_result def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return max(prefix_function(_UpperCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod()
57
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } __SCREAMING_SNAKE_CASE : List[Any] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = {} with open(_SCREAMING_SNAKE_CASE , """r""" ) as file: for line_number, line in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = line.strip() if line: snake_case_ = line.split() snake_case_ = line_number snake_case_ = words[0] snake_case_ = value return result def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: for attribute in key.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(_SCREAMING_SNAKE_CASE ): snake_case_ = PARAM_MAPPING[full_name.split(""".""" )[-1]] snake_case_ = """param""" if weight_type is not None and weight_type != "param": snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape elif weight_type is not None and weight_type == "param": snake_case_ = hf_pointer for attribute in hf_param_name.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = shape_pointer.shape # let's reduce dimension snake_case_ = value[0] else: snake_case_ = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": snake_case_ = value elif weight_type == "weight_g": snake_case_ = value elif weight_type == "weight_v": snake_case_ = value elif weight_type == "bias": snake_case_ = value elif weight_type == "param": for attribute in hf_param_name.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = value else: snake_case_ = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(_SCREAMING_SNAKE_CASE ): snake_case_ = PARAM_MAPPING[full_name.split(""".""" )[-1]] snake_case_ = """param""" if weight_type is not None and weight_type != "param": snake_case_ = """.""".join([key, weight_type] ) elif weight_type is not None and weight_type == "param": snake_case_ = """.""".join([key, hf_param_name] ) else: snake_case_ = key snake_case_ = value if """lm_head""" in full_key else value[0] __SCREAMING_SNAKE_CASE : int = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> List[str]: snake_case_ = False for key, mapped_key in MAPPING.items(): snake_case_ = """wav2vec2.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: snake_case_ = True if "*" in mapped_key: snake_case_ = name.split(_SCREAMING_SNAKE_CASE )[0].split(""".""" )[-2] snake_case_ = mapped_key.replace("""*""" , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: snake_case_ = """weight_g""" elif "weight_v" in name: snake_case_ = """weight_v""" elif "bias" in name: snake_case_ = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj snake_case_ = """weight""" else: snake_case_ = None if hf_dict is not None: rename_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return is_used return is_used def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = [] snake_case_ = fairseq_model.state_dict() snake_case_ = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): snake_case_ = False if "conv_layers" in name: load_conv_layer( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == """group""" , ) snake_case_ = True else: snake_case_ = load_wavaveca_layer(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(f"""Unused weights: {unused_weights}""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = full_name.split("""conv_layers.""" )[-1] snake_case_ = name.split(""".""" ) snake_case_ = int(items[0] ) snake_case_ = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_SCREAMING_SNAKE_CASE ) @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False ) -> int: if config_path is not None: snake_case_ = WavaVecaConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) else: snake_case_ = WavaVecaConfig() if is_seq_class: snake_case_ = read_txt_into_dict(_SCREAMING_SNAKE_CASE ) snake_case_ = idalabel snake_case_ = WavaVecaForSequenceClassification(_SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) elif is_finetuned: if dict_path: snake_case_ = Dictionary.load(_SCREAMING_SNAKE_CASE ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq snake_case_ = target_dict.pad_index snake_case_ = target_dict.bos_index snake_case_ = target_dict.eos_index snake_case_ = len(target_dict.symbols ) snake_case_ = os.path.join(_SCREAMING_SNAKE_CASE , """vocab.json""" ) if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) ) return os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) snake_case_ = target_dict.indices # fairseq has the <pad> and <s> switched snake_case_ = 0 snake_case_ = 1 with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaCTCTokenizer( _SCREAMING_SNAKE_CASE , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=_SCREAMING_SNAKE_CASE , ) snake_case_ = True if config.feat_extract_norm == """layer""" else False snake_case_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) snake_case_ = WavaVecaProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaForCTC(_SCREAMING_SNAKE_CASE ) else: snake_case_ = WavaVecaForPreTraining(_SCREAMING_SNAKE_CASE ) if is_finetuned or is_seq_class: snake_case_ , snake_case_ , snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: snake_case_ = argparse.Namespace(task="""audio_pretraining""" ) snake_case_ = fairseq.tasks.setup_task(_SCREAMING_SNAKE_CASE ) snake_case_ , snake_case_ , snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=_SCREAMING_SNAKE_CASE ) snake_case_ = model[0].eval() recursively_load_weights(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , not is_finetuned ) hf_wavavec.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) __SCREAMING_SNAKE_CASE : Any = parser.parse_args() __SCREAMING_SNAKE_CASE : List[Any] = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
347
0
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. lowercase_ = {"""LayoutLMv2Config""", """LayoutLMv3Config"""} @is_pipeline_test class a_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCamelCase = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: UpperCamelCase = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: UpperCamelCase = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def snake_case_( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" ) _SCREAMING_SNAKE_CASE = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(A ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) _SCREAMING_SNAKE_CASE = text_classifier("""This is great !""" , top_k=2 ) self.assertEqual( nested_simplify(A ) , [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}] ) _SCREAMING_SNAKE_CASE = text_classifier(["""This is great !""", """This is bad"""] , top_k=2 ) self.assertEqual( nested_simplify(A ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) _SCREAMING_SNAKE_CASE = text_classifier("""This is great !""" , top_k=1 ) self.assertEqual(nested_simplify(A ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) # Legacy behavior _SCREAMING_SNAKE_CASE = text_classifier("""This is great !""" , return_all_scores=A ) self.assertEqual(nested_simplify(A ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) _SCREAMING_SNAKE_CASE = text_classifier("""This is great !""" , return_all_scores=A ) self.assertEqual( nested_simplify(A ) , [[{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]] ) _SCREAMING_SNAKE_CASE = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=A ) self.assertEqual( nested_simplify(A ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) _SCREAMING_SNAKE_CASE = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=A ) self.assertEqual( nested_simplify(A ) , [ {"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_0""", """score""": 0.504}, ] , ) @require_torch def snake_case_( self ) -> int: import torch _SCREAMING_SNAKE_CASE = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" , device=torch.device("""cpu""" ) , ) _SCREAMING_SNAKE_CASE = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(A ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @require_tf def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""tf""" ) _SCREAMING_SNAKE_CASE = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(A ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @slow @require_torch def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = pipeline("""text-classification""" ) _SCREAMING_SNAKE_CASE = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(A ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) _SCREAMING_SNAKE_CASE = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(A ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) _SCREAMING_SNAKE_CASE = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(A ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) @slow @require_tf def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE = pipeline("""text-classification""" , framework="""tf""" ) _SCREAMING_SNAKE_CASE = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(A ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) _SCREAMING_SNAKE_CASE = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(A ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) _SCREAMING_SNAKE_CASE = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(A ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) def snake_case_( self , A , A , A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = TextClassificationPipeline(model=A , tokenizer=A ) return text_classifier, ["HuggingFace is in", "This is another test"] def snake_case_( self , A , A ) -> int: _SCREAMING_SNAKE_CASE = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 _SCREAMING_SNAKE_CASE = """HuggingFace is in""" _SCREAMING_SNAKE_CASE = text_classifier(A ) self.assertEqual(nested_simplify(A ) , [{"""label""": ANY(A ), """score""": ANY(A )}] ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) _SCREAMING_SNAKE_CASE = ["""HuggingFace is in """, """Paris is in France"""] _SCREAMING_SNAKE_CASE = text_classifier(A ) self.assertEqual( nested_simplify(A ) , [{"""label""": ANY(A ), """score""": ANY(A )}, {"""label""": ANY(A ), """score""": ANY(A )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) self.assertTrue(outputs[1]["""label"""] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format _SCREAMING_SNAKE_CASE = text_classifier(A , top_k=A ) _SCREAMING_SNAKE_CASE = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(A ) , [[{"""label""": ANY(A ), """score""": ANY(A )}] * N, [{"""label""": ANY(A ), """score""": ANY(A )}] * N] , ) _SCREAMING_SNAKE_CASE = {"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""} _SCREAMING_SNAKE_CASE = text_classifier(A ) self.assertEqual( nested_simplify(A ) , {"""label""": ANY(A ), """score""": ANY(A )} , ) self.assertTrue(outputs["""label"""] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. _SCREAMING_SNAKE_CASE = [["""HuggingFace is in """, """Paris is in France"""]] with self.assertRaises(A ): text_classifier(A ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility _SCREAMING_SNAKE_CASE = text_classifier([[["""HuggingFace is in """, """Paris is in France"""]]] ) self.assertEqual( nested_simplify(A ) , [{"""label""": ANY(A ), """score""": ANY(A )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() )
58
"""simple docstring""" import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class __A : '''simple docstring''' def __init__( self : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any=14 , UpperCAmelCase_ : Union[str, Any]=7 , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : str=99 , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : List[Any]=4 , UpperCAmelCase_ : Optional[int]=4 , UpperCAmelCase_ : int=4 , UpperCAmelCase_ : str=37 , UpperCAmelCase_ : Any="gelu" , UpperCAmelCase_ : str=0.1 , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : int=512 , UpperCAmelCase_ : Tuple=0.02 , ) ->List[str]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = rotary_dim snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = initializer_range snake_case_ = None snake_case_ = vocab_size - 1 snake_case_ = vocab_size - 1 snake_case_ = vocab_size - 1 def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_input_mask: snake_case_ = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=UpperCAmelCase_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""input_ids""": input_ids, """attention_mask""": attention_mask} return config, inputs_dict def lowerCAmelCase ( self : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict ) ->Tuple: """simple docstring""" snake_case_ = 20 snake_case_ = model_class_name(UpperCAmelCase_ ) snake_case_ = model.init_cache(input_ids.shape[0] , UpperCAmelCase_ ) snake_case_ = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) snake_case_ = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) snake_case_ = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) snake_case_ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="""i4""" ) snake_case_ = model( input_ids[:, -1:] , attention_mask=UpperCAmelCase_ , past_key_values=outputs_cache.past_key_values , position_ids=UpperCAmelCase_ , ) snake_case_ = model(UpperCAmelCase_ ) snake_case_ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = 20 snake_case_ = model_class_name(UpperCAmelCase_ ) snake_case_ = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) snake_case_ = model.init_cache(input_ids.shape[0] , UpperCAmelCase_ ) snake_case_ = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) snake_case_ = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) snake_case_ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="""i4""" ) snake_case_ = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) snake_case_ = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ ) snake_case_ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) @require_flax class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Any = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () __lowercase: List[str] = (FlaxGPTJForCausalLM,) if is_flax_available() else () def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = FlaxGPTJModelTester(self ) def lowerCAmelCase ( self : int ) ->List[Any]: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ , snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : List[str] ) ->Any: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ , snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) @tooslow def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" snake_case_ = GPTaTokenizer.from_pretrained("""gpt2""" , pad_token="""<|endoftext|>""" , padding_side="""left""" ) snake_case_ = tokenizer(["""Hello this is a long string""", """Hey"""] , return_tensors="""np""" , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ ) snake_case_ = FlaxGPTJForCausalLM.from_pretrained("""EleutherAI/gpt-j-6B""" ) snake_case_ = False snake_case_ = model.config.eos_token_id snake_case_ = jax.jit(model.generate ) snake_case_ = jit_generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , pad_token_id=tokenizer.pad_token_id ).sequences snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = [ """Hello this is a long string of text.\n\nI'm trying to get the text of the""", """Hey, I'm a little late to the party. I'm going to""", ] self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) @is_pt_flax_cross_test def lowerCAmelCase ( self : int ) ->str: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class snake_case_ = model_class.__name__[4:] # Skip the "Flax" at the beginning snake_case_ = getattr(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ , snake_case_ = pt_inputs["""input_ids"""].shape snake_case_ = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCAmelCase_ ): snake_case_ = 0 snake_case_ = 1 snake_case_ = 0 snake_case_ = 1 snake_case_ = pt_model_class(UpperCAmelCase_ ).eval() snake_case_ = model_class(UpperCAmelCase_ , dtype=jnp.floataa ) snake_case_ = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , UpperCAmelCase_ ) snake_case_ = fx_state with torch.no_grad(): snake_case_ = pt_model(**UpperCAmelCase_ ).to_tuple() snake_case_ = fx_model(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(UpperCAmelCase_ ) snake_case_ = model_class.from_pretrained(UpperCAmelCase_ , from_pt=UpperCAmelCase_ ) snake_case_ = fx_model_loaded(**UpperCAmelCase_ ).to_tuple() self.assertEqual( len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output_loaded, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class snake_case_ = model_class.__name__[4:] # Skip the "Flax" at the beginning snake_case_ = getattr(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = pt_model_class(UpperCAmelCase_ ).eval() snake_case_ = model_class(UpperCAmelCase_ , dtype=jnp.floataa ) snake_case_ = load_flax_weights_in_pytorch_model(UpperCAmelCase_ , fx_model.params ) snake_case_ , snake_case_ = pt_inputs["""input_ids"""].shape snake_case_ = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCAmelCase_ ): snake_case_ = 0 snake_case_ = 1 snake_case_ = 0 snake_case_ = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): snake_case_ = pt_model(**UpperCAmelCase_ ).to_tuple() snake_case_ = fx_model(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(UpperCAmelCase_ ) snake_case_ = pt_model_class.from_pretrained(UpperCAmelCase_ , from_flax=UpperCAmelCase_ ) with torch.no_grad(): snake_case_ = pt_model_loaded(**UpperCAmelCase_ ).to_tuple() self.assertEqual( len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ = model_class_name.from_pretrained("""EleutherAI/gpt-j-6B""" ) snake_case_ = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCAmelCase_ )
347
0
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class UpperCAmelCase : def __init__(self : Dict , snake_case__ : Dict , snake_case__ : Any=13 , snake_case__ : Any=32 , snake_case__ : Optional[Any]=2 , snake_case__ : Union[str, Any]=3 , snake_case__ : List[Any]=16 , snake_case__ : int=[1, 2, 1] , snake_case__ : Dict=[2, 2, 4] , snake_case__ : Dict=2 , snake_case__ : Tuple=2.0 , snake_case__ : Optional[int]=True , snake_case__ : Union[str, Any]=0.0 , snake_case__ : Any=0.0 , snake_case__ : Union[str, Any]=0.1 , snake_case__ : int="gelu" , snake_case__ : Optional[int]=False , snake_case__ : List[Any]=True , snake_case__ : List[str]=0.02 , snake_case__ : int=1e-5 , snake_case__ : List[str]=True , snake_case__ : Union[str, Any]=None , snake_case__ : List[Any]=True , snake_case__ : Optional[Any]=10 , snake_case__ : Optional[Any]=8 , snake_case__ : Any=["stage1", "stage2", "stage3"] , snake_case__ : Tuple=[1, 2, 3] , ) -> Union[str, Any]: '''simple docstring''' snake_case : Any = parent snake_case : Optional[int] = batch_size snake_case : Union[str, Any] = image_size snake_case : Dict = patch_size snake_case : Optional[Any] = num_channels snake_case : Union[str, Any] = embed_dim snake_case : int = depths snake_case : List[str] = num_heads snake_case : Union[str, Any] = window_size snake_case : Union[str, Any] = mlp_ratio snake_case : List[Any] = qkv_bias snake_case : List[Any] = hidden_dropout_prob snake_case : Union[str, Any] = attention_probs_dropout_prob snake_case : Union[str, Any] = drop_path_rate snake_case : int = hidden_act snake_case : Optional[int] = use_absolute_embeddings snake_case : int = patch_norm snake_case : Union[str, Any] = layer_norm_eps snake_case : Any = initializer_range snake_case : Optional[Any] = is_training snake_case : Tuple = scope snake_case : Optional[int] = use_labels snake_case : Optional[Any] = type_sequence_label_size snake_case : Union[str, Any] = encoder_stride snake_case : Any = out_features snake_case : Tuple = out_indices def _SCREAMING_SNAKE_CASE (self : Optional[Any] ) -> Dict: '''simple docstring''' snake_case : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case : int = None if self.use_labels: snake_case : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case : Dict = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE (self : List[str] ) -> int: '''simple docstring''' return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def _SCREAMING_SNAKE_CASE (self : Tuple , snake_case__ : List[Any] , snake_case__ : List[str] , snake_case__ : Tuple ) -> Optional[Any]: '''simple docstring''' snake_case : Union[str, Any] = MaskFormerSwinModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() snake_case : List[Any] = model(snake_case__ ) snake_case : Dict = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) snake_case : int = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _SCREAMING_SNAKE_CASE (self : List[str] , snake_case__ : Union[str, Any] , snake_case__ : List[Any] , snake_case__ : Union[str, Any] ) -> str: '''simple docstring''' snake_case : Optional[int] = MaskFormerSwinBackbone(config=snake_case__ ) model.to(snake_case__ ) model.eval() snake_case : List[Any] = model(snake_case__ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [16, 32, 64] ) # verify ValueError with self.parent.assertRaises(snake_case__ ): snake_case : Tuple = ["stem"] snake_case : List[Any] = MaskFormerSwinBackbone(config=snake_case__ ) def _SCREAMING_SNAKE_CASE (self : List[Any] ) -> List[Any]: '''simple docstring''' snake_case : Union[str, Any] = self.prepare_config_and_inputs() snake_case , snake_case , snake_case : List[Any] = config_and_inputs snake_case : int = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase ( A_ ,A_ ,unittest.TestCase ): A__ : List[str] = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) A__ : str = {"feature-extraction": MaskFormerSwinModel} if is_torch_available() else {} A__ : Optional[Any] = False A__ : List[Any] = False A__ : List[str] = False A__ : List[str] = False A__ : Union[str, Any] = False def _SCREAMING_SNAKE_CASE (self : Optional[int] ) -> List[str]: '''simple docstring''' snake_case : str = MaskFormerSwinModelTester(self ) snake_case : Optional[int] = ConfigTester(self , config_class=snake_case__ , embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( "`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with" " `nn.DataParallel`" ) ) def _SCREAMING_SNAKE_CASE (self : str ) -> Optional[Any]: '''simple docstring''' pass def _SCREAMING_SNAKE_CASE (self : str ) -> List[str]: '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE (self : Tuple ) -> List[Any]: '''simple docstring''' return def _SCREAMING_SNAKE_CASE (self : Dict ) -> str: '''simple docstring''' snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def _SCREAMING_SNAKE_CASE (self : int ) -> Dict: '''simple docstring''' snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*snake_case__ ) @unittest.skip("Swin does not use inputs_embeds" ) def _SCREAMING_SNAKE_CASE (self : int ) -> Any: '''simple docstring''' pass @unittest.skip("Swin does not support feedforward chunking" ) def _SCREAMING_SNAKE_CASE (self : List[str] ) -> Dict: '''simple docstring''' pass def _SCREAMING_SNAKE_CASE (self : Optional[Any] ) -> List[str]: '''simple docstring''' snake_case , snake_case : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case : int = model_class(snake_case__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case : List[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case__ , nn.Linear ) ) def _SCREAMING_SNAKE_CASE (self : Optional[Any] ) -> Dict: '''simple docstring''' snake_case , snake_case : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case : str = model_class(snake_case__ ) snake_case : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case : Optional[Any] = [*signature.parameters.keys()] snake_case : Tuple = ["pixel_values"] self.assertListEqual(arg_names[:1] , snake_case__ ) @unittest.skip(reason="MaskFormerSwin is only used as backbone and doesn't support output_attentions" ) def _SCREAMING_SNAKE_CASE (self : List[Any] ) -> str: '''simple docstring''' pass @unittest.skip(reason="MaskFormerSwin is only used as an internal backbone" ) def _SCREAMING_SNAKE_CASE (self : Tuple ) -> Any: '''simple docstring''' pass def _SCREAMING_SNAKE_CASE (self : Optional[Any] , snake_case__ : List[Any] , snake_case__ : str , snake_case__ : List[Any] , snake_case__ : Tuple ) -> Optional[int]: '''simple docstring''' snake_case : Tuple = model_class(snake_case__ ) model.to(snake_case__ ) model.eval() with torch.no_grad(): snake_case : Any = model(**self._prepare_for_class(snake_case__ , snake_case__ ) ) snake_case : int = outputs.hidden_states snake_case : Union[str, Any] = getattr( self.model_tester , "expected_num_hidden_layers" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(snake_case__ ) , snake_case__ ) # Swin has a different seq_length snake_case : Any = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case : Tuple = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _SCREAMING_SNAKE_CASE (self : Dict ) -> Union[str, Any]: '''simple docstring''' snake_case , snake_case : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case : int = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: snake_case : int = True self.check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case : Dict = True self.check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) def _SCREAMING_SNAKE_CASE (self : int ) -> Any: '''simple docstring''' snake_case , snake_case : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case : Any = 3 snake_case : List[str] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) snake_case : Tuple = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case : str = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) snake_case : str = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: snake_case : str = True self.check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case : Optional[Any] = True self.check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ , (padded_height, padded_width) ) @unittest.skip(reason="MaskFormerSwin doesn't have pretrained checkpoints" ) def _SCREAMING_SNAKE_CASE (self : Optional[int] ) -> str: '''simple docstring''' pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def _SCREAMING_SNAKE_CASE (self : str ) -> int: '''simple docstring''' pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def _SCREAMING_SNAKE_CASE (self : int ) -> str: '''simple docstring''' pass def _SCREAMING_SNAKE_CASE (self : Any ) -> Any: '''simple docstring''' snake_case , snake_case : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(snake_case__ : Union[str, Any] ): snake_case : Any = 0 return t def check_equivalence(snake_case__ : Union[str, Any] , snake_case__ : int , snake_case__ : List[str] , snake_case__ : Optional[int]={} ): with torch.no_grad(): snake_case : Optional[Any] = model(**snake_case__ , return_dict=snake_case__ , **snake_case__ ) snake_case : Tuple = model(**snake_case__ , return_dict=snake_case__ , **snake_case__ ).to_tuple() def recursive_check(snake_case__ : List[str] , snake_case__ : Optional[Any] ): if isinstance(snake_case__ , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(snake_case__ , snake_case__ ): recursive_check(snake_case__ , snake_case__ ) elif isinstance(snake_case__ , snake_case__ ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(snake_case__ , snake_case__ ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(snake_case__ ) , set_nan_tensor_to_zero(snake_case__ ) , atol=1e-5 ) , msg=( "Tuple and dict output are not equal. Difference:" f""" {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:""" f""" {torch.isnan(snake_case__ ).any()} and `inf`: {torch.isinf(snake_case__ )}. Dict has""" f""" `nan`: {torch.isnan(snake_case__ ).any()} and `inf`: {torch.isinf(snake_case__ )}.""" ) , ) recursive_check(snake_case__ , snake_case__ ) for model_class in self.all_model_classes: snake_case : Optional[int] = model_class(snake_case__ ) model.to(snake_case__ ) model.eval() snake_case : Union[str, Any] = self._prepare_for_class(snake_case__ , snake_case__ ) snake_case : Tuple = self._prepare_for_class(snake_case__ , snake_case__ ) check_equivalence(snake_case__ , snake_case__ , snake_case__ ) snake_case : Tuple = self._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) snake_case : Optional[Any] = self._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) check_equivalence(snake_case__ , snake_case__ , snake_case__ ) snake_case : Dict = self._prepare_for_class(snake_case__ , snake_case__ ) snake_case : List[Any] = self._prepare_for_class(snake_case__ , snake_case__ ) check_equivalence(snake_case__ , snake_case__ , snake_case__ , {"output_hidden_states": True} ) snake_case : Any = self._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) snake_case : List[str] = self._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) check_equivalence(snake_case__ , snake_case__ , snake_case__ , {"output_hidden_states": True} ) @require_torch class UpperCAmelCase ( unittest.TestCase ,A_ ): A__ : int = (MaskFormerSwinBackbone,) if is_torch_available() else () A__ : int = MaskFormerSwinConfig def _SCREAMING_SNAKE_CASE (self : List[Any] ) -> Any: '''simple docstring''' snake_case : Union[str, Any] = MaskFormerSwinModelTester(self ) def _SCREAMING_SNAKE_CASE (self : Optional[int] ) -> Optional[Any]: '''simple docstring''' snake_case , snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_common() snake_case : Optional[int] = inputs_dict["pixel_values"].shape[0] for backbone_class in self.all_model_classes: snake_case : Optional[int] = backbone_class(snake_case__ ) backbone.to(snake_case__ ) backbone.eval() snake_case : Union[str, Any] = backbone(**snake_case__ ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , snake_case__ ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True snake_case : Optional[int] = backbone(**snake_case__ , output_hidden_states=snake_case__ ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) snake_case , snake_case , snake_case : Dict = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: snake_case : Optional[Any] = backbone(**snake_case__ , output_attentions=snake_case__ ) self.assertIsNotNone(outputs.attentions )
59
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING __SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) class __A (snake_case__): '''simple docstring''' __lowercase: int = """upernet""" def __init__( self : str , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : str=512 , UpperCAmelCase_ : int=0.02 , UpperCAmelCase_ : Optional[Any]=[1, 2, 3, 6] , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Tuple=0.4 , UpperCAmelCase_ : Tuple=384 , UpperCAmelCase_ : Union[str, Any]=256 , UpperCAmelCase_ : str=1 , UpperCAmelCase_ : Tuple=False , UpperCAmelCase_ : Tuple=255 , **UpperCAmelCase_ : Dict , ) ->Union[str, Any]: """simple docstring""" super().__init__(**UpperCAmelCase_ ) if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) snake_case_ = CONFIG_MAPPING["""resnet"""](out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = backbone_config.get("""model_type""" ) snake_case_ = CONFIG_MAPPING[backbone_model_type] snake_case_ = config_class.from_dict(UpperCAmelCase_ ) snake_case_ = backbone_config snake_case_ = hidden_size snake_case_ = initializer_range snake_case_ = pool_scales snake_case_ = use_auxiliary_head snake_case_ = auxiliary_loss_weight snake_case_ = auxiliary_in_channels snake_case_ = auxiliary_channels snake_case_ = auxiliary_num_convs snake_case_ = auxiliary_concat_input snake_case_ = loss_ignore_index def lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.backbone_config.to_dict() snake_case_ = self.__class__.model_type return output
347
0
"""simple docstring""" def _snake_case ( _snake_case : list ): for i in range(len(_snake_case ) - 1 , 0 , -1 ): lowerCAmelCase : int = False for j in range(_snake_case , 0 , -1 ): if unsorted[j] < unsorted[j - 1]: lowerCAmelCase, lowerCAmelCase : Tuple = unsorted[j - 1], unsorted[j] lowerCAmelCase : Optional[Any] = True for j in range(_snake_case ): if unsorted[j] > unsorted[j + 1]: lowerCAmelCase, lowerCAmelCase : Any = unsorted[j + 1], unsorted[j] lowerCAmelCase : int = True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() snake_case__ : List[str] = input('''Enter numbers separated by a comma:\n''').strip() snake_case__ : str = [int(item) for item in user_input.split(''',''')] print(f"""{cocktail_shaker_sort(unsorted) = }""")
60
"""simple docstring""" import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = """ylacombe/bark-small""" snake_case_ = tempfile.mkdtemp() snake_case_ = """en_speaker_1""" snake_case_ = """This is a test string""" snake_case_ = """speaker_embeddings_path.json""" snake_case_ = """speaker_embeddings""" def lowerCAmelCase ( self : List[str] , **UpperCAmelCase_ : str ) ->Optional[int]: """simple docstring""" return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = self.get_tokenizer() snake_case_ = BarkProcessor(tokenizer=UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) snake_case_ = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def lowerCAmelCase ( self : Dict ) ->int: """simple docstring""" snake_case_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) snake_case_ = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) snake_case_ = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) snake_case_ = 35 snake_case_ = 2 snake_case_ = 8 snake_case_ = { """semantic_prompt""": np.ones(UpperCAmelCase_ ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset snake_case_ = processor(text=self.input_string , voice_preset=UpperCAmelCase_ ) snake_case_ = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([] ) ).tolist() ) # test loading voice preset from npz file snake_case_ = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(UpperCAmelCase_ , **UpperCAmelCase_ ) snake_case_ = processor(text=self.input_string , voice_preset=UpperCAmelCase_ ) snake_case_ = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([] ) ).tolist() ) # test loading voice preset from the hub snake_case_ = processor(text=self.input_string , voice_preset=self.voice_preset ) def lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" snake_case_ = self.get_tokenizer() snake_case_ = BarkProcessor(tokenizer=UpperCAmelCase_ ) snake_case_ = processor(text=self.input_string ) snake_case_ = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
347
0
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class A_ : '''simple docstring''' def __init__( self , lowercase_ , lowercase_=13 , lowercase_=2 , lowercase_=24 , lowercase_=16 , lowercase_=True , lowercase_=True , lowercase_=32 , lowercase_=5 , lowercase_=4 , lowercase_=37 , lowercase_="gelu" , lowercase_=0.1 , lowercase_=0.1 , lowercase_=10 , lowercase_=0.02 , lowercase_=None , lowercase_=2 , lowercase_=2 , ): """simple docstring""" UpperCAmelCase_ : Optional[int] = parent UpperCAmelCase_ : Union[str, Any] = batch_size UpperCAmelCase_ : List[str] = patch_size UpperCAmelCase_ : Tuple = max_length UpperCAmelCase_ : Optional[Any] = num_mel_bins UpperCAmelCase_ : List[str] = is_training UpperCAmelCase_ : List[Any] = use_labels UpperCAmelCase_ : Dict = hidden_size UpperCAmelCase_ : List[str] = num_hidden_layers UpperCAmelCase_ : List[Any] = num_attention_heads UpperCAmelCase_ : Union[str, Any] = intermediate_size UpperCAmelCase_ : Optional[Any] = hidden_act UpperCAmelCase_ : Optional[int] = hidden_dropout_prob UpperCAmelCase_ : str = attention_probs_dropout_prob UpperCAmelCase_ : str = type_sequence_label_size UpperCAmelCase_ : Optional[int] = initializer_range UpperCAmelCase_ : Any = scope UpperCAmelCase_ : str = frequency_stride UpperCAmelCase_ : Dict = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) UpperCAmelCase_ : Any = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 UpperCAmelCase_ : List[str] = (self.max_length - self.patch_size) // self.time_stride + 1 UpperCAmelCase_ : Optional[int] = frequency_out_dimension * time_out_dimension UpperCAmelCase_ : Union[str, Any] = num_patches + 2 def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Optional[Any] = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) UpperCAmelCase_ : Optional[Any] = None if self.use_labels: UpperCAmelCase_ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ : Optional[Any] = self.get_config() return config, input_values, labels def UpperCamelCase__ ( self ): """simple docstring""" return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowercase_ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def UpperCamelCase__ ( self , lowercase_ , lowercase_ , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Dict = ASTModel(config=lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase_ : str = model(lowercase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Union[str, Any] = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) : Optional[int] = config_and_inputs UpperCAmelCase_ : str = {"input_values": input_values} return config, inputs_dict @require_torch class A_ (lowercase__ ,lowercase__ ,unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ : Dict = ( {"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel} if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Tuple = False def UpperCamelCase__ ( self , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ): """simple docstring""" if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Optional[int] = ASTModelTester(self ) UpperCAmelCase_ : Tuple = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37 ) def UpperCamelCase__ ( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="AST does not use inputs_embeds" ) def UpperCamelCase__ ( self ): """simple docstring""" pass def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ : Optional[Any] = model_class(lowercase_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCAmelCase_ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowercase_ , nn.Linear ) ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ : Dict = model_class(lowercase_ ) UpperCAmelCase_ : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase_ : int = [*signature.parameters.keys()] UpperCAmelCase_ : List[Any] = ["input_values"] self.assertListEqual(arg_names[:1] , lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_ ) @slow def UpperCamelCase__ ( self ): """simple docstring""" for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : Optional[Any] = ASTModel.from_pretrained(lowercase_ ) self.assertIsNotNone(lowercase_ ) def __a ( ): UpperCAmelCase_ : Any = hf_hub_download( repo_id="nielsr/audio-spectogram-transformer-checkpoint", filename="sample_audio.flac", repo_type="dataset" ) UpperCAmelCase_ , UpperCAmelCase_ : Any = torchaudio.load(__lowerCamelCase ) return audio, sampling_rate @require_torch @require_torchaudio class A_ (unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase__ ( self ): """simple docstring""" return ( ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ) if is_torchaudio_available() else None ) @slow def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : str = self.default_feature_extractor UpperCAmelCase_ : str = ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ).to(lowercase_ ) UpperCAmelCase_ : List[Any] = self.default_feature_extractor UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = prepare_audio() UpperCAmelCase_ : int = audio.squeeze().numpy() UpperCAmelCase_ : Any = feature_extractor(lowercase_ , sampling_rate=lowercase_ , return_tensors="pt" ).to(lowercase_ ) # forward pass with torch.no_grad(): UpperCAmelCase_ : Optional[Any] = model(**lowercase_ ) # verify the logits UpperCAmelCase_ : List[Any] = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , lowercase_ ) UpperCAmelCase_ : List[Any] = torch.tensor([-0.87_60, -7.00_42, -8.66_02] ).to(lowercase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1E-4 ) )
61
"""simple docstring""" import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 __SCREAMING_SNAKE_CASE : int = sys.version_info >= (3, 10) def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: return field(default_factory=lambda: default , metadata=_SCREAMING_SNAKE_CASE ) @dataclass class __A : '''simple docstring''' __lowercase: int __lowercase: float __lowercase: str __lowercase: bool @dataclass class __A : '''simple docstring''' __lowercase: int = 42 __lowercase: str = field(default="""toto""" , metadata={"""help""": """help message"""}) @dataclass class __A : '''simple docstring''' __lowercase: bool = False __lowercase: bool = True __lowercase: Optional[bool] = None class __A (snake_case__): '''simple docstring''' __lowercase: str = """titi""" __lowercase: Any = """toto""" class __A (snake_case__): '''simple docstring''' __lowercase: int = """titi""" __lowercase: Optional[Any] = """toto""" __lowercase: List[Any] = 42 @dataclass class __A : '''simple docstring''' __lowercase: BasicEnum = "toto" def lowerCAmelCase ( self : int ) ->List[Any]: """simple docstring""" snake_case_ = BasicEnum(self.foo ) @dataclass class __A : '''simple docstring''' __lowercase: MixedTypeEnum = "toto" def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = MixedTypeEnum(self.foo ) @dataclass class __A : '''simple docstring''' __lowercase: Optional[int] = None __lowercase: Optional[float] = field(default=snake_case__ , metadata={"""help""": """help message"""}) __lowercase: Optional[str] = None __lowercase: Optional[List[str]] = list_field(default=[]) __lowercase: Optional[List[int]] = list_field(default=[]) @dataclass class __A : '''simple docstring''' __lowercase: List[int] = list_field(default=[]) __lowercase: List[int] = list_field(default=[1, 2, 3]) __lowercase: List[str] = list_field(default=["""Hallo""", """Bonjour""", """Hello"""]) __lowercase: List[float] = list_field(default=[0.1, 0.2, 0.3]) @dataclass class __A : '''simple docstring''' __lowercase: List[int] = field() __lowercase: str = field() __lowercase: BasicEnum = field() def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" snake_case_ = BasicEnum(self.required_enum ) @dataclass class __A : '''simple docstring''' __lowercase: int __lowercase: "BasicEnum" = field() __lowercase: "Optional[bool]" = None __lowercase: "str" = field(default="""toto""" , metadata={"""help""": """help message"""}) __lowercase: "List[str]" = list_field(default=["""Hallo""", """Bonjour""", """Hello"""]) if is_python_no_less_than_3_10: @dataclass class __A : '''simple docstring''' __lowercase: bool = False __lowercase: bool = True __lowercase: bool | None = None @dataclass class __A : '''simple docstring''' __lowercase: int | None = None __lowercase: float | None = field(default=snake_case__ , metadata={"""help""": """help message"""}) __lowercase: str | None = None __lowercase: list[str] | None = list_field(default=[]) __lowercase: list[int] | None = list_field(default=[]) class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : argparse.ArgumentParser , UpperCAmelCase_ : argparse.ArgumentParser ) ->Optional[int]: """simple docstring""" self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): snake_case_ = {k: v for k, v in vars(UpperCAmelCase_ ).items() if k != """container"""} snake_case_ = {k: v for k, v in vars(UpperCAmelCase_ ).items() if k != """container"""} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("""choices""" , UpperCAmelCase_ ) and yy.get("""choices""" , UpperCAmelCase_ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["""type"""](UpperCAmelCase_ ) , yy["""type"""](UpperCAmelCase_ ) ) del xx["type"], yy["type"] self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : int ) ->Any: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--bar""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--baz""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--flag""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ , const=UpperCAmelCase_ , nargs="""?""" ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = ["""--foo""", """1""", """--baz""", """quux""", """--bar""", """0.5"""] ((snake_case_) , ) = parser.parse_args_into_dataclasses(UpperCAmelCase_ , look_for_args_file=UpperCAmelCase_ ) self.assertFalse(example.flag ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=42 , type=UpperCAmelCase_ ) expected.add_argument("""--baz""" , default="""toto""" , type=UpperCAmelCase_ , help="""help message""" ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ , const=UpperCAmelCase_ , nargs="""?""" ) expected.add_argument("""--baz""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ , const=UpperCAmelCase_ , nargs="""?""" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("""--no_baz""" , action="""store_false""" , default=UpperCAmelCase_ , dest="""baz""" ) expected.add_argument("""--opt""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ ) snake_case_ = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(UpperCAmelCase_ ) for dataclass_type in dataclass_types: snake_case_ = HfArgumentParser(UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """--no_baz"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """--baz"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """True""", """--baz""", """True""", """--opt""", """True"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """False""", """--baz""", """False""", """--opt""", """False"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) def lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=["""titi""", """toto""", 42] , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) snake_case_ = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) snake_case_ = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) snake_case_ = parser.parse_args_into_dataclasses(["""--foo""", """titi"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) snake_case_ = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) snake_case_ = parser.parse_args_into_dataclasses(["""--foo""", """42"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" @dataclass class __A : '''simple docstring''' __lowercase: Literal["titi", "toto", 42] = "toto" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=("""titi""", """toto""", 42) , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) snake_case_ = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) snake_case_ = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo_int""" , nargs="""+""" , default=[] , type=UpperCAmelCase_ ) expected.add_argument("""--bar_int""" , nargs="""+""" , default=[1, 2, 3] , type=UpperCAmelCase_ ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=UpperCAmelCase_ ) expected.add_argument("""--foo_float""" , nargs="""+""" , default=[0.1, 0.2, 0.3] , type=UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual( UpperCAmelCase_ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["""Hallo""", """Bonjour""", """Hello"""] , foo_float=[0.1, 0.2, 0.3] ) , ) snake_case_ = parser.parse_args("""--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7""".split() ) self.assertEqual(UpperCAmelCase_ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["""a""", """b""", """c"""] , foo_float=[0.1, 0.7] ) ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=UpperCAmelCase_ , type=UpperCAmelCase_ ) expected.add_argument("""--bar""" , default=UpperCAmelCase_ , type=UpperCAmelCase_ , help="""help message""" ) expected.add_argument("""--baz""" , default=UpperCAmelCase_ , type=UpperCAmelCase_ ) expected.add_argument("""--ces""" , nargs="""+""" , default=[] , type=UpperCAmelCase_ ) expected.add_argument("""--des""" , nargs="""+""" , default=[] , type=UpperCAmelCase_ ) snake_case_ = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(UpperCAmelCase_ ) for dataclass_type in dataclass_types: snake_case_ = HfArgumentParser(UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , bar=UpperCAmelCase_ , baz=UpperCAmelCase_ , ces=[] , des=[] ) ) snake_case_ = parser.parse_args("""--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3""".split() ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=12 , bar=3.14 , baz="""42""" , ces=["""a""", """b""", """c"""] , des=[1, 2, 3] ) ) def lowerCAmelCase ( self : Optional[Any] ) ->Optional[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--required_list""" , nargs="""+""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--required_str""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=UpperCAmelCase_ , ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=UpperCAmelCase_ , ) expected.add_argument("""--opt""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ ) expected.add_argument("""--baz""" , default="""toto""" , type=UpperCAmelCase_ , help="""help message""" ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } snake_case_ = parser.parse_dict(UpperCAmelCase_ )[0] snake_case_ = BasicExample(**UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, """extra""": 42, } self.assertRaises(UpperCAmelCase_ , parser.parse_dict , UpperCAmelCase_ , allow_extra_keys=UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = os.path.join(UpperCAmelCase_ , """temp_json""" ) os.mkdir(UpperCAmelCase_ ) with open(temp_local_path + """.json""" , """w+""" ) as f: json.dump(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_yaml_file(Path(temp_local_path + """.json""" ) )[0] snake_case_ = BasicExample(**UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = os.path.join(UpperCAmelCase_ , """temp_yaml""" ) os.mkdir(UpperCAmelCase_ ) with open(temp_local_path + """.yaml""" , """w+""" ) as f: yaml.dump(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_yaml_file(Path(temp_local_path + """.yaml""" ) )[0] snake_case_ = BasicExample(**UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ )
347
0
_A = '\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' _A = [{'type': 'code', 'content': INSTALL_CONTENT}] _A = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
62
"""simple docstring""" import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy __SCREAMING_SNAKE_CASE : Any = logging.getLogger(__name__) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , ) -> Optional[Any]: snake_case_ = bnb_quantization_config.load_in_abit snake_case_ = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( """You have a version of `bitsandbytes` that is not compatible with 8bit quantization,""" """ make sure you have the latest version of `bitsandbytes` installed.""" ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( """You have a version of `bitsandbytes` that is not compatible with 4bit quantization,""" """make sure you have the latest version of `bitsandbytes` installed.""" ) snake_case_ = [] # custom device map if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(device_map.keys() ) > 1: snake_case_ = [key for key, value in device_map.items() if value in ["""disk""", """cpu"""]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: snake_case_ = get_keys_to_not_convert(_SCREAMING_SNAKE_CASE ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(_SCREAMING_SNAKE_CASE ) snake_case_ = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: snake_case_ = [] snake_case_ = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(_SCREAMING_SNAKE_CASE ) # compatibility with peft snake_case_ = load_in_abit snake_case_ = load_in_abit snake_case_ = get_parameter_device(_SCREAMING_SNAKE_CASE ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( """It is not recommended to quantize a loaded model. """ """The model should be instantiated under the `init_empty_weights` context manager.""" ) snake_case_ = replace_with_bnb_layers(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE ) # convert param to the right dtype snake_case_ = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: snake_case_ = name.replace(""".weight""" , """""" ).replace(""".bias""" , """""" ) snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(_SCREAMING_SNAKE_CASE ): param.to(_SCREAMING_SNAKE_CASE ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info( f"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" """We move the model to cuda.""" ) return model elif weights_location is None: raise RuntimeError( f"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): snake_case_ = replace_with_bnb_layers( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE ) snake_case_ = get_quantized_model_device_map( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_memory=_SCREAMING_SNAKE_CASE , no_split_module_classes=_SCREAMING_SNAKE_CASE , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): snake_case_ = True snake_case_ = any(x in list(device_map.values() ) for x in ["""cpu""", """disk"""] ) load_checkpoint_in_model( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=bnb_quantization_config.torch_dtype , offload_folder=_SCREAMING_SNAKE_CASE , offload_state_dict=_SCREAMING_SNAKE_CASE , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(_SCREAMING_SNAKE_CASE , device_map=_SCREAMING_SNAKE_CASE , offload_dir=_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: if device_map is None: if torch.cuda.is_available(): snake_case_ = {"""""": torch.cuda.current_device()} else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info("""The device_map was not initialized.""" """Setting device_map to `{'':torch.cuda.current_device()}`.""" ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( """If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or """ """'sequential'.""" ) snake_case_ = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) snake_case_ = {} snake_case_ = special_dtypes snake_case_ = no_split_module_classes snake_case_ = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": snake_case_ = get_balanced_memory( _SCREAMING_SNAKE_CASE , low_zero=(device_map == """balanced_low_0""") , max_memory=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) snake_case_ = max_memory snake_case_ = infer_auto_device_map(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # check if don't have any quantized module on the cpu snake_case_ = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules snake_case_ = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( """ Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules in `torch_dtype`, you need to pass a custom `device_map` to `load_and_quantize_model`. Check https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk for more details. """ ) else: logger.info( """Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit""" ) del device_map_without_some_modules return device_map def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: if modules_to_not_convert is None: snake_case_ = [] snake_case_ , snake_case_ = _replace_with_bnb_layers( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , ) -> List[Any]: snake_case_ = False for name, module in model.named_children(): if current_key_name is None: snake_case_ = [] current_key_name.append(_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` snake_case_ = """.""".join(_SCREAMING_SNAKE_CASE ) snake_case_ = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: snake_case_ = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: snake_case_ = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=_SCREAMING_SNAKE_CASE , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: snake_case_ = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("""load_in_8bit and load_in_4bit can't be both False""" ) snake_case_ = module.weight.data if module.bias is not None: snake_case_ = module.bias.data bnb_module.requires_grad_(_SCREAMING_SNAKE_CASE ) setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = True if len(list(module.children() ) ) > 0: snake_case_ , snake_case_ = _replace_with_bnb_layers( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def _a ( _SCREAMING_SNAKE_CASE ) -> Any: # Create a copy of the model with init_empty_weights(): snake_case_ = deepcopy(_SCREAMING_SNAKE_CASE ) # this has 0 cost since it is done inside `init_empty_weights` context manager` snake_case_ = find_tied_parameters(_SCREAMING_SNAKE_CASE ) # For compatibility with Accelerate < 0.18 if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: snake_case_ = sum(_SCREAMING_SNAKE_CASE , [] ) snake_case_ = len(_SCREAMING_SNAKE_CASE ) > 0 # Check if it is a base model snake_case_ = False if hasattr(_SCREAMING_SNAKE_CASE , """base_model_prefix""" ): snake_case_ = not hasattr(_SCREAMING_SNAKE_CASE , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head snake_case_ = list(model.named_children() ) snake_case_ = [list_modules[-1][0]] # add last module together with tied weights snake_case_ = set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE ) snake_case_ = list(set(_SCREAMING_SNAKE_CASE ) ) + list(_SCREAMING_SNAKE_CASE ) # remove ".weight" from the keys snake_case_ = [""".weight""", """.bias"""] snake_case_ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: snake_case_ = name.replace(_SCREAMING_SNAKE_CASE , """""" ) filtered_module_names.append(_SCREAMING_SNAKE_CASE ) return filtered_module_names def _a ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: for m in model.modules(): if isinstance(_SCREAMING_SNAKE_CASE , bnb.nn.Linearabit ): return True return False def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: return next(parameter.parameters() ).device def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: # if it is not quantized, we quantize and offload the quantized weights and the SCB stats if fpaa_statistics is None: set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 0 , dtype=_SCREAMING_SNAKE_CASE , value=_SCREAMING_SNAKE_CASE ) snake_case_ = param_name snake_case_ = model if "." in tensor_name: snake_case_ = tensor_name.split(""".""" ) for split in splits[:-1]: snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if new_module is None: raise ValueError(f"""{module} has no attribute {split}.""" ) snake_case_ = new_module snake_case_ = splits[-1] # offload weights snake_case_ = False offload_weight(module._parameters[tensor_name] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) if hasattr(module._parameters[tensor_name] , """SCB""" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("""weight""" , """SCB""" ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE , ) else: offload_weight(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) offload_weight(_SCREAMING_SNAKE_CASE , param_name.replace("""weight""" , """SCB""" ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , """meta""" , dtype=_SCREAMING_SNAKE_CASE , value=torch.empty(*param.size() ) )
347
0
'''simple docstring''' import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : List[Any] , __a : int , __a : Optional[Any]=13 , __a : str=7 , __a : Optional[int]=True , __a : List[Any]=True , __a : Any=True , __a : List[str]=True , __a : str=99 , __a : int=32 , __a : Any=5 , __a : Union[str, Any]=4 , __a : Optional[int]=37 , __a : Optional[Any]="gelu" , __a : Any=0.1 , __a : str=0.1 , __a : Any=5_12 , __a : Optional[Any]=16 , __a : Dict=2 , __a : Union[str, Any]=0.02 , __a : Any=False , __a : Optional[int]=True , __a : List[Any]="None" , __a : Optional[int]=3 , __a : Dict=4 , __a : List[str]=None , ): _a = parent _a = batch_size _a = seq_length _a = is_training _a = use_input_mask _a = use_token_type_ids _a = use_labels _a = vocab_size _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = max_position_embeddings _a = type_vocab_size _a = type_sequence_label_size _a = initializer_range _a = num_labels _a = num_choices _a = relative_attention _a = position_biased_input _a = pos_att_type _a = scope def UpperCamelCase__ ( self : Optional[int] ): _a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a = None if self.use_input_mask: _a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) _a = None if self.use_token_type_ids: _a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _a = None _a = None _a = None if self.use_labels: _a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a = ids_tensor([self.batch_size] , self.num_choices ) _a = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase__ ( self : Optional[int] ): return DebertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def UpperCamelCase__ ( self : Any ): _a = self.get_config() _a = 3_00 return config def UpperCamelCase__ ( self : List[str] , __a : Dict ): self.parent.assertListEqual(list(result.loss.size() ) , [] ) def UpperCamelCase__ ( self : List[Any] , __a : int , __a : Dict , __a : Tuple , __a : str , __a : Union[str, Any] , __a : List[str] , __a : List[Any] ): _a = DebertaModel(config=__a ) model.to(__a ) model.eval() _a = model(__a , attention_mask=__a , token_type_ids=__a )[0] _a = model(__a , token_type_ids=__a )[0] _a = model(__a )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def UpperCamelCase__ ( self : str , __a : List[str] , __a : Optional[Any] , __a : Tuple , __a : List[Any] , __a : Dict , __a : Optional[Any] , __a : List[str] ): _a = DebertaForMaskedLM(config=__a ) model.to(__a ) model.eval() _a = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase__ ( self : Optional[Any] , __a : int , __a : Optional[int] , __a : Dict , __a : int , __a : Optional[int] , __a : str , __a : Dict ): _a = self.num_labels _a = DebertaForSequenceClassification(__a ) model.to(__a ) model.eval() _a = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__a ) def UpperCamelCase__ ( self : List[str] , __a : int , __a : Dict , __a : Union[str, Any] , __a : Dict , __a : str , __a : Optional[Any] , __a : List[str] ): _a = self.num_labels _a = DebertaForTokenClassification(config=__a ) model.to(__a ) model.eval() _a = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase__ ( self : Optional[Any] , __a : List[Any] , __a : Dict , __a : List[str] , __a : Optional[int] , __a : Union[str, Any] , __a : int , __a : Optional[Any] ): _a = DebertaForQuestionAnswering(config=__a ) model.to(__a ) model.eval() _a = model( __a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase__ ( self : List[str] ): _a = self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) = config_and_inputs _a = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) __a =( { 'feature-extraction': DebertaModel, 'fill-mask': DebertaForMaskedLM, 'question-answering': DebertaForQuestionAnswering, 'text-classification': DebertaForSequenceClassification, 'token-classification': DebertaForTokenClassification, 'zero-shot': DebertaForSequenceClassification, } if is_torch_available() else {} ) __a =True __a =False __a =False __a =False __a =False def UpperCamelCase__ ( self : Tuple ): _a = DebertaModelTester(self ) _a = ConfigTester(self , config_class=__a , hidden_size=37 ) def UpperCamelCase__ ( self : Optional[int] ): self.config_tester.run_common_tests() def UpperCamelCase__ ( self : str ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__a ) def UpperCamelCase__ ( self : Any ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__a ) def UpperCamelCase__ ( self : List[str] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__a ) def UpperCamelCase__ ( self : List[Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__a ) def UpperCamelCase__ ( self : Any ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__a ) @slow def UpperCamelCase__ ( self : List[str] ): for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a = DebertaModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @require_torch @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" @unittest.skip(reason="Model not available yet" ) def UpperCamelCase__ ( self : Tuple ): pass @slow def UpperCamelCase__ ( self : List[Any] ): _a = DebertaModel.from_pretrained("microsoft/deberta-base" ) _a = torch.tensor([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]] ) _a = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): _a = model(__a , attention_mask=__a )[0] # compare the actual values for a slice. _a = torch.tensor( [[[-0.5986, -0.8055, -0.8462], [1.4484, -0.9348, -0.8059], [0.3123, 0.0032, -1.4131]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __a , atol=1e-4 ) , f'{output[:, 1:4, 1:4]}' )
63
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple = { 'microsoft/beit-base-patch16-224-pt22k': ( 'https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json' ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __A (snake_case__): '''simple docstring''' __lowercase: Optional[int] = """beit""" def __init__( self : List[str] , UpperCAmelCase_ : List[Any]=8_192 , UpperCAmelCase_ : Dict=768 , UpperCAmelCase_ : int=12 , UpperCAmelCase_ : Tuple=12 , UpperCAmelCase_ : List[Any]=3_072 , UpperCAmelCase_ : Tuple="gelu" , UpperCAmelCase_ : Dict=0.0 , UpperCAmelCase_ : List[str]=0.0 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : Optional[Any]=1E-12 , UpperCAmelCase_ : int=224 , UpperCAmelCase_ : Tuple=16 , UpperCAmelCase_ : List[str]=3 , UpperCAmelCase_ : int=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Tuple=False , UpperCAmelCase_ : int=False , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Dict=[3, 5, 7, 11] , UpperCAmelCase_ : Tuple=[1, 2, 3, 6] , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[Any]=0.4 , UpperCAmelCase_ : Optional[Any]=256 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : int=False , UpperCAmelCase_ : Tuple=255 , **UpperCAmelCase_ : List[str] , ) ->Optional[Any]: """simple docstring""" super().__init__(**UpperCAmelCase_ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = use_mask_token snake_case_ = use_absolute_position_embeddings snake_case_ = use_relative_position_bias snake_case_ = use_shared_relative_position_bias snake_case_ = layer_scale_init_value snake_case_ = drop_path_rate snake_case_ = use_mean_pooling # decode head attributes (semantic segmentation) snake_case_ = out_indices snake_case_ = pool_scales # auxiliary head attributes (semantic segmentation) snake_case_ = use_auxiliary_head snake_case_ = auxiliary_loss_weight snake_case_ = auxiliary_channels snake_case_ = auxiliary_num_convs snake_case_ = auxiliary_concat_input snake_case_ = semantic_loss_ignore_index class __A (snake_case__): '''simple docstring''' __lowercase: List[Any] = version.parse("""1.11""") @property def lowerCAmelCase ( self : Dict ) ->Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def lowerCAmelCase ( self : Any ) ->float: """simple docstring""" return 1E-4
347
0
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : list[int] , snake_case__ : list[int] ): """simple docstring""" if not len(snake_case__ ) == len(snake_case__ ) == 3: raise ValueError("""Please enter a valid equation.""" ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError("""Both a & b of two equations can't be zero.""" ) # Extract the coefficients _snake_case , _snake_case , _snake_case : Optional[Any] = equationa _snake_case , _snake_case , _snake_case : Optional[Any] = equationa # Calculate the determinants of the matrices _snake_case : Any = aa * ba - aa * ba _snake_case : Optional[int] = ca * ba - ca * ba _snake_case : Tuple = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError("""Infinite solutions. (Consistent system)""" ) else: raise ValueError("""No solution. (Inconsistent system)""" ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: _snake_case : int = determinant_x / determinant _snake_case : List[str] = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
64
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : List[Any] = {'vocab_file': 'spiece.model'} __SCREAMING_SNAKE_CASE : int = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', } } # TODO(PVP) - this should be removed in Transformers v5 __SCREAMING_SNAKE_CASE : Dict = { 't5-small': 512, 't5-base': 512, 't5-large': 512, 't5-3b': 512, 't5-11b': 512, } __SCREAMING_SNAKE_CASE : Optional[int] = '▁' class __A (snake_case__): '''simple docstring''' __lowercase: Optional[int] = VOCAB_FILES_NAMES __lowercase: Any = PRETRAINED_VOCAB_FILES_MAP __lowercase: Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase: List[str] = ["""input_ids""", """attention_mask"""] def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any]="</s>" , UpperCAmelCase_ : Optional[Any]="<unk>" , UpperCAmelCase_ : Any="<pad>" , UpperCAmelCase_ : Tuple=100 , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , UpperCAmelCase_ : Optional[int]=True , **UpperCAmelCase_ : Dict , ) ->None: """simple docstring""" if extra_ids > 0 and additional_special_tokens is None: snake_case_ = [F"""<extra_id_{i}>""" for i in range(UpperCAmelCase_ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens snake_case_ = len(set(filter(lambda UpperCAmelCase_ : bool("""extra_id""" in str(UpperCAmelCase_ ) ) , UpperCAmelCase_ ) ) ) if extra_tokens != extra_ids: raise ValueError( F"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are""" """ provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids""" """ tokens""" ) if legacy: logger.warning_once( F"""You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to""" """ read the related pull request available at https://github.com/huggingface/transformers/pull/24565""" ) snake_case_ = legacy snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , extra_ids=UpperCAmelCase_ , additional_special_tokens=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , legacy=UpperCAmelCase_ , **UpperCAmelCase_ , ) snake_case_ = vocab_file snake_case_ = extra_ids snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) @staticmethod def lowerCAmelCase ( UpperCAmelCase_ : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any] ) ->Union[str, Any]: """simple docstring""" if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: snake_case_ = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( """This tokenizer was incorrectly instantiated with a model max length of""" F""" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this""" """ behavior is kept to avoid breaking backwards compatibility when padding/encoding with""" """ `truncation is True`.\n- Be aware that you SHOULD NOT rely on""" F""" {pretrained_model_name_or_path} automatically truncating your input to""" F""" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences""" F""" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with""" """ `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please""" """ instantiate this tokenizer with `model_max_length` set to your preferred value.""" , UpperCAmelCase_ , ) return max_model_length @property def lowerCAmelCase ( self : Optional[Any] ) ->Optional[Any]: """simple docstring""" return self.sp_model.get_piece_size() + self._extra_ids def lowerCAmelCase ( self : Any ) ->Optional[int]: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(UpperCAmelCase_ )) + [1] return ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" return list( set(filter(lambda UpperCAmelCase_ : bool(re.search(R"""<extra_id_\d+>""" , UpperCAmelCase_ ) ) is not None , self.additional_special_tokens ) ) ) def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" return [self._convert_token_to_id(UpperCAmelCase_ ) for token in self.get_sentinel_tokens()] def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[int] ) ->List[int]: """simple docstring""" if len(UpperCAmelCase_ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F"""This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated""" """ eos tokens being added.""" ) return token_ids else: return token_ids + [self.eos_token_id] def lowerCAmelCase ( self : str , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = self._add_eos_if_not_present(UpperCAmelCase_ ) if token_ids_a is None: return token_ids_a else: snake_case_ = self._add_eos_if_not_present(UpperCAmelCase_ ) return token_ids_a + token_ids_a def __getstate__( self : Optional[Any] ) ->Tuple: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Optional[Any] , UpperCAmelCase_ : List[Any] ) ->List[Any]: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : "TextInput" , **UpperCAmelCase_ : Tuple ) ->List[str]: """simple docstring""" if not self.legacy: snake_case_ = SPIECE_UNDERLINE + text.replace(UpperCAmelCase_ , """ """ ) return super().tokenize(UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Any ) ->Tuple: """simple docstring""" if not self.legacy: snake_case_ = text.startswith(UpperCAmelCase_ ) if is_first: snake_case_ = text[1:] snake_case_ = self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) if not self.legacy and not is_first and not text.startswith(""" """ ) and tokens[0].startswith(UpperCAmelCase_ ): snake_case_ = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" if token.startswith("""<extra_id_""" ): snake_case_ = re.match(R"""<extra_id_(\d+)>""" , UpperCAmelCase_ ) snake_case_ = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(UpperCAmelCase_ ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" if index < self.sp_model.get_piece_size(): snake_case_ = self.sp_model.IdToPiece(UpperCAmelCase_ ) else: snake_case_ = F"""<extra_id_{self.vocab_size - 1 - index}>""" return token def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[str] ) ->Optional[Any]: """simple docstring""" snake_case_ = [] snake_case_ = """""" snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase_ ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(UpperCAmelCase_ ) snake_case_ = False out_string += self.sp_model.decode(UpperCAmelCase_ ) return out_string.strip() def lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,)
347
0
import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class A ( UpperCAmelCase_ ): def __init__(self : List[str] , __UpperCAmelCase : int , __UpperCAmelCase : Dict=1_3 , __UpperCAmelCase : str=7 , __UpperCAmelCase : List[Any]=True , __UpperCAmelCase : List[Any]=True , __UpperCAmelCase : Optional[int]=False , __UpperCAmelCase : int=True , __UpperCAmelCase : Dict=9_9 , __UpperCAmelCase : List[Any]=3_2 , __UpperCAmelCase : str=5 , __UpperCAmelCase : List[str]=4 , __UpperCAmelCase : int=6_4 , __UpperCAmelCase : int="gelu" , __UpperCAmelCase : Dict=0.1 , __UpperCAmelCase : str=0.1 , __UpperCAmelCase : Optional[Any]=5_1_2 , __UpperCAmelCase : Optional[Any]=1_6 , __UpperCAmelCase : Any=2 , __UpperCAmelCase : List[Any]=0.02 , __UpperCAmelCase : str=3 , __UpperCAmelCase : Union[str, Any]=4 , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : List[Any]=2 , __UpperCAmelCase : List[str]=2 , __UpperCAmelCase : Optional[int]=2 , __UpperCAmelCase : Optional[Any]=2 , __UpperCAmelCase : int=4 , __UpperCAmelCase : Dict=1 , ) -> Any: """simple docstring""" UpperCAmelCase__ = parent UpperCAmelCase__ = batch_size UpperCAmelCase__ = seq_length UpperCAmelCase__ = is_training UpperCAmelCase__ = use_input_mask UpperCAmelCase__ = use_token_type_ids UpperCAmelCase__ = use_labels UpperCAmelCase__ = vocab_size UpperCAmelCase__ = hidden_size UpperCAmelCase__ = num_hidden_layers UpperCAmelCase__ = num_attention_heads UpperCAmelCase__ = intermediate_size UpperCAmelCase__ = hidden_act UpperCAmelCase__ = hidden_dropout_prob UpperCAmelCase__ = attention_probs_dropout_prob UpperCAmelCase__ = max_position_embeddings UpperCAmelCase__ = type_vocab_size UpperCAmelCase__ = type_sequence_label_size UpperCAmelCase__ = initializer_range UpperCAmelCase__ = num_labels UpperCAmelCase__ = num_choices UpperCAmelCase__ = scope UpperCAmelCase__ = q_groups UpperCAmelCase__ = k_groups UpperCAmelCase__ = v_groups UpperCAmelCase__ = post_attention_groups UpperCAmelCase__ = intermediate_groups UpperCAmelCase__ = output_groups def lowercase_ (self : Union[str, Any] ) -> List[str]: """simple docstring""" UpperCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase__ = None if self.use_input_mask: UpperCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None if self.use_labels: UpperCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase__ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase_ (self : Optional[int] ) -> Union[str, Any]: """simple docstring""" return SqueezeBertConfig( embedding_size=self.hidden_size , 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 , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def lowercase_ (self : Dict , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Any , __UpperCAmelCase : List[str] ) -> int: """simple docstring""" UpperCAmelCase__ = SqueezeBertModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() UpperCAmelCase__ = model(__UpperCAmelCase , __UpperCAmelCase ) UpperCAmelCase__ = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowercase_ (self : Dict , __UpperCAmelCase : str , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Optional[int] ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = SqueezeBertForMaskedLM(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() UpperCAmelCase__ = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowercase_ (self : Tuple , __UpperCAmelCase : int , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : int , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Union[str, Any] ) -> int: """simple docstring""" UpperCAmelCase__ = SqueezeBertForQuestionAnswering(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() UpperCAmelCase__ = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , start_positions=__UpperCAmelCase , end_positions=__UpperCAmelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowercase_ (self : List[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = self.num_labels UpperCAmelCase__ = SqueezeBertForSequenceClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() UpperCAmelCase__ = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowercase_ (self : Dict , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : int , __UpperCAmelCase : str , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Union[str, Any] ) -> int: """simple docstring""" UpperCAmelCase__ = self.num_labels UpperCAmelCase__ = SqueezeBertForTokenClassification(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() UpperCAmelCase__ = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowercase_ (self : List[str] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Tuple , __UpperCAmelCase : str , __UpperCAmelCase : Any ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = self.num_choices UpperCAmelCase__ = SqueezeBertForMultipleChoice(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() UpperCAmelCase__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase__ = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowercase_ (self : Dict ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = self.prepare_config_and_inputs() ((UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__)) = config_and_inputs UpperCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class A ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): __UpperCAmelCase : Optional[int] = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCAmelCase : Any = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : str = False __UpperCAmelCase : Tuple = True __UpperCAmelCase : Any = False def lowercase_ (self : Optional[Any] ) -> List[str]: """simple docstring""" UpperCAmelCase__ = SqueezeBertModelTester(self ) UpperCAmelCase__ = ConfigTester(self , config_class=__UpperCAmelCase , dim=3_7 ) def lowercase_ (self : Any ) -> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() def lowercase_ (self : List[str] ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*__UpperCAmelCase ) def lowercase_ (self : Any ) -> Dict: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*__UpperCAmelCase ) def lowercase_ (self : str ) -> Any: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*__UpperCAmelCase ) def lowercase_ (self : Dict ) -> Dict: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*__UpperCAmelCase ) def lowercase_ (self : Any ) -> int: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*__UpperCAmelCase ) def lowercase_ (self : Dict ) -> Any: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*__UpperCAmelCase ) @slow def lowercase_ (self : List[str] ) -> List[Any]: """simple docstring""" for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase__ = SqueezeBertModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) @require_sentencepiece @require_tokenizers @require_torch class A ( unittest.TestCase ): @slow def lowercase_ (self : int ) -> int: """simple docstring""" UpperCAmelCase__ = SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-mnli" ) UpperCAmelCase__ = torch.tensor([[1, 2_9_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 1_3, 1_5_8_8, 2]] ) UpperCAmelCase__ = model(__UpperCAmelCase )[0] UpperCAmelCase__ = torch.Size((1, 3) ) self.assertEqual(output.shape , __UpperCAmelCase ) UpperCAmelCase__ = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-4 ) )
65
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE = 1_000_000 ) -> int: snake_case_ = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , _SCREAMING_SNAKE_CASE ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
347
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { "uclanlp/visualbert-vqa": "https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json", "uclanlp/visualbert-vqa-pre": "https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json", "uclanlp/visualbert-vqa-coco-pre": ( "https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json" ), "uclanlp/visualbert-vcr": "https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json", "uclanlp/visualbert-vcr-pre": "https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json", "uclanlp/visualbert-vcr-coco-pre": ( "https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json" ), "uclanlp/visualbert-nlvr2": "https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json", "uclanlp/visualbert-nlvr2-pre": "https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json", "uclanlp/visualbert-nlvr2-coco-pre": ( "https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json" ) # See all VisualBERT models at https://huggingface.co/models?filter=visual_bert } class lowerCamelCase ( _lowerCAmelCase ): '''simple docstring''' _A : int = """visual_bert""" def __init__( self: List[Any] , snake_case: Union[str, Any]=30_522 , snake_case: Dict=768 , snake_case: Any=512 , snake_case: Any=12 , snake_case: Any=12 , snake_case: List[Any]=3_072 , snake_case: int="gelu" , snake_case: int=0.1 , snake_case: str=0.1 , snake_case: str=512 , snake_case: Dict=2 , snake_case: int=0.0_2 , snake_case: Optional[int]=1E-12 , snake_case: str=False , snake_case: List[Any]=True , snake_case: Union[str, Any]=1 , snake_case: Optional[Any]=0 , snake_case: Tuple=2 , **snake_case: Union[str, Any] , ) -> Union[str, Any]: super().__init__(pad_token_id=snake_case , bos_token_id=snake_case , eos_token_id=snake_case , **snake_case ) snake_case_ :Optional[int] = vocab_size snake_case_ :Optional[int] = max_position_embeddings snake_case_ :Union[str, Any] = hidden_size snake_case_ :Optional[int] = visual_embedding_dim snake_case_ :int = num_hidden_layers snake_case_ :Optional[int] = num_attention_heads snake_case_ :Optional[int] = intermediate_size snake_case_ :str = hidden_act snake_case_ :Optional[Any] = hidden_dropout_prob snake_case_ :str = attention_probs_dropout_prob snake_case_ :List[Any] = initializer_range snake_case_ :Optional[Any] = type_vocab_size snake_case_ :Tuple = layer_norm_eps snake_case_ :Optional[Any] = bypass_transformer snake_case_ :List[str] = special_visual_initialize
66
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: print(f"""Vertex\tShortest Distance from vertex {src}""" ) for i, d in enumerate(_SCREAMING_SNAKE_CASE ): print(f"""{i}\t\t{d}""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: for j in range(_SCREAMING_SNAKE_CASE ): snake_case_ , snake_case_ , snake_case_ = (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 _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[float]: snake_case_ = [float("""inf""" )] * vertex_count snake_case_ = 0.0 for _ in range(vertex_count - 1 ): for j in range(_SCREAMING_SNAKE_CASE ): snake_case_ , snake_case_ , snake_case_ = (graph[j][k] for k in ["""src""", """dst""", """weight"""]) if distance[u] != float("""inf""" ) and distance[u] + w < distance[v]: snake_case_ = distance[u] + w snake_case_ = check_negative_cycle(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if negative_cycle_exists: raise Exception("""Negative cycle found""" ) return distance if __name__ == "__main__": import doctest doctest.testmod() __SCREAMING_SNAKE_CASE : int = int(input('Enter number of vertices: ').strip()) __SCREAMING_SNAKE_CASE : Dict = 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 : List[str] = ( int(x) for x in input('Enter source, destination, weight: ').strip().split(' ') ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'src': src, 'dst': dest, 'weight': weight} __SCREAMING_SNAKE_CASE : Union[str, Any] = int(input('\nEnter shortest path source:').strip()) __SCREAMING_SNAKE_CASE : str = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
347
0
'''simple docstring''' import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( ) -> str: __lowerCamelCase = 10 __lowerCamelCase = datasets.Features( { '''tokens''': datasets.Sequence(datasets.Value('''string''' ) ), '''labels''': datasets.Sequence(datasets.ClassLabel(names=['''negative''', '''positive'''] ) ), '''answers''': datasets.Sequence( { '''text''': datasets.Value('''string''' ), '''answer_start''': datasets.Value('''int32''' ), } ), '''id''': datasets.Value('''int64''' ), } ) __lowerCamelCase = datasets.Dataset.from_dict( { '''tokens''': [['''foo'''] * 5] * n, '''labels''': [[1] * 5] * n, '''answers''': [{'''answer_start''': [97], '''text''': ['''1976''']}] * 10, '''id''': list(range(UpperCamelCase__ ) ), } , features=UpperCamelCase__ , ) return dataset @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]: __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''file.arrow''' ) dataset.map(cache_file_name=UpperCamelCase__ ) return filename # FILE_CONTENT + files __UpperCAmelCase ="\\n Text data.\n Second line of data." @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> Union[str, Any]: __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''file.txt''' __lowerCamelCase = FILE_CONTENT with open(UpperCamelCase__ , '''w''' ) as f: f.write(UpperCamelCase__ ) return filename @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> Optional[Any]: import bza __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''file.txt.bz2''' __lowerCamelCase = bytes(UpperCamelCase__ , '''utf-8''' ) with bza.open(UpperCamelCase__ , '''wb''' ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> Dict: import gzip __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''file.txt.gz''' ) __lowerCamelCase = bytes(UpperCamelCase__ , '''utf-8''' ) with gzip.open(UpperCamelCase__ , '''wb''' ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> str: if datasets.config.LZ4_AVAILABLE: import lza.frame __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''file.txt.lz4''' __lowerCamelCase = bytes(UpperCamelCase__ , '''utf-8''' ) with lza.frame.open(UpperCamelCase__ , '''wb''' ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> int: if datasets.config.PY7ZR_AVAILABLE: import pyazr __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''file.txt.7z''' with pyazr.SevenZipFile(UpperCamelCase__ , '''w''' ) as archive: archive.write(UpperCamelCase__ , arcname=os.path.basename(UpperCamelCase__ ) ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]: import tarfile __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''file.txt.tar''' with tarfile.TarFile(UpperCamelCase__ , '''w''' ) as f: f.add(UpperCamelCase__ , arcname=os.path.basename(UpperCamelCase__ ) ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> str: import lzma __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''file.txt.xz''' __lowerCamelCase = bytes(UpperCamelCase__ , '''utf-8''' ) with lzma.open(UpperCamelCase__ , '''wb''' ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Optional[Any]: import zipfile __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''file.txt.zip''' with zipfile.ZipFile(UpperCamelCase__ , '''w''' ) as f: f.write(UpperCamelCase__ , arcname=os.path.basename(UpperCamelCase__ ) ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> List[Any]: if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''file.txt.zst''' __lowerCamelCase = bytes(UpperCamelCase__ , '''utf-8''' ) with zstd.open(UpperCamelCase__ , '''wb''' ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> Tuple: __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''file.xml''' __lowerCamelCase = textwrap.dedent( '''\ <?xml version="1.0" encoding="UTF-8" ?> <tmx version="1.4"> <header segtype="sentence" srclang="ca" /> <body> <tu> <tuv xml:lang="ca"><seg>Contingut 1</seg></tuv> <tuv xml:lang="en"><seg>Content 1</seg></tuv> </tu> <tu> <tuv xml:lang="ca"><seg>Contingut 2</seg></tuv> <tuv xml:lang="en"><seg>Content 2</seg></tuv> </tu> <tu> <tuv xml:lang="ca"><seg>Contingut 3</seg></tuv> <tuv xml:lang="en"><seg>Content 3</seg></tuv> </tu> <tu> <tuv xml:lang="ca"><seg>Contingut 4</seg></tuv> <tuv xml:lang="en"><seg>Content 4</seg></tuv> </tu> <tu> <tuv xml:lang="ca"><seg>Contingut 5</seg></tuv> <tuv xml:lang="en"><seg>Content 5</seg></tuv> </tu> </body> </tmx>''' ) with open(UpperCamelCase__ , '''w''' ) as f: f.write(UpperCamelCase__ ) return filename __UpperCAmelCase =[ {"col_1": "0", "col_2": 0, "col_3": 0.0}, {"col_1": "1", "col_2": 1, "col_3": 1.0}, {"col_1": "2", "col_2": 2, "col_3": 2.0}, {"col_1": "3", "col_2": 3, "col_3": 3.0}, ] __UpperCAmelCase =[ {"col_1": "4", "col_2": 4, "col_3": 4.0}, {"col_1": "5", "col_2": 5, "col_3": 5.0}, ] __UpperCAmelCase ={ "col_1": ["0", "1", "2", "3"], "col_2": [0, 1, 2, 3], "col_3": [0.0, 1.0, 2.0, 3.0], } __UpperCAmelCase =[ {"col_3": 0.0, "col_1": "0", "col_2": 0}, {"col_3": 1.0, "col_1": "1", "col_2": 1}, ] __UpperCAmelCase =[ {"col_1": "s0", "col_2": 0, "col_3": 0.0}, {"col_1": "s1", "col_2": 1, "col_3": 1.0}, {"col_1": "s2", "col_2": 2, "col_3": 2.0}, {"col_1": "s3", "col_2": 3, "col_3": 3.0}, ] @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( ) -> Any: return DATA_DICT_OF_LISTS @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> List[str]: __lowerCamelCase = datasets.Dataset.from_dict(UpperCamelCase__ ) __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.arrow''' ) dataset.map(cache_file_name=UpperCamelCase__ ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> int: __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.sqlite''' ) with contextlib.closing(sqlitea.connect(UpperCamelCase__ ) ) as con: __lowerCamelCase = con.cursor() cur.execute('''CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)''' ) for item in DATA: cur.execute('''INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)''' , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> Any: __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.csv''' ) with open(UpperCamelCase__ , '''w''' , newline='''''' ) as f: __lowerCamelCase = csv.DictWriter(UpperCamelCase__ , fieldnames=['''col_1''', '''col_2''', '''col_3'''] ) writer.writeheader() for item in DATA: writer.writerow(UpperCamelCase__ ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> Dict: __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset2.csv''' ) with open(UpperCamelCase__ , '''w''' , newline='''''' ) as f: __lowerCamelCase = csv.DictWriter(UpperCamelCase__ , fieldnames=['''col_1''', '''col_2''', '''col_3'''] ) writer.writeheader() for item in DATA: writer.writerow(UpperCamelCase__ ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]: import bza __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''dataset.csv.bz2''' with open(UpperCamelCase__ , '''rb''' ) as f: __lowerCamelCase = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(UpperCamelCase__ , '''wb''' ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> int: __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''dataset.csv.zip''' with zipfile.ZipFile(UpperCamelCase__ , '''w''' ) as f: f.write(UpperCamelCase__ , arcname=os.path.basename(UpperCamelCase__ ) ) f.write(UpperCamelCase__ , arcname=os.path.basename(UpperCamelCase__ ) ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> List[str]: __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''dataset.csv.zip''' with zipfile.ZipFile(UpperCamelCase__ , '''w''' ) as f: f.write(UpperCamelCase__ , arcname=os.path.basename(csv_path.replace('''.csv''' , '''.CSV''' ) ) ) f.write(UpperCamelCase__ , arcname=os.path.basename(csva_path.replace('''.csv''' , '''.CSV''' ) ) ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Any: __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''dataset_with_dir.csv.zip''' with zipfile.ZipFile(UpperCamelCase__ , '''w''' ) as f: f.write(UpperCamelCase__ , arcname=os.path.join('''main_dir''' , os.path.basename(UpperCamelCase__ ) ) ) f.write(UpperCamelCase__ , arcname=os.path.join('''main_dir''' , os.path.basename(UpperCamelCase__ ) ) ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> Union[str, Any]: __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.parquet''' ) __lowerCamelCase = pa.schema( { '''col_1''': pa.string(), '''col_2''': pa.intaa(), '''col_3''': pa.floataa(), } ) with open(UpperCamelCase__ , '''wb''' ) as f: __lowerCamelCase = pq.ParquetWriter(UpperCamelCase__ , schema=UpperCamelCase__ ) __lowerCamelCase = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(UpperCamelCase__ ) )] for k in DATA[0]} , schema=UpperCamelCase__ ) writer.write_table(UpperCamelCase__ ) writer.close() return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> Union[str, Any]: __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.json''' ) __lowerCamelCase = {'''data''': DATA} with open(UpperCamelCase__ , '''w''' ) as f: json.dump(UpperCamelCase__ , UpperCamelCase__ ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> Tuple: __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.json''' ) __lowerCamelCase = {'''data''': DATA_DICT_OF_LISTS} with open(UpperCamelCase__ , '''w''' ) as f: json.dump(UpperCamelCase__ , UpperCamelCase__ ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> Dict: __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.jsonl''' ) with open(UpperCamelCase__ , '''w''' ) as f: for item in DATA: f.write(json.dumps(UpperCamelCase__ ) + '''\n''' ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> str: __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset2.jsonl''' ) with open(UpperCamelCase__ , '''w''' ) as f: for item in DATA: f.write(json.dumps(UpperCamelCase__ ) + '''\n''' ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> Dict: __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset_312.jsonl''' ) with open(UpperCamelCase__ , '''w''' ) as f: for item in DATA_312: f.write(json.dumps(UpperCamelCase__ ) + '''\n''' ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> Optional[int]: __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset-str.jsonl''' ) with open(UpperCamelCase__ , '''w''' ) as f: for item in DATA_STR: f.write(json.dumps(UpperCamelCase__ ) + '''\n''' ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> str: import gzip __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.txt.gz''' ) with open(UpperCamelCase__ , '''rb''' ) as orig_file: with gzip.open(UpperCamelCase__ , '''wb''' ) as zipped_file: zipped_file.writelines(UpperCamelCase__ ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> int: import gzip __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.jsonl.gz''' ) with open(UpperCamelCase__ , '''rb''' ) as orig_file: with gzip.open(UpperCamelCase__ , '''wb''' ) as zipped_file: zipped_file.writelines(UpperCamelCase__ ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> List[str]: __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''dataset.jsonl.zip''' with zipfile.ZipFile(UpperCamelCase__ , '''w''' ) as f: f.write(UpperCamelCase__ , arcname=os.path.basename(UpperCamelCase__ ) ) f.write(UpperCamelCase__ , arcname=os.path.basename(UpperCamelCase__ ) ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]: __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''dataset_nested.jsonl.zip''' with zipfile.ZipFile(UpperCamelCase__ , '''w''' ) as f: f.write(UpperCamelCase__ , arcname=os.path.join('''nested''' , os.path.basename(UpperCamelCase__ ) ) ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> str: __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''dataset_with_dir.jsonl.zip''' with zipfile.ZipFile(UpperCamelCase__ , '''w''' ) as f: f.write(UpperCamelCase__ , arcname=os.path.join('''main_dir''' , os.path.basename(UpperCamelCase__ ) ) ) f.write(UpperCamelCase__ , arcname=os.path.join('''main_dir''' , os.path.basename(UpperCamelCase__ ) ) ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Any: __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''dataset.jsonl.tar''' with tarfile.TarFile(UpperCamelCase__ , '''w''' ) as f: f.add(UpperCamelCase__ , arcname=os.path.basename(UpperCamelCase__ ) ) f.add(UpperCamelCase__ , arcname=os.path.basename(UpperCamelCase__ ) ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Optional[Any]: __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''dataset_nested.jsonl.tar''' with tarfile.TarFile(UpperCamelCase__ , '''w''' ) as f: f.add(UpperCamelCase__ , arcname=os.path.join('''nested''' , os.path.basename(UpperCamelCase__ ) ) ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> Any: __lowerCamelCase = ['''0''', '''1''', '''2''', '''3'''] __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.txt''' ) with open(UpperCamelCase__ , '''w''' ) as f: for item in data: f.write(item + '''\n''' ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> Optional[Any]: __lowerCamelCase = ['''0''', '''1''', '''2''', '''3'''] __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset2.txt''' ) with open(UpperCamelCase__ , '''w''' ) as f: for item in data: f.write(item + '''\n''' ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> List[Any]: __lowerCamelCase = ['''0''', '''1''', '''2''', '''3'''] __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''dataset.abc''' with open(UpperCamelCase__ , '''w''' ) as f: for item in data: f.write(item + '''\n''' ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]: __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''dataset.text.zip''' with zipfile.ZipFile(UpperCamelCase__ , '''w''' ) as f: f.write(UpperCamelCase__ , arcname=os.path.basename(UpperCamelCase__ ) ) f.write(UpperCamelCase__ , arcname=os.path.basename(UpperCamelCase__ ) ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> str: __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''dataset_with_dir.text.zip''' with zipfile.ZipFile(UpperCamelCase__ , '''w''' ) as f: f.write(UpperCamelCase__ , arcname=os.path.join('''main_dir''' , os.path.basename(UpperCamelCase__ ) ) ) f.write(UpperCamelCase__ , arcname=os.path.join('''main_dir''' , os.path.basename(UpperCamelCase__ ) ) ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]: __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''dataset.ext.zip''' with zipfile.ZipFile(UpperCamelCase__ , '''w''' ) as f: f.write(UpperCamelCase__ , arcname=os.path.basename('''unsupported.ext''' ) ) f.write(UpperCamelCase__ , arcname=os.path.basename('''unsupported_2.ext''' ) ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> List[str]: __lowerCamelCase = '''\n'''.join(['''First''', '''Second\u2029with Unicode new line''', '''Third'''] ) __lowerCamelCase = str(tmp_path_factory.mktemp('''data''' ) / '''dataset_with_unicode_new_lines.txt''' ) with open(UpperCamelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( ) -> Optional[Any]: return os.path.join('''tests''' , '''features''' , '''data''' , '''test_image_rgb.jpg''' ) @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( ) -> Optional[Any]: return os.path.join('''tests''' , '''features''' , '''data''' , '''test_audio_44100.wav''' ) @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Optional[Any]: __lowerCamelCase = tmp_path_factory.mktemp('''data''' ) / '''dataset.img.zip''' with zipfile.ZipFile(UpperCamelCase__ , '''w''' ) as f: f.write(UpperCamelCase__ , arcname=os.path.basename(UpperCamelCase__ ) ) f.write(UpperCamelCase__ , arcname=os.path.basename(UpperCamelCase__ ).replace('''.jpg''' , '''2.jpg''' ) ) return path @pytest.fixture(scope='''session''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> int: __lowerCamelCase = tmp_path_factory.mktemp('''data_dir''' ) (data_dir / "subdir").mkdir() with open(data_dir / '''subdir''' / '''train.txt''' , '''w''' ) as f: f.write('''foo\n''' * 10 ) with open(data_dir / '''subdir''' / '''test.txt''' , '''w''' ) as f: f.write('''bar\n''' * 10 ) # hidden file with open(data_dir / '''subdir''' / '''.test.txt''' , '''w''' ) as f: f.write('''bar\n''' * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / '''.subdir''' / '''train.txt''' , '''w''' ) as f: f.write('''foo\n''' * 10 ) with open(data_dir / '''.subdir''' / '''test.txt''' , '''w''' ) as f: f.write('''bar\n''' * 10 ) return data_dir
67
"""simple docstring""" import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) __SCREAMING_SNAKE_CASE : List[str] = logging.getLogger(__name__) __SCREAMING_SNAKE_CASE : str = tf.data.AUTOTUNE def _a ( ) -> List[str]: snake_case_ = argparse.ArgumentParser(description="""Train a masked language model on TPU.""" ) parser.add_argument( """--pretrained_model_config""" , type=_SCREAMING_SNAKE_CASE , default="""roberta-base""" , help="""The model config to use. Note that we don't copy the model's weights, only the config!""" , ) parser.add_argument( """--tokenizer""" , type=_SCREAMING_SNAKE_CASE , default="""unigram-tokenizer-wikitext""" , help="""The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model's vocab size.""" , ) parser.add_argument( """--per_replica_batch_size""" , type=_SCREAMING_SNAKE_CASE , default=8 , help="""Batch size per TPU core.""" , ) parser.add_argument( """--no_tpu""" , action="""store_true""" , help="""If set, run on CPU and don't try to initialize a TPU. Useful for debugging on non-TPU instances.""" , ) parser.add_argument( """--tpu_name""" , type=_SCREAMING_SNAKE_CASE , help="""Name of TPU resource to initialize. Should be blank on Colab, and 'local' on TPU VMs.""" , default="""local""" , ) parser.add_argument( """--tpu_zone""" , type=_SCREAMING_SNAKE_CASE , help="""Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes.""" , ) parser.add_argument( """--gcp_project""" , type=_SCREAMING_SNAKE_CASE , help="""Google cloud project name. Only used for non-Colab TPU nodes.""" ) parser.add_argument( """--bfloat16""" , action="""store_true""" , help="""Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU.""" , ) parser.add_argument( """--train_dataset""" , type=_SCREAMING_SNAKE_CASE , help="""Path to training dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--shuffle_buffer_size""" , type=_SCREAMING_SNAKE_CASE , default=2**18 , help="""Size of the shuffle buffer (in samples)""" , ) parser.add_argument( """--eval_dataset""" , type=_SCREAMING_SNAKE_CASE , help="""Path to evaluation dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--num_epochs""" , type=_SCREAMING_SNAKE_CASE , default=1 , help="""Number of epochs to train for.""" , ) parser.add_argument( """--learning_rate""" , type=_SCREAMING_SNAKE_CASE , default=1E-4 , help="""Learning rate to use for training.""" , ) parser.add_argument( """--weight_decay_rate""" , type=_SCREAMING_SNAKE_CASE , default=1E-3 , help="""Weight decay rate to use for training.""" , ) parser.add_argument( """--max_length""" , type=_SCREAMING_SNAKE_CASE , default=512 , help="""Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py""" , ) parser.add_argument( """--mlm_probability""" , type=_SCREAMING_SNAKE_CASE , default=0.15 , help="""Fraction of tokens to mask during training.""" , ) parser.add_argument("""--output_dir""" , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help="""Path to save model checkpoints to.""" ) parser.add_argument("""--hub_model_id""" , type=_SCREAMING_SNAKE_CASE , help="""Model ID to upload to on the Hugging Face Hub.""" ) snake_case_ = parser.parse_args() return args def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: try: if args.tpu_name: snake_case_ = tf.distribute.cluster_resolver.TPUClusterResolver( args.tpu_name , zone=args.tpu_zone , project=args.gcp_project ) else: snake_case_ = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: raise RuntimeError( """Couldn't connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or """ """--gcp_project. When running on a TPU VM, use --tpu_name local.""" ) tf.config.experimental_connect_to_cluster(_SCREAMING_SNAKE_CASE ) tf.tpu.experimental.initialize_tpu_system(_SCREAMING_SNAKE_CASE ) return tpu def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = 0 for file in file_list: snake_case_ = file.split("""/""" )[-1] snake_case_ = re.search(r"""-\d+-(\d+)\.tfrecord""" , _SCREAMING_SNAKE_CASE ).group(1 ) snake_case_ = int(_SCREAMING_SNAKE_CASE ) num_samples += sample_count return num_samples def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Union[str, Any]: snake_case_ = count_samples(_SCREAMING_SNAKE_CASE ) snake_case_ = tf.data.Dataset.from_tensor_slices(_SCREAMING_SNAKE_CASE ) if shuffle: snake_case_ = dataset.shuffle(len(_SCREAMING_SNAKE_CASE ) ) snake_case_ = tf.data.TFRecordDataset(_SCREAMING_SNAKE_CASE , num_parallel_reads=_SCREAMING_SNAKE_CASE ) # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here snake_case_ = dataset.apply(tf.data.experimental.assert_cardinality(_SCREAMING_SNAKE_CASE ) ) snake_case_ = dataset.map(_SCREAMING_SNAKE_CASE , num_parallel_calls=_SCREAMING_SNAKE_CASE ) if shuffle: assert shuffle_buffer_size is not None snake_case_ = dataset.shuffle(args.shuffle_buffer_size ) snake_case_ = dataset.batch(_SCREAMING_SNAKE_CASE , drop_remainder=_SCREAMING_SNAKE_CASE ) snake_case_ = dataset.map(_SCREAMING_SNAKE_CASE , num_parallel_calls=_SCREAMING_SNAKE_CASE ) snake_case_ = dataset.prefetch(_SCREAMING_SNAKE_CASE ) return dataset def _a ( _SCREAMING_SNAKE_CASE ) -> List[Any]: if not args.no_tpu: snake_case_ = initialize_tpu(_SCREAMING_SNAKE_CASE ) snake_case_ = tf.distribute.TPUStrategy(_SCREAMING_SNAKE_CASE ) else: snake_case_ = tf.distribute.OneDeviceStrategy(device="""/gpu:0""" ) if args.bfloataa: tf.keras.mixed_precision.set_global_policy("""mixed_bfloat16""" ) snake_case_ = AutoTokenizer.from_pretrained(args.tokenizer ) snake_case_ = AutoConfig.from_pretrained(args.pretrained_model_config ) snake_case_ = tokenizer.vocab_size snake_case_ = tf.io.gfile.glob(os.path.join(args.train_dataset , """*.tfrecord""" ) ) if not training_records: raise ValueError(f"""No .tfrecord files found in {args.train_dataset}.""" ) snake_case_ = tf.io.gfile.glob(os.path.join(args.eval_dataset , """*.tfrecord""" ) ) if not eval_records: raise ValueError(f"""No .tfrecord files found in {args.eval_dataset}.""" ) snake_case_ = count_samples(_SCREAMING_SNAKE_CASE ) snake_case_ = num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync) snake_case_ = steps_per_epoch * args.num_epochs with strategy.scope(): snake_case_ = TFAutoModelForMaskedLM.from_config(_SCREAMING_SNAKE_CASE ) model(model.dummy_inputs ) # Pass some dummy inputs through the model to ensure all the weights are built snake_case_ , snake_case_ = create_optimizer( num_train_steps=_SCREAMING_SNAKE_CASE , num_warmup_steps=total_train_steps // 20 , init_lr=args.learning_rate , weight_decay_rate=args.weight_decay_rate , ) # Transformers models compute the right loss for their task by default when labels are passed, and will # use this for training unless you specify your own loss function in compile(). model.compile(optimizer=_SCREAMING_SNAKE_CASE , metrics=["""accuracy"""] ) def decode_fn(_SCREAMING_SNAKE_CASE ): snake_case_ = { """input_ids""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), """attention_mask""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), } return tf.io.parse_single_example(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can # use their methods in our data pipeline. snake_case_ = DataCollatorForLanguageModeling( tokenizer=_SCREAMING_SNAKE_CASE , mlm_probability=args.mlm_probability , mlm=_SCREAMING_SNAKE_CASE , return_tensors="""tf""" ) def mask_with_collator(_SCREAMING_SNAKE_CASE ): # TF really needs an isin() function snake_case_ = ( ~tf.cast(batch["""attention_mask"""] , tf.bool ) | (batch["""input_ids"""] == tokenizer.cls_token_id) | (batch["""input_ids"""] == tokenizer.sep_token_id) ) snake_case_ , snake_case_ = data_collator.tf_mask_tokens( batch["""input_ids"""] , vocab_size=len(_SCREAMING_SNAKE_CASE ) , mask_token_id=tokenizer.mask_token_id , special_tokens_mask=_SCREAMING_SNAKE_CASE , ) return batch snake_case_ = args.per_replica_batch_size * strategy.num_replicas_in_sync snake_case_ = prepare_dataset( _SCREAMING_SNAKE_CASE , decode_fn=_SCREAMING_SNAKE_CASE , mask_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , shuffle=_SCREAMING_SNAKE_CASE , shuffle_buffer_size=args.shuffle_buffer_size , ) snake_case_ = prepare_dataset( _SCREAMING_SNAKE_CASE , decode_fn=_SCREAMING_SNAKE_CASE , mask_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , shuffle=_SCREAMING_SNAKE_CASE , ) snake_case_ = [] if args.hub_model_id: callbacks.append( PushToHubCallback(output_dir=args.output_dir , hub_model_id=args.hub_model_id , tokenizer=_SCREAMING_SNAKE_CASE ) ) model.fit( _SCREAMING_SNAKE_CASE , validation_data=_SCREAMING_SNAKE_CASE , epochs=args.num_epochs , callbacks=_SCREAMING_SNAKE_CASE , ) model.save_pretrained(args.output_dir ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = parse_args() main(args)
347
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ = { """configuration_instructblip""": [ """INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """InstructBlipConfig""", """InstructBlipQFormerConfig""", """InstructBlipVisionConfig""", ], """processing_instructblip""": ["""InstructBlipProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """InstructBlipQFormerModel""", """InstructBlipPreTrainedModel""", """InstructBlipForConditionalGeneration""", """InstructBlipVisionModel""", ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
68
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float: if density <= 0: raise ValueError("""Impossible fluid density""" ) if bulk_modulus <= 0: raise ValueError("""Impossible bulk modulus""" ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
347
0
"""simple docstring""" import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process __UpperCamelCase = logging.getLogger(__name__) __UpperCamelCase = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) __UpperCamelCase = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class UpperCamelCase : SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={ "help": ( "The model checkpoint for weights initialization.Don't set if you want to train a model from scratch." ) } , ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(lowerCAmelCase__ )} , ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={ "help": ( "Override some existing default config settings when a model is trained from scratch. Example: " "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index" ) } , ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) SCREAMING_SNAKE_CASE_ = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) def a_ ( self) -> Tuple: if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( '--config_overrides can\'t be used in combination with --config_name or --model_name_or_path') @dataclass class UpperCamelCase : SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={"help": "The name of the dataset to use (via the datasets library)."} ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) SCREAMING_SNAKE_CASE_ = field(default=lowerCAmelCase__ , metadata={"help": "The input training data file (a text file)."} ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={"help": "An optional input train ref data file for whole word masking in Chinese."} , ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."} , ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) SCREAMING_SNAKE_CASE_ = field( default=5 , metadata={ "help": "The percentage of the train set used as validation set in case there's no validation split" } , ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated. Default to the max input length of the model." ) } , ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={"help": "The number of processes to use for the preprocessing."} , ) SCREAMING_SNAKE_CASE_ = field( default=0.15 , metadata={"help": "Ratio of tokens to mask for masked language modeling loss"} ) SCREAMING_SNAKE_CASE_ = field( default=lowerCAmelCase__ , metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) } , ) def a_ ( self) -> Optional[Any]: if self.train_file is not None: snake_case_ = self.train_file.split('.')[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: snake_case_ = self.validation_file.split('.')[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase ) -> str: with open(UpperCAmelCase , 'r' , encoding='utf-8' ) as f: snake_case_ = [json.loads(UpperCAmelCase ) for line in f.read().splitlines() if (len(UpperCAmelCase ) > 0 and not line.isspace())] assert len(UpperCAmelCase ) == len(UpperCAmelCase ) snake_case_ = {c: dataset[c] for c in dataset.column_names} snake_case_ = refs return Dataset.from_dict(UpperCAmelCase ) def UpperCAmelCase ( ) -> Optional[Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. snake_case_ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. snake_case_ , snake_case_ , snake_case_ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case_ , snake_case_ , snake_case_ = parser.parse_args_into_dataclasses() # Detecting last checkpoint. snake_case_ = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: snake_case_ = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'Output directory ({training_args.output_dir}) already exists and is not empty. ' 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None: logger.info( f'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + f'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' , UpperCAmelCase ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. snake_case_ = load_dataset(data_args.dataset_name , data_args.dataset_config_name ) if "validation" not in datasets.keys(): snake_case_ = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f'train[:{data_args.validation_split_percentage}%]' , ) snake_case_ = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f'train[{data_args.validation_split_percentage}%:]' , ) else: snake_case_ = {} if data_args.train_file is not None: snake_case_ = data_args.train_file if data_args.validation_file is not None: snake_case_ = data_args.validation_file snake_case_ = data_args.train_file.split('.' )[-1] if extension == "txt": snake_case_ = 'text' snake_case_ = load_dataset(UpperCAmelCase , data_files=UpperCAmelCase ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case_ = { 'cache_dir': model_args.cache_dir, 'revision': model_args.model_revision, 'use_auth_token': True if model_args.use_auth_token else None, } if model_args.config_name: snake_case_ = AutoConfig.from_pretrained(model_args.config_name , **UpperCAmelCase ) elif model_args.model_name_or_path: snake_case_ = AutoConfig.from_pretrained(model_args.model_name_or_path , **UpperCAmelCase ) else: snake_case_ = CONFIG_MAPPING[model_args.model_type]() logger.warning('You are instantiating a new config instance from scratch.' ) if model_args.config_overrides is not None: logger.info(f'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(f'New config: {config}' ) snake_case_ = { 'cache_dir': model_args.cache_dir, 'use_fast': model_args.use_fast_tokenizer, 'revision': model_args.model_revision, 'use_auth_token': True if model_args.use_auth_token else None, } if model_args.tokenizer_name: snake_case_ = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **UpperCAmelCase ) elif model_args.model_name_or_path: snake_case_ = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **UpperCAmelCase ) else: raise ValueError( 'You are instantiating a new tokenizer from scratch. This is not supported by this script.' 'You can do it from another script, save it, and load it from here, using --tokenizer_name.' ) if model_args.model_name_or_path: snake_case_ = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=UpperCAmelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('Training new model from scratch' ) snake_case_ = AutoModelForMaskedLM.from_config(UpperCAmelCase ) model.resize_token_embeddings(len(UpperCAmelCase ) ) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: snake_case_ = datasets['train'].column_names else: snake_case_ = datasets['validation'].column_names snake_case_ = 'text' if 'text' in column_names else column_names[0] snake_case_ = 'max_length' if data_args.pad_to_max_length else False def tokenize_function(UpperCAmelCase ): # Remove empty lines snake_case_ = [line for line in examples['text'] if len(UpperCAmelCase ) > 0 and not line.isspace()] return tokenizer(examples['text'] , padding=UpperCAmelCase , truncation=UpperCAmelCase , max_length=data_args.max_seq_length ) snake_case_ = datasets.map( UpperCAmelCase , batched=UpperCAmelCase , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: snake_case_ = add_chinese_references(tokenized_datasets['train'] , data_args.train_ref_file ) if data_args.validation_ref_file is not None: snake_case_ = add_chinese_references( tokenized_datasets['validation'] , data_args.validation_ref_file ) # If we have ref files, need to avoid it removed by trainer snake_case_ = data_args.train_ref_file or data_args.validation_ref_file if has_ref: snake_case_ = False # Data collator # This one will take care of randomly masking the tokens. snake_case_ = DataCollatorForWholeWordMask(tokenizer=UpperCAmelCase , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer snake_case_ = Trainer( model=UpperCAmelCase , args=UpperCAmelCase , train_dataset=tokenized_datasets['train'] if training_args.do_train else None , eval_dataset=tokenized_datasets['validation'] if training_args.do_eval else None , tokenizer=UpperCAmelCase , data_collator=UpperCAmelCase , ) # Training if training_args.do_train: if last_checkpoint is not None: snake_case_ = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ): snake_case_ = model_args.model_name_or_path else: snake_case_ = None snake_case_ = trainer.train(resume_from_checkpoint=UpperCAmelCase ) trainer.save_model() # Saves the tokenizer too for easy upload snake_case_ = os.path.join(training_args.output_dir , 'train_results.txt' ) if trainer.is_world_process_zero(): with open(UpperCAmelCase , 'w' ) as writer: logger.info('***** Train results *****' ) for key, value in sorted(train_result.metrics.items() ): logger.info(f' {key} = {value}' ) writer.write(f'{key} = {value}\n' ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , 'trainer_state.json' ) ) # Evaluation snake_case_ = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) snake_case_ = trainer.evaluate() snake_case_ = math.exp(eval_output['eval_loss'] ) snake_case_ = perplexity snake_case_ = os.path.join(training_args.output_dir , 'eval_results_mlm_wwm.txt' ) if trainer.is_world_process_zero(): with open(UpperCAmelCase , 'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in sorted(results.items() ): logger.info(f' {key} = {value}' ) writer.write(f'{key} = {value}\n' ) return results def UpperCAmelCase ( UpperCAmelCase ) -> List[str]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
69
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if num < 0: return False snake_case_ = num snake_case_ = 0 while num > 0: snake_case_ = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
347
0
'''simple docstring''' # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path A__ : Dict =Path(__file__).resolve().parents[3] / '''src''' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) A__ : Optional[int] ={'''base''': '''patrickvonplaten/wav2vec2_tiny_random''', '''robust''': '''patrickvonplaten/wav2vec2_tiny_random_robust'''} A__ : List[str] ='''zero2''' A__ : List[Any] ='''zero3''' A__ : str =[ZEROa, ZEROa] def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = parameterized.to_safe_name("""_""".join(str(lowerCAmelCase ) for x in param.args ) ) return f"{func.__name__}_{param_based_name}" # Cartesian-product of zero stages with models to test A__ : Any =list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class UpperCAmelCase ( snake_case_ ): @parameterized.expand(__snake_case , name_func=__snake_case ) def lowercase__ ( self : List[str] , __snake_case : Tuple , __snake_case : Optional[int] ) -> List[str]: self.run_and_check( stage=__snake_case , model=__snake_case , distributed=__snake_case , fpaa=__snake_case , ) @require_torch_multi_gpu @parameterized.expand(__snake_case , name_func=__snake_case ) def lowercase__ ( self : List[Any] , __snake_case : Union[str, Any] , __snake_case : int ) -> int: self.run_and_check( stage=__snake_case , model=__snake_case , distributed=__snake_case , fpaa=__snake_case , ) @parameterized.expand(__snake_case , name_func=__snake_case ) def lowercase__ ( self : Any , __snake_case : Optional[int] , __snake_case : Dict ) -> Tuple: self.run_and_check( stage=__snake_case , model=__snake_case , distributed=__snake_case , fpaa=__snake_case , ) @require_torch_multi_gpu @parameterized.expand(__snake_case , name_func=__snake_case ) def lowercase__ ( self : Tuple , __snake_case : Optional[int] , __snake_case : Dict ) -> Union[str, Any]: self.run_and_check( stage=__snake_case , model=__snake_case , distributed=__snake_case , fpaa=__snake_case , ) def lowercase__ ( self : Optional[Any] , __snake_case : Union[str, Any] ) -> Union[str, Any]: # XXX: run_asr is premature and doesn't save any results # so all we check for now is that the process didn't fail pass def lowercase__ ( self : Dict , __snake_case : str , __snake_case : str , __snake_case : int = 10 , __snake_case : bool = True , __snake_case : bool = True , __snake_case : bool = True , ) -> Optional[int]: _lowerCAmelCase = models[model] _lowerCAmelCase = self.run_trainer( stage=__snake_case , model_name=__snake_case , eval_steps=__snake_case , num_train_epochs=1 , distributed=__snake_case , fpaa=__snake_case , ) self.do_checks(__snake_case ) return output_dir def lowercase__ ( self : Optional[int] , __snake_case : str , __snake_case : str , __snake_case : int = 10 , __snake_case : int = 1 , __snake_case : bool = True , __snake_case : bool = True , ) -> Optional[Any]: _lowerCAmelCase = self.get_auto_remove_tmp_dir("""./xxx""" , after=__snake_case ) _lowerCAmelCase = f"\n --model_name_or_path {model_name}\n --dataset_name hf-internal-testing/librispeech_asr_dummy\n --dataset_config_name clean\n --train_split_name validation\n --validation_split_name validation\n --output_dir {output_dir}\n --num_train_epochs {str(__snake_case )}\n --per_device_train_batch_size 2\n --per_device_eval_batch_size 2\n --evaluation_strategy steps\n --learning_rate 5e-4\n --warmup_steps 8\n --orthography timit\n --preprocessing_num_workers 1\n --group_by_length\n --freeze_feature_extractor\n --report_to none\n --save_steps 0\n --eval_steps {eval_steps}\n --report_to none\n ".split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files _lowerCAmelCase = f"--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json".split() _lowerCAmelCase = [f"{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"] _lowerCAmelCase = self.get_launcher(__snake_case ) _lowerCAmelCase = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(__snake_case , env=self.get_env() ) return output_dir def lowercase__ ( self : Tuple , __snake_case : List[Any]=False ) -> List[Any]: # 1. explicitly set --num_nodes=1 just in case these tests end up run on a multi-node setup # - it won't be able to handle that # 2. for now testing with just 2 gpus max (since some quality tests may give different # results with mode gpus because we use very little data) _lowerCAmelCase = min(2 , get_gpu_count() ) if distributed else 1 return f"deepspeed --num_nodes 1 --num_gpus {num_gpus}".split()
70
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin __SCREAMING_SNAKE_CASE : Tuple = get_tests_dir('fixtures/test_sentencepiece_bpe_char.model') @require_sentencepiece @require_tokenizers class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Tuple = SpeechTaTokenizer __lowercase: int = False __lowercase: List[str] = True def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing snake_case_ = SpeechTaTokenizer(UpperCAmelCase_ ) snake_case_ = AddedToken("""<mask>""" , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) snake_case_ = mask_token tokenizer.add_special_tokens({"""mask_token""": mask_token} ) tokenizer.add_tokens(["""<ctc_blank>"""] ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = """this is a test""" snake_case_ = """this is a test""" return input_text, output_text def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Any=False , UpperCAmelCase_ : Tuple=20 , UpperCAmelCase_ : Dict=5 ) ->List[Any]: """simple docstring""" snake_case_ , snake_case_ = self.get_input_output_texts(UpperCAmelCase_ ) snake_case_ = tokenizer.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ ) snake_case_ = tokenizer.decode(UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ ) return text, ids def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" snake_case_ = """<pad>""" snake_case_ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_ ) , UpperCAmelCase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_ ) , UpperCAmelCase_ ) def lowerCAmelCase ( self : int ) ->str: """simple docstring""" snake_case_ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-4] , """œ""" ) self.assertEqual(vocab_keys[-2] , """<mask>""" ) self.assertEqual(vocab_keys[-1] , """<ctc_blank>""" ) self.assertEqual(len(UpperCAmelCase_ ) , 81 ) def lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = self.get_tokenizers(do_lower_case=UpperCAmelCase_ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case_ = tokenizer.vocab_size snake_case_ = len(UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) snake_case_ = ["""aaaaa bbbbbb""", """cccccccccdddddddd"""] snake_case_ = tokenizer.add_tokens(UpperCAmelCase_ ) snake_case_ = tokenizer.vocab_size snake_case_ = len(UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , 0 ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , len(UpperCAmelCase_ ) ) self.assertEqual(UpperCAmelCase_ , all_size + len(UpperCAmelCase_ ) ) snake_case_ = tokenizer.encode("""aaaaa bbbbbb low cccccccccdddddddd l""" , add_special_tokens=UpperCAmelCase_ ) self.assertGreaterEqual(len(UpperCAmelCase_ ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) snake_case_ = {"""eos_token""": """>>>>|||<||<<|<<""", """pad_token""": """<<<<<|||>|>>>>|>"""} snake_case_ = tokenizer.add_special_tokens(UpperCAmelCase_ ) snake_case_ = tokenizer.vocab_size snake_case_ = len(UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , 0 ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , len(UpperCAmelCase_ ) ) self.assertEqual(UpperCAmelCase_ , all_size_a + len(UpperCAmelCase_ ) ) snake_case_ = tokenizer.encode( """>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l""" , add_special_tokens=UpperCAmelCase_ ) self.assertGreaterEqual(len(UpperCAmelCase_ ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" pass def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" pass def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = self.get_tokenizer() snake_case_ = tokenizer.tokenize("""This is a test""" ) # fmt: off self.assertListEqual(UpperCAmelCase_ , [SPIECE_UNDERLINE, """T""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """a""", SPIECE_UNDERLINE, """t""", """e""", """s""", """t"""] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) snake_case_ = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( UpperCAmelCase_ , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """92000""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) snake_case_ = tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) # fmt: off self.assertListEqual(UpperCAmelCase_ , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on snake_case_ = tokenizer.convert_ids_to_tokens(UpperCAmelCase_ ) self.assertListEqual( UpperCAmelCase_ , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """<unk>""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) @slow def lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" snake_case_ = [ """Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides """ """general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural """ """Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained """ """models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.""", """BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly """ """conditioning on both left and right context in all layers.""", """The quick brown fox jumps over the lazy dog.""", ] # fmt: off snake_case_ = { """input_ids""": [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], """attention_mask""": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase_ , model_name="""microsoft/speecht5_asr""" , revision="""c5ef64c71905caeccde0e4462ef3f9077224c524""" , sequences=UpperCAmelCase_ , )
347
0
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize('repo_id' ,['canonical_dataset_name', 'org-name/dataset-name'] ) @pytest.mark.parametrize('path' ,['filename.csv', 'filename with blanks.csv'] ) @pytest.mark.parametrize('revision' ,[None, 'v2'] ) def A ( a_ ,a_ ,a_ ) -> Optional[int]: __UpperCamelCase : Tuple =hf_hub_url(repo_id=a_ ,path=a_ ,revision=a_ ) assert url == F'https://huggingface.co/datasets/{repo_id}/resolve/{revision or "main"}/{quote(a_ )}'
71
"""simple docstring""" import datasets __SCREAMING_SNAKE_CASE : Tuple = '\\n@InProceedings{conneau2018xnli,\n author = "Conneau, Alexis\n and Rinott, Ruty\n and Lample, Guillaume\n and Williams, Adina\n and Bowman, Samuel R.\n and Schwenk, Holger\n and Stoyanov, Veselin",\n title = "XNLI: Evaluating Cross-lingual Sentence Representations",\n booktitle = "Proceedings of the 2018 Conference on Empirical Methods\n in Natural Language Processing",\n year = "2018",\n publisher = "Association for Computational Linguistics",\n location = "Brussels, Belgium",\n}\n' __SCREAMING_SNAKE_CASE : Dict = '\\nXNLI is a subset of a few thousand examples from MNLI which has been translated\ninto a 14 different languages (some low-ish resource). As with MNLI, the goal is\nto predict textual entailment (does sentence A imply/contradict/neither sentence\nB) and is a classification task (given two sentences, predict one of three\nlabels).\n' __SCREAMING_SNAKE_CASE : List[str] = '\nComputes XNLI score which is just simple accuracy.\nArgs:\n predictions: Predicted labels.\n references: Ground truth labels.\nReturns:\n \'accuracy\': accuracy\nExamples:\n\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> xnli_metric = datasets.load_metric("xnli")\n >>> results = xnli_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n' def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: return (preds == labels).mean() @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __A (datasets.Metric): '''simple docstring''' def lowerCAmelCase ( self : str ) ->Any: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), """references""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), } ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" , ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" return {"accuracy": simple_accuracy(UpperCAmelCase_ , UpperCAmelCase_ )}
347
0
"""simple docstring""" from datetime import datetime import requests def snake_case_ ( A_ : str ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = '''https://downloadgram.net/wp-json/wppress/video-downloader/video?url=''' _lowerCamelCase : Dict = requests.get(base_url + url ).json()[0]['''urls'''][0]['''src'''] return requests.get(A_ ).content if __name__ == "__main__": lowerCAmelCase__ = input('''Enter Video/IGTV url: ''').strip() lowerCAmelCase__ = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4""" with open(file_name, '''wb''') as fp: fp.write(download_video(url)) print(F"""Done. Video saved to disk as {file_name}.""")
72
"""simple docstring""" from ..utils import DummyObject, requires_backends class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : List[str] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""sentencepiece"""] def __init__( self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Tuple ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : Any , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : List[Any] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Dict = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[str] = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : int ) ->List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Tuple , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Dict ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Union[str, Any] ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[Any] = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : Optional[Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""sentencepiece"""] def __init__( self : Optional[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : str , **UpperCAmelCase_ : int ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Optional[int] , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Tuple = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : List[Any] ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : List[str] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Tuple = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Optional[Any] ) ->str: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Optional[Any] ) ->int: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = ["""sentencepiece"""] def __init__( self : Optional[Any] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : Optional[Any] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Dict ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : List[str] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any] ) ->List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : Any , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Optional[Any] ) ->List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Dict = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Union[str, Any] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Optional[int] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = ["""sentencepiece"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : str ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""sentencepiece"""] def __init__( self : Tuple , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Optional[int] ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Dict = ["""sentencepiece"""] def __init__( self : Optional[int] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : List[str] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Optional[int] ) ->Any: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[str] = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Union[str, Any] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Optional[int] ) ->str: """simple docstring""" requires_backends(self , ["""sentencepiece"""] )
347
0
import argparse import math import os import torch from neural_compressor.utils.pytorch import load from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, StableDiffusionPipeline, UNetaDConditionModel def SCREAMING_SNAKE_CASE__ ( ) -> Optional[Any]: __lowerCamelCase : Tuple = argparse.ArgumentParser() parser.add_argument( '-m' , '--pretrained_model_name_or_path' , type=lowerCamelCase__ , default=lowerCamelCase__ , required=lowerCamelCase__ , help='Path to pretrained model or model identifier from huggingface.co/models.' , ) parser.add_argument( '-c' , '--caption' , type=lowerCamelCase__ , default='robotic cat with wings' , help='Text used to generate images.' , ) parser.add_argument( '-n' , '--images_num' , type=lowerCamelCase__ , default=4 , help='How much images to generate.' , ) parser.add_argument( '-s' , '--seed' , type=lowerCamelCase__ , default=4_2 , help='Seed for random process.' , ) parser.add_argument( '-ci' , '--cuda_id' , type=lowerCamelCase__ , default=0 , help='cuda_id.' , ) __lowerCamelCase : Any = parser.parse_args() return args def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: if not len(lowerCamelCase__ ) == rows * cols: raise ValueError('The specified number of rows and columns are not correct.' ) __lowerCamelCase , __lowerCamelCase : Optional[int] = imgs[0].size __lowerCamelCase : List[Any] = Image.new('RGB' , size=(cols * w, rows * h) ) __lowerCamelCase , __lowerCamelCase : List[str] = grid.size for i, img in enumerate(lowerCamelCase__ ): grid.paste(lowerCamelCase__ , box=(i % cols * w, i // cols * h) ) return grid def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__="robotic cat with wings" , lowerCamelCase__=7.5 , lowerCamelCase__=5_0 , lowerCamelCase__=1 , lowerCamelCase__=4_2 , ) -> int: __lowerCamelCase : Any = torch.Generator(pipeline.device ).manual_seed(lowerCamelCase__ ) __lowerCamelCase : int = pipeline( lowerCamelCase__ , guidance_scale=lowerCamelCase__ , num_inference_steps=lowerCamelCase__ , generator=lowerCamelCase__ , num_images_per_prompt=lowerCamelCase__ , ).images __lowerCamelCase : Union[str, Any] = int(math.sqrt(lowerCamelCase__ ) ) __lowerCamelCase : str = image_grid(lowerCamelCase__ , rows=_rows , cols=num_images_per_prompt // _rows ) return grid, images a =parse_args() # Load models and create wrapper for stable diffusion a =CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="""tokenizer""") a =CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="""text_encoder""") a =AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="""vae""") a =UNetaDConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="""unet""") a =StableDiffusionPipeline.from_pretrained( args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer ) a =lambda images, clip_input: (images, False) if os.path.exists(os.path.join(args.pretrained_model_name_or_path, """best_model.pt""")): a =load(args.pretrained_model_name_or_path, model=unet) unet.eval() setattr(pipeline, """unet""", unet) else: a =unet.to(torch.device("""cuda""", args.cuda_id)) a =pipeline.to(unet.device) a , a =generate_images(pipeline, prompt=args.caption, num_images_per_prompt=args.images_num, seed=args.seed) grid.save(os.path.join(args.pretrained_model_name_or_path, """{}.png""".format("""_""".join(args.caption.split())))) a =os.path.join(args.pretrained_model_name_or_path, """_""".join(args.caption.split())) os.makedirs(dirname, exist_ok=True) for idx, image in enumerate(images): image.save(os.path.join(dirname, """{}.png""".format(idx + 1)))
73
"""simple docstring""" import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor __SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) class __A (snake_case__): '''simple docstring''' def __init__( self : str , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int ) ->None: """simple docstring""" warnings.warn( """The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use MobileViTImageProcessor instead.""" , UpperCAmelCase_ , ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ )
347
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer import diffusers from diffusers import ( AutoencoderKL, EulerDiscreteScheduler, StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.schedulers import KarrasDiffusionSchedulers from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() def _snake_case ( snake_case__ : Union[str, Any] ): A = [tensor.shape for tensor in tensor_list] return all(shape == shapes[0] for shape in shapes[1:] ) class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Any = StableDiffusionLatentUpscalePipeline _lowerCamelCase: Dict = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { '''height''', '''width''', '''cross_attention_kwargs''', '''negative_prompt_embeds''', '''prompt_embeds''', } _lowerCamelCase: List[str] = PipelineTesterMixin.required_optional_params - {'''num_images_per_prompt'''} _lowerCamelCase: int = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS _lowerCamelCase: Union[str, Any] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _lowerCamelCase: Optional[int] = frozenset([] ) _lowerCamelCase: Tuple = True @property def _SCREAMING_SNAKE_CASE ( self : str ) -> str: A = 1 A = 4 A = (16, 16) A = floats_tensor((batch_size, num_channels) + sizes ,rng=random.Random(0 ) ).to(A_ ) return image def _SCREAMING_SNAKE_CASE ( self : int ) -> str: torch.manual_seed(0 ) A = UNetaDConditionModel( act_fn='gelu' ,attention_head_dim=8 ,norm_num_groups=A_ ,block_out_channels=[32, 32, 64, 64] ,time_cond_proj_dim=160 ,conv_in_kernel=1 ,conv_out_kernel=1 ,cross_attention_dim=32 ,down_block_types=( 'KDownBlock2D', 'KCrossAttnDownBlock2D', 'KCrossAttnDownBlock2D', 'KCrossAttnDownBlock2D', ) ,in_channels=8 ,mid_block_type=A_ ,only_cross_attention=A_ ,out_channels=5 ,resnet_time_scale_shift='scale_shift' ,time_embedding_type='fourier' ,timestep_post_act='gelu' ,up_block_types=('KCrossAttnUpBlock2D', 'KCrossAttnUpBlock2D', 'KCrossAttnUpBlock2D', 'KUpBlock2D') ,) A = AutoencoderKL( block_out_channels=[32, 32, 64, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=[ 'DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D', ] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=4 ,) A = EulerDiscreteScheduler(prediction_type='sample' ) A = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,hidden_act='quick_gelu' ,projection_dim=512 ,) A = CLIPTextModel(A_ ) A = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) A = { 'unet': model.eval(), 'vae': vae.eval(), 'scheduler': scheduler, 'text_encoder': text_encoder, 'tokenizer': tokenizer, } return components def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[int] ,A_ : Union[str, Any]=0 ) -> List[Any]: if str(A_ ).startswith('mps' ): A = torch.manual_seed(A_ ) else: A = torch.Generator(device=A_ ).manual_seed(A_ ) A = { 'prompt': 'A painting of a squirrel eating a burger', 'image': self.dummy_image.cpu(), 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = 'cpu' A = self.get_dummy_components() A = self.pipeline_class(**A_ ) pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs(A_ ) A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] self.assertEqual(image.shape ,(1, 256, 256, 3) ) A = np.array( [0.47_22_24_12, 0.41_92_16_33, 0.44_71_74_34, 0.46_87_41_92, 0.42_58_82_58, 0.46_15_07_26, 0.4_67_75_34, 0.45_58_38_32, 0.48_57_90_55] ) A = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(A_ ,1e-3 ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: super().test_attention_slicing_forward_pass(expected_max_diff=7e-3 ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: super().test_cpu_offload_forward_pass(expected_max_diff=3e-3 ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: super().test_inference_batch_single_identical(expected_max_diff=7e-3 ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3e-3 ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: super().test_save_load_local(expected_max_difference=3e-3 ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: A = [ 'DDIMScheduler', 'DDPMScheduler', 'PNDMScheduler', 'HeunDiscreteScheduler', 'EulerAncestralDiscreteScheduler', 'KDPM2DiscreteScheduler', 'KDPM2AncestralDiscreteScheduler', 'DPMSolverSDEScheduler', ] A = self.get_dummy_components() A = self.pipeline_class(**A_ ) # make sure that PNDM does not need warm-up pipe.scheduler.register_to_config(skip_prk_steps=A_ ) pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs(A_ ) A = 2 A = [] for scheduler_enum in KarrasDiffusionSchedulers: if scheduler_enum.name in skip_schedulers: # no sigma schedulers are not supported # no schedulers continue A = getattr(A_ ,scheduler_enum.name ) A = scheduler_cls.from_config(pipe.scheduler.config ) A = pipe(**A_ )[0] outputs.append(A_ ) assert check_same_shape(A_ ) @require_torch_gpu @slow class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: super().tearDown() gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: A = torch.manual_seed(33 ) A = StableDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4' ,torch_dtype=torch.floataa ) pipe.to('cuda' ) A = StableDiffusionLatentUpscalePipeline.from_pretrained( 'stabilityai/sd-x2-latent-upscaler' ,torch_dtype=torch.floataa ) upscaler.to('cuda' ) A = 'a photo of an astronaut high resolution, unreal engine, ultra realistic' A = pipe(A_ ,generator=A_ ,output_type='latent' ).images A = upscaler( prompt=A_ ,image=A_ ,num_inference_steps=20 ,guidance_scale=0 ,generator=A_ ,output_type='np' ,).images[0] A = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy' ) assert np.abs((expected_image - image).mean() ) < 5e-2 def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: A = torch.manual_seed(33 ) A = StableDiffusionLatentUpscalePipeline.from_pretrained( 'stabilityai/sd-x2-latent-upscaler' ,torch_dtype=torch.floataa ) upscaler.to('cuda' ) A = 'the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas' A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png' ) A = upscaler( prompt=A_ ,image=A_ ,num_inference_steps=20 ,guidance_scale=0 ,generator=A_ ,output_type='np' ,).images[0] A = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy' ) assert np.abs((expected_image - image).max() ) < 5e-2
74
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Any: snake_case_ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"""blocks.{i}.norm1.weight""", f"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """vit.embeddings.cls_token"""), ("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" snake_case_ = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) return rename_keys def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Tuple: for i in range(config.num_hidden_layers ): if base_model: snake_case_ = """""" else: snake_case_ = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case_ = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" ) snake_case_ = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict snake_case_ = in_proj_weight[ : config.hidden_size, : ] snake_case_ = in_proj_bias[: config.hidden_size] snake_case_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case_ = in_proj_weight[ -config.hidden_size :, : ] snake_case_ = in_proj_bias[-config.hidden_size :] def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: snake_case_ = dct.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = val def _a ( ) -> Any: snake_case_ = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = ViTConfig() snake_case_ = False # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size if vit_name[-5:] == "in21k": snake_case_ = True snake_case_ = int(vit_name[-12:-10] ) snake_case_ = int(vit_name[-9:-6] ) else: snake_case_ = 1_000 snake_case_ = """huggingface/label-files""" snake_case_ = """imagenet-1k-id2label.json""" snake_case_ = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) snake_case_ = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} snake_case_ = idalabel snake_case_ = {v: k for k, v in idalabel.items()} snake_case_ = int(vit_name[-6:-4] ) snake_case_ = int(vit_name[-3:] ) # size of the architecture if "deit" in vit_name: if vit_name[9:].startswith("""tiny""" ): snake_case_ = 192 snake_case_ = 768 snake_case_ = 12 snake_case_ = 3 elif vit_name[9:].startswith("""small""" ): snake_case_ = 384 snake_case_ = 1_536 snake_case_ = 12 snake_case_ = 6 else: pass else: if vit_name[4:].startswith("""small""" ): snake_case_ = 768 snake_case_ = 2_304 snake_case_ = 8 snake_case_ = 8 elif vit_name[4:].startswith("""base""" ): pass elif vit_name[4:].startswith("""large""" ): snake_case_ = 1_024 snake_case_ = 4_096 snake_case_ = 24 snake_case_ = 16 elif vit_name[4:].startswith("""huge""" ): snake_case_ = 1_280 snake_case_ = 5_120 snake_case_ = 32 snake_case_ = 16 # load original model from timm snake_case_ = timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ) timm_model.eval() # load state_dict of original model, remove and rename some keys snake_case_ = timm_model.state_dict() if base_model: remove_classification_head_(_SCREAMING_SNAKE_CASE ) snake_case_ = create_rename_keys(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for src, dest in rename_keys: rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) read_in_q_k_v(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load HuggingFace model if vit_name[-5:] == "in21k": snake_case_ = ViTModel(_SCREAMING_SNAKE_CASE ).eval() else: snake_case_ = ViTForImageClassification(_SCREAMING_SNAKE_CASE ).eval() model.load_state_dict(_SCREAMING_SNAKE_CASE ) # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor if "deit" in vit_name: snake_case_ = DeiTImageProcessor(size=config.image_size ) else: snake_case_ = ViTImageProcessor(size=config.image_size ) snake_case_ = image_processor(images=prepare_img() , return_tensors="""pt""" ) snake_case_ = encoding["""pixel_values"""] snake_case_ = model(_SCREAMING_SNAKE_CASE ) if base_model: snake_case_ = timm_model.forward_features(_SCREAMING_SNAKE_CASE ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(_SCREAMING_SNAKE_CASE , outputs.pooler_output , atol=1E-3 ) else: snake_case_ = timm_model(_SCREAMING_SNAKE_CASE ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_SCREAMING_SNAKE_CASE , outputs.logits , atol=1E-3 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(f"""Saving model {vit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--vit_name', default='vit_base_patch16_224', type=str, help='Name of the ViT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) __SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
347
0
'''simple docstring''' import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class __UpperCamelCase : def __init__( self, lowerCAmelCase, lowerCAmelCase=13, lowerCAmelCase=7, lowerCAmelCase=True, lowerCAmelCase=True, lowerCAmelCase=False, lowerCAmelCase=True, lowerCAmelCase=99, lowerCAmelCase=32, lowerCAmelCase=5, lowerCAmelCase=4, lowerCAmelCase=37, lowerCAmelCase="gelu", lowerCAmelCase=0.1, lowerCAmelCase=0.1, lowerCAmelCase=512, lowerCAmelCase=16, lowerCAmelCase=2, lowerCAmelCase=0.0_2, lowerCAmelCase=3, lowerCAmelCase=4, lowerCAmelCase=None, ): """simple docstring""" lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =seq_length lowerCamelCase_ =is_training lowerCamelCase_ =use_input_mask lowerCamelCase_ =use_token_type_ids lowerCamelCase_ =use_labels lowerCamelCase_ =vocab_size lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_act lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =type_vocab_size lowerCamelCase_ =type_sequence_label_size lowerCamelCase_ =initializer_range lowerCamelCase_ =num_labels lowerCamelCase_ =num_choices lowerCamelCase_ =scope def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) lowerCamelCase_ =None if self.use_input_mask: lowerCamelCase_ =random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase_ =None if self.use_token_type_ids: lowerCamelCase_ =ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size ) lowerCamelCase_ =None lowerCamelCase_ =None lowerCamelCase_ =None if self.use_labels: lowerCamelCase_ =ids_tensor([self.batch_size], self.type_sequence_label_size ) lowerCamelCase_ =ids_tensor([self.batch_size, self.seq_length], self.num_labels ) lowerCamelCase_ =ids_tensor([self.batch_size], self.num_choices ) lowerCamelCase_ =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase__ ( self ): """simple docstring""" return LlamaConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=lowerCAmelCase, initializer_range=self.initializer_range, ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =LlamaModel(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() lowerCamelCase_ =model(lowerCAmelCase, attention_mask=lowerCAmelCase ) lowerCamelCase_ =model(lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, ): """simple docstring""" lowerCamelCase_ =True lowerCamelCase_ =LlamaModel(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() lowerCamelCase_ =model( lowerCAmelCase, attention_mask=lowerCAmelCase, encoder_hidden_states=lowerCAmelCase, encoder_attention_mask=lowerCAmelCase, ) lowerCamelCase_ =model( lowerCAmelCase, attention_mask=lowerCAmelCase, encoder_hidden_states=lowerCAmelCase, ) lowerCamelCase_ =model(lowerCAmelCase, attention_mask=lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, ): """simple docstring""" lowerCamelCase_ =LlamaForCausalLM(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() lowerCamelCase_ =model(lowerCAmelCase, attention_mask=lowerCAmelCase, labels=lowerCAmelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size) ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, ): """simple docstring""" lowerCamelCase_ =True lowerCamelCase_ =True lowerCamelCase_ =LlamaForCausalLM(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() # first forward pass lowerCamelCase_ =model( lowerCAmelCase, attention_mask=lowerCAmelCase, encoder_hidden_states=lowerCAmelCase, encoder_attention_mask=lowerCAmelCase, use_cache=lowerCAmelCase, ) lowerCamelCase_ =outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids lowerCamelCase_ =ids_tensor((self.batch_size, 3), config.vocab_size ) lowerCamelCase_ =ids_tensor((self.batch_size, 3), vocab_size=2 ) # append to next input_ids and lowerCamelCase_ =torch.cat([input_ids, next_tokens], dim=-1 ) lowerCamelCase_ =torch.cat([input_mask, next_mask], dim=-1 ) lowerCamelCase_ =model( lowerCAmelCase, attention_mask=lowerCAmelCase, encoder_hidden_states=lowerCAmelCase, encoder_attention_mask=lowerCAmelCase, output_hidden_states=lowerCAmelCase, )['''hidden_states'''][0] lowerCamelCase_ =model( lowerCAmelCase, attention_mask=lowerCAmelCase, encoder_hidden_states=lowerCAmelCase, encoder_attention_mask=lowerCAmelCase, past_key_values=lowerCAmelCase, output_hidden_states=lowerCAmelCase, )['''hidden_states'''][0] # select random slice lowerCamelCase_ =ids_tensor((1,), output_from_past.shape[-1] ).item() lowerCamelCase_ =output_from_no_past[:, -3:, random_slice_idx].detach() lowerCamelCase_ =output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCAmelCase, lowerCAmelCase, atol=1e-3 ) ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self.prepare_config_and_inputs() ( ( lowerCamelCase_ ), ( lowerCamelCase_ ), ( lowerCamelCase_ ), ( lowerCamelCase_ ), ( lowerCamelCase_ ), ( lowerCamelCase_ ), ( lowerCamelCase_ ), ) =config_and_inputs lowerCamelCase_ ={'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __UpperCamelCase ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase : str =(LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () lowercase : Optional[Any] =(LlamaForCausalLM,) if is_torch_available() else () lowercase : int =( { 'feature-extraction': LlamaModel, 'text-classification': LlamaForSequenceClassification, 'text-generation': LlamaForCausalLM, 'zero-shot': LlamaForSequenceClassification, } if is_torch_available() else {} ) lowercase : str =False lowercase : List[Any] =False def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =LlamaModelTester(self ) lowerCamelCase_ =ConfigTester(self, config_class=lowerCAmelCase, hidden_size=37 ) def lowercase__ ( self ): """simple docstring""" self.config_tester.run_common_tests() def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowerCamelCase_ =type self.model_tester.create_and_check_model(*lowerCAmelCase ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_, lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ =3 lowerCamelCase_ =input_dict['''input_ids'''] lowerCamelCase_ =input_ids.ne(1 ).to(lowerCAmelCase ) lowerCamelCase_ =ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size ) lowerCamelCase_ =LlamaForSequenceClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() lowerCamelCase_ =model(lowerCAmelCase, attention_mask=lowerCAmelCase, labels=lowerCAmelCase ) self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels) ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_, lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ =3 lowerCamelCase_ ='''single_label_classification''' lowerCamelCase_ =input_dict['''input_ids'''] lowerCamelCase_ =input_ids.ne(1 ).to(lowerCAmelCase ) lowerCamelCase_ =ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size ) lowerCamelCase_ =LlamaForSequenceClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() lowerCamelCase_ =model(lowerCAmelCase, attention_mask=lowerCAmelCase, labels=lowerCAmelCase ) self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels) ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_, lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ =3 lowerCamelCase_ ='''multi_label_classification''' lowerCamelCase_ =input_dict['''input_ids'''] lowerCamelCase_ =input_ids.ne(1 ).to(lowerCAmelCase ) lowerCamelCase_ =ids_tensor( [self.model_tester.batch_size, config.num_labels], self.model_tester.type_sequence_label_size ).to(torch.float ) lowerCamelCase_ =LlamaForSequenceClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() lowerCamelCase_ =model(lowerCAmelCase, attention_mask=lowerCAmelCase, labels=lowerCAmelCase ) self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('''LLaMA buffers include complex numbers, which breaks this test''' ) def lowercase__ ( self ): """simple docstring""" pass @parameterized.expand([('''linear''',), ('''dynamic''',)] ) def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" lowerCamelCase_, lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ =ids_tensor([1, 10], config.vocab_size ) lowerCamelCase_ =ids_tensor([1, int(config.max_position_embeddings * 1.5 )], config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights lowerCamelCase_ =LlamaModel(lowerCAmelCase ) original_model.to(lowerCAmelCase ) original_model.eval() lowerCamelCase_ =original_model(lowerCAmelCase ).last_hidden_state lowerCamelCase_ =original_model(lowerCAmelCase ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights lowerCamelCase_ ={'''type''': scaling_type, '''factor''': 1_0.0} lowerCamelCase_ =LlamaModel(lowerCAmelCase ) scaled_model.to(lowerCAmelCase ) scaled_model.eval() lowerCamelCase_ =scaled_model(lowerCAmelCase ).last_hidden_state lowerCamelCase_ =scaled_model(lowerCAmelCase ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(lowerCAmelCase, lowerCAmelCase, atol=1e-5 ) ) else: self.assertFalse(torch.allclose(lowerCAmelCase, lowerCAmelCase, atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(lowerCAmelCase, lowerCAmelCase, atol=1e-5 ) ) @require_torch class __UpperCamelCase ( unittest.TestCase ): @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' ) @slow def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =[1, 306, 4_658, 278, 6_593, 310, 2_834, 338] lowerCamelCase_ =LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-7b-hf''', device_map='''auto''' ) lowerCamelCase_ =model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 lowerCamelCase_ =torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]] ) torch.testing.assert_close(out.mean(-1 ), lowerCAmelCase, atol=1e-2, rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off lowerCamelCase_ =torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30], lowerCAmelCase, atol=1e-5, rtol=1e-5 ) @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' ) @slow def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =[1, 306, 4_658, 278, 6_593, 310, 2_834, 338] lowerCamelCase_ =LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-hf''', device_map='''auto''' ) lowerCamelCase_ =model(torch.tensor(lowerCAmelCase ) ) # Expected mean on dim = -1 lowerCamelCase_ =torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]] ) torch.testing.assert_close(out.mean(-1 ), lowerCAmelCase, atol=1e-2, rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off lowerCamelCase_ =torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3] ) # fmt: on torch.testing.assert_close(out[0, 0, :30], lowerCAmelCase, atol=1e-5, rtol=1e-5 ) @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' ) @slow def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =[1, 306, 4_658, 278, 6_593, 310, 2_834, 338] lowerCamelCase_ =LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-chat-hf''', device_map='''auto''' ) lowerCamelCase_ =model(torch.tensor(lowerCAmelCase ) ) # Expected mean on dim = -1 lowerCamelCase_ =torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]] ) torch.testing.assert_close(out.mean(-1 ), lowerCAmelCase, atol=1e-2, rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off lowerCamelCase_ =torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3] ) # fmt: on torch.testing.assert_close(out.mean(-1 ), lowerCAmelCase, atol=1e-2, rtol=1e-2 ) @unittest.skip( '''Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test''' ) @slow def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =[1, 306, 4_658, 278, 6_593, 310, 2_834, 338] lowerCamelCase_ =LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-70b-hf''', device_map='''auto''' ) lowerCamelCase_ =model(torch.tensor(lowerCAmelCase ) ) lowerCamelCase_ =torch.tensor( [[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]], dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ), lowerCAmelCase, atol=1e-2, rtol=1e-2 ) # fmt: off lowerCamelCase_ =torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2] ) # fmt: on torch.testing.assert_close(out[0, 0, :30], lowerCAmelCase, atol=1e-5, rtol=1e-5 ) @unittest.skip('''Model is curently gated''' ) @slow def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ ='''Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi''' lowerCamelCase_ ='''Simply put, the theory of relativity states that ''' lowerCamelCase_ =LlamaTokenizer.from_pretrained('''meta-llama/Llama-2-13b-chat-hf''' ) lowerCamelCase_ =tokenizer.encode(lowerCAmelCase, return_tensors='''pt''' ) lowerCamelCase_ =LlamaForCausalLM.from_pretrained( '''meta-llama/Llama-2-13b-chat-hf''', device_map='''sequential''', use_safetensors=lowerCAmelCase ) # greedy generation outputs lowerCamelCase_ =model.generate(lowerCAmelCase, max_new_tokens=64, top_p=lowerCAmelCase, temperature=1, do_sample=lowerCAmelCase ) lowerCamelCase_ =tokenizer.decode(generated_ids[0], skip_special_tokens=lowerCAmelCase ) self.assertEqual(lowerCAmelCase, lowerCAmelCase )
75
"""simple docstring""" import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __A (unittest.TestCase): '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple=13 , UpperCAmelCase_ : List[Any]=7 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Dict=99 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : Tuple=5 , UpperCAmelCase_ : Union[str, Any]=4 , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : int="gelu" , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : Dict=512 , UpperCAmelCase_ : Optional[Any]=16 , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : str=0.02 , UpperCAmelCase_ : str=4 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_attention_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_choices def lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_attention_mask: snake_case_ = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = 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 , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Union[str, Any] = True __lowercase: int = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" snake_case_ = FlaxRoFormerModelTester(self ) @slow def lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=UpperCAmelCase_ ) snake_case_ = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCAmelCase_ ) @require_flax class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" snake_case_ = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) snake_case_ = jnp.array([[0, 1, 2, 3, 4, 5]] ) snake_case_ = model(UpperCAmelCase_ )[0] snake_case_ = 50_000 snake_case_ = (1, 6, vocab_size) self.assertEqual(output.shape , UpperCAmelCase_ ) snake_case_ = jnp.array( [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) )
347
0
import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import logging a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a , _a , _a , _a=False): try: import torch # noqa: F401 except ImportError: logger.error( "Loading a PyTorch model in Flax, requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions.") raise if not is_sharded: SCREAMING_SNAKE_CASE : str = os.path.abspath(_a) logger.info(f"Loading PyTorch weights from {pt_path}") SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(_a , map_location="cpu") logger.info(f"PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values()):,} parameters.") SCREAMING_SNAKE_CASE : str = convert_pytorch_state_dict_to_flax(_a , _a) else: # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files SCREAMING_SNAKE_CASE : List[str] = convert_pytorch_sharded_state_dict_to_flax(_a , _a) return flax_state_dict def lowerCamelCase__ ( _a , _a , _a , _a , ): def is_key_or_prefix_key_in_dict(_a) -> bool: return len(set(_a) & {key, (model_prefix,) + key}) > 0 # layer norm SCREAMING_SNAKE_CASE : Dict = pt_tuple_key[:-1] + ("scale",) if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(_a): return renamed_pt_tuple_key, pt_tensor # batch norm layer mean SCREAMING_SNAKE_CASE : Tuple = pt_tuple_key[:-1] + ("mean",) if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(_a): return renamed_pt_tuple_key, pt_tensor # batch norm layer var SCREAMING_SNAKE_CASE : List[str] = pt_tuple_key[:-1] + ("var",) if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(_a): return renamed_pt_tuple_key, pt_tensor # embedding SCREAMING_SNAKE_CASE : int = pt_tuple_key[:-1] + ("embedding",) if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(_a): return renamed_pt_tuple_key, pt_tensor # conv layer SCREAMING_SNAKE_CASE : Any = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(_a): SCREAMING_SNAKE_CASE : Optional[int] = pt_tensor.transpose(2 , 3 , 1 , 0) return renamed_pt_tuple_key, pt_tensor # linear layer SCREAMING_SNAKE_CASE : Union[str, Any] = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(_a): SCREAMING_SNAKE_CASE : Tuple = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight SCREAMING_SNAKE_CASE : Dict = pt_tuple_key[:-1] + ("weight",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias SCREAMING_SNAKE_CASE : List[str] = pt_tuple_key[:-1] + ("bias",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 SCREAMING_SNAKE_CASE : Optional[int] = None if pt_tuple_key[-3::2] == ("parametrizations", "original0"): SCREAMING_SNAKE_CASE : List[str] = pt_tuple_key[-2] + "_g" elif pt_tuple_key[-3::2] == ("parametrizations", "original1"): SCREAMING_SNAKE_CASE : Any = pt_tuple_key[-2] + "_v" if name is not None: SCREAMING_SNAKE_CASE : str = pt_tuple_key[:-3] + (name,) return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def lowerCamelCase__ ( _a , _a): # convert pytorch tensor to numpy SCREAMING_SNAKE_CASE : int = {k: v.numpy() for k, v in pt_state_dict.items()} SCREAMING_SNAKE_CASE : List[Any] = flax_model.base_model_prefix # use params dict if the model contains batch norm layers if "params" in flax_model.params: SCREAMING_SNAKE_CASE : Dict = flax_model.params["params"] else: SCREAMING_SNAKE_CASE : Union[str, Any] = flax_model.params SCREAMING_SNAKE_CASE : Optional[Any] = flatten_dict(_a) # add batch_stats keys,values to dict if "batch_stats" in flax_model.params: SCREAMING_SNAKE_CASE : int = flatten_dict(flax_model.params["batch_stats"]) random_flax_state_dict.update(_a) SCREAMING_SNAKE_CASE : Dict = {} SCREAMING_SNAKE_CASE : int = (model_prefix not in flax_model_params) and ( model_prefix in {k.split(".")[0] for k in pt_state_dict.keys()} ) SCREAMING_SNAKE_CASE : Union[str, Any] = (model_prefix in flax_model_params) and ( model_prefix not in {k.split(".")[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): SCREAMING_SNAKE_CASE : Optional[int] = tuple(pt_key.split(".")) # remove base model prefix if necessary SCREAMING_SNAKE_CASE : Dict = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: SCREAMING_SNAKE_CASE : Dict = pt_tuple_key[1:] # Correctly rename weight parameters SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : int = rename_key_and_reshape_tensor( _a , _a , _a , _a) # add model prefix if necessary SCREAMING_SNAKE_CASE : Optional[Any] = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: SCREAMING_SNAKE_CASE : Any = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.") # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1] or "var" in flax_key[-1]: SCREAMING_SNAKE_CASE : Dict = jnp.asarray(_a) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(_a , _a) continue # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE : List[Any] = jnp.asarray(_a) else: # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE : str = jnp.asarray(_a) return unflatten_dict(_a) def lowerCamelCase__ ( _a , _a): import torch # Load the index SCREAMING_SNAKE_CASE : int = {} for shard_file in shard_filenames: # load using msgpack utils SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(_a) SCREAMING_SNAKE_CASE : Tuple = {k: v.numpy() for k, v in pt_state_dict.items()} SCREAMING_SNAKE_CASE : Tuple = flax_model.base_model_prefix # use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict if "batch_stats" in flax_model.params: SCREAMING_SNAKE_CASE : str = flax_model.params["params"] SCREAMING_SNAKE_CASE : Union[str, Any] = flatten_dict(_a) random_flax_state_dict.update(flatten_dict(flax_model.params["batch_stats"])) else: SCREAMING_SNAKE_CASE : Any = flax_model.params SCREAMING_SNAKE_CASE : Tuple = flatten_dict(_a) SCREAMING_SNAKE_CASE : List[Any] = (model_prefix not in flax_model_params) and ( model_prefix in {k.split(".")[0] for k in pt_state_dict.keys()} ) SCREAMING_SNAKE_CASE : Union[str, Any] = (model_prefix in flax_model_params) and ( model_prefix not in {k.split(".")[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): SCREAMING_SNAKE_CASE : int = tuple(pt_key.split(".")) # remove base model prefix if necessary SCREAMING_SNAKE_CASE : Optional[int] = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: SCREAMING_SNAKE_CASE : Tuple = pt_tuple_key[1:] # Correctly rename weight parameters SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[int] = rename_key_and_reshape_tensor( _a , _a , _a , _a) # add model prefix if necessary SCREAMING_SNAKE_CASE : Optional[int] = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: SCREAMING_SNAKE_CASE : Optional[Any] = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.") # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1]: SCREAMING_SNAKE_CASE : Dict = jnp.asarray(_a) continue if "var" in flax_key[-1]: SCREAMING_SNAKE_CASE : Tuple = jnp.asarray(_a) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(_a , _a) continue # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE : int = jnp.asarray(_a) else: # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE : str = jnp.asarray(_a) return unflatten_dict(_a) def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : str = os.path.abspath(_a) logger.info(f"Loading Flax weights from {flax_checkpoint_path}") # import correct flax class SCREAMING_SNAKE_CASE : int = getattr(_a , "Flax" + model.__class__.__name__) # load flax weight dict with open(_a , "rb") as state_f: try: SCREAMING_SNAKE_CASE : str = from_bytes(_a , state_f.read()) except UnpicklingError: raise EnvironmentError(f"Unable to convert {flax_checkpoint_path} to Flax deserializable object. ") return load_flax_weights_in_pytorch_model(_a , _a) def lowerCamelCase__ ( _a , _a): try: import torch # noqa: F401 except ImportError: logger.error( "Loading a Flax weights in PyTorch, requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions.") raise # check if we have bf16 weights SCREAMING_SNAKE_CASE : int = flatten_dict(jax.tree_util.tree_map(lambda _a: x.dtype == jnp.bfloataa , _a)).values() if any(_a): # convert all weights to fp32 if the are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( "Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` " "before loading those in PyTorch model.") SCREAMING_SNAKE_CASE : Optional[Any] = jax.tree_util.tree_map( lambda _a: params.astype(np.floataa) if params.dtype == jnp.bfloataa else params , _a) SCREAMING_SNAKE_CASE : Optional[Any] = flatten_dict(_a) SCREAMING_SNAKE_CASE : Optional[int] = pt_model.state_dict() SCREAMING_SNAKE_CASE : Union[str, Any] = (pt_model.base_model_prefix in flax_state) and ( pt_model.base_model_prefix not in {k.split(".")[0] for k in pt_model_dict.keys()} ) SCREAMING_SNAKE_CASE : Dict = (pt_model.base_model_prefix not in flax_state) and ( pt_model.base_model_prefix in {k.split(".")[0] for k in pt_model_dict.keys()} ) # keep track of unexpected & missing keys SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : int = set(pt_model_dict.keys()) for flax_key_tuple, flax_tensor in flax_state_dict.items(): SCREAMING_SNAKE_CASE : Dict = flax_key_tuple[0] == pt_model.base_model_prefix SCREAMING_SNAKE_CASE : Union[str, Any] = ".".join((pt_model.base_model_prefix,) + flax_key_tuple) in pt_model_dict # adapt flax_key to prepare for loading from/to base model only if load_model_with_head_into_base_model and has_base_model_prefix: SCREAMING_SNAKE_CASE : Union[str, Any] = flax_key_tuple[1:] elif load_base_model_into_model_with_head and require_base_model_prefix: SCREAMING_SNAKE_CASE : Tuple = (pt_model.base_model_prefix,) + flax_key_tuple # rename flax weights to PyTorch format if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(_a) not in pt_model_dict: # conv layer SCREAMING_SNAKE_CASE : List[str] = flax_key_tuple[:-1] + ("weight",) SCREAMING_SNAKE_CASE : Tuple = jnp.transpose(_a , (3, 2, 0, 1)) elif flax_key_tuple[-1] == "kernel" and ".".join(_a) not in pt_model_dict: # linear layer SCREAMING_SNAKE_CASE : int = flax_key_tuple[:-1] + ("weight",) SCREAMING_SNAKE_CASE : Any = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: SCREAMING_SNAKE_CASE : Union[str, Any] = flax_key_tuple[:-1] + ("weight",) # adding batch stats from flax batch norm to pt elif "mean" in flax_key_tuple[-1]: SCREAMING_SNAKE_CASE : Union[str, Any] = flax_key_tuple[:-1] + ("running_mean",) elif "var" in flax_key_tuple[-1]: SCREAMING_SNAKE_CASE : Union[str, Any] = flax_key_tuple[:-1] + ("running_var",) if "batch_stats" in flax_state: SCREAMING_SNAKE_CASE : Dict = ".".join(flax_key_tuple[1:]) # Remove the params/batch_stats header else: SCREAMING_SNAKE_CASE : List[str] = ".".join(_a) # We also need to look at `pt_model_dict` and see if there are keys requiring further transformation. SCREAMING_SNAKE_CASE : Optional[int] = {} # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 for key in pt_model_dict: SCREAMING_SNAKE_CASE : int = key.split(".") SCREAMING_SNAKE_CASE : int = None if key_components[-3::2] == ["parametrizations", "original0"]: SCREAMING_SNAKE_CASE : Union[str, Any] = key_components[-2] + "_g" elif key_components[-3::2] == ["parametrizations", "original1"]: SCREAMING_SNAKE_CASE : Dict = key_components[-2] + "_v" if name is not None: SCREAMING_SNAKE_CASE : Optional[int] = key_components[:-3] + [name] SCREAMING_SNAKE_CASE : List[str] = ".".join(_a) SCREAMING_SNAKE_CASE : str = key if flax_key in special_pt_names: SCREAMING_SNAKE_CASE : Optional[Any] = special_pt_names[flax_key] if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected " f"to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.") else: # add weight to pytorch dict SCREAMING_SNAKE_CASE : Dict = np.asarray(_a) if not isinstance(_a , np.ndarray) else flax_tensor SCREAMING_SNAKE_CASE : int = torch.from_numpy(_a) # remove from missing keys missing_keys.remove(_a) else: # weight is not expected by PyTorch model unexpected_keys.append(_a) pt_model.load_state_dict(_a) # re-transform missing_keys to list SCREAMING_SNAKE_CASE : str = list(_a) if len(_a) > 0: logger.warning( "Some weights of the Flax model were not used when initializing the PyTorch model" f" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing" f" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture" " (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This" f" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect" " to be exactly identical (e.g. initializing a BertForSequenceClassification model from a" " FlaxBertForSequenceClassification model).") else: logger.warning(f"All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n") if len(_a) > 0: logger.warning( f"Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly" f" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to" " use it for predictions and inference.") else: logger.warning( f"All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n" "If your task is similar to the task the model of the checkpoint was trained on, " f"you can already use {pt_model.__class__.__name__} for predictions without further training.") return pt_model
76
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> bool: snake_case_ = get_failure_array(_SCREAMING_SNAKE_CASE ) # 2) Step through text searching for pattern snake_case_ , snake_case_ = 0, 0 # index into text, pattern while i < len(_SCREAMING_SNAKE_CASE ): if pattern[j] == text[i]: if j == (len(_SCREAMING_SNAKE_CASE ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: snake_case_ = failure[j - 1] continue i += 1 return False def _a ( _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = [0] snake_case_ = 0 snake_case_ = 1 while j < len(_SCREAMING_SNAKE_CASE ): if pattern[i] == pattern[j]: i += 1 elif i > 0: snake_case_ = failure[i - 1] continue j += 1 failure.append(_SCREAMING_SNAKE_CASE ) return failure if __name__ == "__main__": # Test 1) __SCREAMING_SNAKE_CASE : Optional[int] = 'abc1abc12' __SCREAMING_SNAKE_CASE : Optional[int] = 'alskfjaldsabc1abc1abc12k23adsfabcabc' __SCREAMING_SNAKE_CASE : List[str] = 'alskfjaldsk23adsfabcabc' assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) __SCREAMING_SNAKE_CASE : int = 'ABABX' __SCREAMING_SNAKE_CASE : Optional[Any] = 'ABABZABABYABABX' assert kmp(pattern, text) # Test 3) __SCREAMING_SNAKE_CASE : Any = 'AAAB' __SCREAMING_SNAKE_CASE : List[Any] = 'ABAAAAAB' assert kmp(pattern, text) # Test 4) __SCREAMING_SNAKE_CASE : Optional[int] = 'abcdabcy' __SCREAMING_SNAKE_CASE : str = 'abcxabcdabxabcdabcdabcy' assert kmp(pattern, text) # Test 5) __SCREAMING_SNAKE_CASE : Any = 'aabaabaaa' assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
347
0
"""simple docstring""" # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _UpperCamelCase : Optional[Any] = {"configuration_mra": ["MRA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MraConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase : Any = [ "MRA_PRETRAINED_MODEL_ARCHIVE_LIST", "MraForMaskedLM", "MraForMultipleChoice", "MraForQuestionAnswering", "MraForSequenceClassification", "MraForTokenClassification", "MraLayer", "MraModel", "MraPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mra import ( MRA_PRETRAINED_MODEL_ARCHIVE_LIST, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraLayer, MraModel, MraPreTrainedModel, ) else: import sys _UpperCamelCase : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure)
77
"""simple docstring""" from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class __A (snake_case__): '''simple docstring''' @slow @require_torch def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = EncoderDecoderModel.from_encoder_decoder_pretrained("""prajjwal1/bert-tiny""" , """prajjwal1/bert-tiny""" ) snake_case_ = BertTokenizer.from_pretrained("""bert-base-uncased""" ) snake_case_ = bertabert.config.encoder.vocab_size snake_case_ = tokenizer.sep_token_id snake_case_ = tokenizer.cls_token_id snake_case_ = 128 snake_case_ = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""train[:1%]""" ) snake_case_ = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""validation[:1%]""" ) snake_case_ = train_dataset.select(range(32 ) ) snake_case_ = val_dataset.select(range(16 ) ) snake_case_ = 4 def _map_to_encoder_decoder_inputs(UpperCAmelCase_ : int ): # Tokenizer will automatically set [BOS] <text> [EOS] snake_case_ = tokenizer(batch["""article"""] , padding="""max_length""" , truncation=UpperCAmelCase_ , max_length=512 ) snake_case_ = tokenizer(batch["""highlights"""] , padding="""max_length""" , truncation=UpperCAmelCase_ , max_length=128 ) snake_case_ = inputs.input_ids snake_case_ = inputs.attention_mask snake_case_ = outputs.input_ids snake_case_ = outputs.input_ids.copy() snake_case_ = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["""labels"""] ] snake_case_ = outputs.attention_mask assert all(len(UpperCAmelCase_ ) == 512 for x in inputs.input_ids ) assert all(len(UpperCAmelCase_ ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(UpperCAmelCase_ : Union[str, Any] ): snake_case_ = pred.label_ids snake_case_ = pred.predictions # all unnecessary tokens are removed snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = sum([int(pred_str[i] == label_str[i] ) for i in range(len(UpperCAmelCase_ ) )] ) / len(UpperCAmelCase_ ) return {"accuracy": accuracy} # map train dataset snake_case_ = train_dataset.map( _map_to_encoder_decoder_inputs , batched=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , remove_columns=["""article""", """highlights"""] , ) train_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) # same for validation dataset snake_case_ = val_dataset.map( _map_to_encoder_decoder_inputs , batched=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , remove_columns=["""article""", """highlights"""] , ) val_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) snake_case_ = self.get_auto_remove_tmp_dir() snake_case_ = SeqaSeqTrainingArguments( output_dir=UpperCAmelCase_ , per_device_train_batch_size=UpperCAmelCase_ , per_device_eval_batch_size=UpperCAmelCase_ , predict_with_generate=UpperCAmelCase_ , evaluation_strategy="""steps""" , do_train=UpperCAmelCase_ , do_eval=UpperCAmelCase_ , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer snake_case_ = SeqaSeqTrainer( model=UpperCAmelCase_ , args=UpperCAmelCase_ , compute_metrics=_compute_metrics , train_dataset=UpperCAmelCase_ , eval_dataset=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ , ) # start training trainer.train()
347
0
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() snake_case_ = logging.get_logger(__name__) snake_case_ = { """post_extract_proj""": """feature_projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.upsample.0""": """encoder.upsample.projection""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """layer_norm""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } def _lowerCAmelCase ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ): for attribute in key.split('.' ): UpperCAmelCase = getattr(lowercase_ , lowercase_ ) if weight_type is not None: UpperCAmelCase = getattr(lowercase_ , lowercase_ ).shape else: UpperCAmelCase = hf_pointer.shape assert hf_shape == value.shape, ( F"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": UpperCAmelCase = value elif weight_type == "weight_g": UpperCAmelCase = value elif weight_type == "weight_v": UpperCAmelCase = value elif weight_type == "bias": UpperCAmelCase = value else: UpperCAmelCase = value logger.info(F"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def _lowerCAmelCase ( lowercase_ , lowercase_ , lowercase_ ): UpperCAmelCase = [] UpperCAmelCase = fairseq_model.state_dict() UpperCAmelCase = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): UpperCAmelCase = False if "conv_layers" in name: load_conv_layer( lowercase_ , lowercase_ , lowercase_ , lowercase_ , hf_model.config.feat_extract_norm == 'group' , ) UpperCAmelCase = True else: for key, mapped_key in MAPPING.items(): UpperCAmelCase = 'sew.' + mapped_key if (is_finetuned and mapped_key != 'lm_head') else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: UpperCAmelCase = True if "*" in mapped_key: UpperCAmelCase = name.split(lowercase_ )[0].split('.' )[-2] UpperCAmelCase = mapped_key.replace('*' , lowercase_ ) if "weight_g" in name: UpperCAmelCase = 'weight_g' elif "weight_v" in name: UpperCAmelCase = 'weight_v' elif "weight" in name: UpperCAmelCase = 'weight' elif "bias" in name: UpperCAmelCase = 'bias' else: UpperCAmelCase = None set_recursively(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) continue if not is_used: unused_weights.append(lowercase_ ) logger.warning(F"""Unused weights: {unused_weights}""" ) def _lowerCAmelCase ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ): UpperCAmelCase = full_name.split('conv_layers.' )[-1] UpperCAmelCase = name.split('.' ) UpperCAmelCase = int(items[0] ) UpperCAmelCase = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) UpperCAmelCase = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) UpperCAmelCase = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) UpperCAmelCase = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) UpperCAmelCase = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(lowercase_ ) def _lowerCAmelCase ( lowercase_ , lowercase_ ): UpperCAmelCase = SEWConfig() if is_finetuned: UpperCAmelCase = model.wav_encoder.wav_model.cfg else: UpperCAmelCase = model.cfg UpperCAmelCase = fs_config.conv_bias UpperCAmelCase = eval(fs_config.conv_feature_layers ) UpperCAmelCase = [x[0] for x in conv_layers] UpperCAmelCase = [x[1] for x in conv_layers] UpperCAmelCase = [x[2] for x in conv_layers] UpperCAmelCase = 'gelu' UpperCAmelCase = 'layer' if fs_config.extractor_mode == 'layer_norm' else 'group' UpperCAmelCase = 0.0 UpperCAmelCase = fs_config.activation_fn.name UpperCAmelCase = fs_config.encoder_embed_dim UpperCAmelCase = 0.0_2 UpperCAmelCase = fs_config.encoder_ffn_embed_dim UpperCAmelCase = 1e-5 UpperCAmelCase = fs_config.encoder_layerdrop UpperCAmelCase = fs_config.encoder_attention_heads UpperCAmelCase = fs_config.conv_pos_groups UpperCAmelCase = fs_config.conv_pos UpperCAmelCase = len(lowercase_ ) UpperCAmelCase = fs_config.encoder_layers UpperCAmelCase = fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: UpperCAmelCase = model.cfg UpperCAmelCase = fs_config.final_dropout UpperCAmelCase = fs_config.layerdrop UpperCAmelCase = fs_config.activation_dropout UpperCAmelCase = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 UpperCAmelCase = fs_config.attention_dropout UpperCAmelCase = fs_config.dropout_input UpperCAmelCase = fs_config.dropout UpperCAmelCase = fs_config.mask_channel_length UpperCAmelCase = fs_config.mask_channel_prob UpperCAmelCase = fs_config.mask_length UpperCAmelCase = fs_config.mask_prob UpperCAmelCase = 'Wav2Vec2FeatureExtractor' UpperCAmelCase = 'Wav2Vec2CTCTokenizer' return config @torch.no_grad() def _lowerCAmelCase ( lowercase_ , lowercase_ , lowercase_=None , lowercase_=None , lowercase_=True ): if is_finetuned: UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) if config_path is not None: UpperCAmelCase = SEWConfig.from_pretrained(lowercase_ ) else: UpperCAmelCase = convert_config(model[0] , lowercase_ ) UpperCAmelCase = model[0].eval() UpperCAmelCase = True if config.feat_extract_norm == 'layer' else False UpperCAmelCase = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=lowercase_ , return_attention_mask=lowercase_ , ) if is_finetuned: if dict_path: UpperCAmelCase = Dictionary.load(lowercase_ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq UpperCAmelCase = target_dict.pad_index UpperCAmelCase = target_dict.bos_index UpperCAmelCase = target_dict.pad_index UpperCAmelCase = target_dict.bos_index UpperCAmelCase = target_dict.eos_index UpperCAmelCase = len(target_dict.symbols ) UpperCAmelCase = os.path.join(lowercase_ , 'vocab.json' ) if not os.path.isdir(lowercase_ ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(lowercase_ ) ) return os.makedirs(lowercase_ , exist_ok=lowercase_ ) with open(lowercase_ , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(target_dict.indices , lowercase_ ) UpperCAmelCase = WavaVecaCTCTokenizer( lowercase_ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=lowercase_ , ) UpperCAmelCase = WavaVecaProcessor(feature_extractor=lowercase_ , tokenizer=lowercase_ ) processor.save_pretrained(lowercase_ ) UpperCAmelCase = SEWForCTC(lowercase_ ) else: UpperCAmelCase = SEWModel(lowercase_ ) feature_extractor.save_pretrained(lowercase_ ) recursively_load_weights(lowercase_ , lowercase_ , lowercase_ ) hf_model.save_pretrained(lowercase_ ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--is_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) snake_case_ = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
78
"""simple docstring""" # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys __SCREAMING_SNAKE_CASE : Tuple = subprocess.check_output('git merge-base main HEAD'.split()).decode('utf-8') __SCREAMING_SNAKE_CASE : Tuple = subprocess.check_output(f"""git diff --name-only {fork_point_sha}""".split()).decode('utf-8').split() __SCREAMING_SNAKE_CASE : Any = '|'.join(sys.argv[1:]) __SCREAMING_SNAKE_CASE : Optional[Any] = re.compile(Rf"""^({joined_dirs}).*?\.py$""") __SCREAMING_SNAKE_CASE : List[str] = [x for x in modified_files if regex.match(x)] print(' '.join(relevant_modified_files), end='')
347
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : int ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowerCAmelCase ( self : Dict ): '''simple docstring''' _A = 1 _A = 3 _A = (32, 32) _A = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(__UpperCAmelCase ) return image @property def lowerCAmelCase ( self : str ): '''simple docstring''' torch.manual_seed(0 ) _A = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) return model @property def lowerCAmelCase ( self : List[str] ): '''simple docstring''' torch.manual_seed(0 ) _A = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def lowerCAmelCase ( self : Any ): '''simple docstring''' torch.manual_seed(0 ) _A = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5006 , ) return RobertaSeriesModelWithTransformation(__UpperCAmelCase ) @property def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' def extract(*__UpperCAmelCase : str , **__UpperCAmelCase : List[Any] ): class _UpperCAmelCase : """simple docstring""" def __init__( self : str ): '''simple docstring''' _A = torch.ones([0] ) def lowerCAmelCase ( self : str , __UpperCAmelCase : List[Any] ): '''simple docstring''' self.pixel_values.to(__UpperCAmelCase ) return self return Out() return extract def lowerCAmelCase ( self : List[str] ): '''simple docstring''' _A = "cpu" # ensure determinism for the device-dependent torch.Generator _A = self.dummy_cond_unet _A = PNDMScheduler(skip_prk_steps=__UpperCAmelCase ) _A = self.dummy_vae _A = self.dummy_text_encoder _A = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) _A = 77 _A = self.dummy_image.to(__UpperCAmelCase ) _A = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk _A = AltDiffusionImgaImgPipeline( unet=__UpperCAmelCase , scheduler=__UpperCAmelCase , vae=__UpperCAmelCase , text_encoder=__UpperCAmelCase , tokenizer=__UpperCAmelCase , safety_checker=__UpperCAmelCase , feature_extractor=self.dummy_extractor , ) _A = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__UpperCAmelCase ) _A = alt_pipe.to(__UpperCAmelCase ) alt_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) _A = "A painting of a squirrel eating a burger" _A = torch.Generator(device=__UpperCAmelCase ).manual_seed(0 ) _A = alt_pipe( [prompt] , generator=__UpperCAmelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=__UpperCAmelCase , ) _A = output.images _A = torch.Generator(device=__UpperCAmelCase ).manual_seed(0 ) _A = alt_pipe( [prompt] , generator=__UpperCAmelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=__UpperCAmelCase , return_dict=__UpperCAmelCase , )[0] _A = image[0, -3:, -3:, -1] _A = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _A = np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5E-3 @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' _A = self.dummy_cond_unet _A = PNDMScheduler(skip_prk_steps=__UpperCAmelCase ) _A = self.dummy_vae _A = self.dummy_text_encoder _A = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) _A = 77 _A = self.dummy_image.to(__UpperCAmelCase ) # put models in fp16 _A = unet.half() _A = vae.half() _A = bert.half() # make sure here that pndm scheduler skips prk _A = AltDiffusionImgaImgPipeline( unet=__UpperCAmelCase , scheduler=__UpperCAmelCase , vae=__UpperCAmelCase , text_encoder=__UpperCAmelCase , tokenizer=__UpperCAmelCase , safety_checker=__UpperCAmelCase , feature_extractor=self.dummy_extractor , ) _A = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__UpperCAmelCase ) _A = alt_pipe.to(__UpperCAmelCase ) alt_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) _A = "A painting of a squirrel eating a burger" _A = torch.manual_seed(0 ) _A = alt_pipe( [prompt] , generator=__UpperCAmelCase , num_inference_steps=2 , output_type="np" , image=__UpperCAmelCase , ).images assert image.shape == (1, 32, 32, 3) @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' _A = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) # resize to resolution that is divisible by 8 but not 16 or 32 _A = init_image.resize((760, 504) ) _A = "BAAI/AltDiffusion" _A = AltDiffusionImgaImgPipeline.from_pretrained( __UpperCAmelCase , safety_checker=__UpperCAmelCase , ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) pipe.enable_attention_slicing() _A = "A fantasy landscape, trending on artstation" _A = torch.manual_seed(0 ) _A = pipe( prompt=__UpperCAmelCase , image=__UpperCAmelCase , strength=0.75 , guidance_scale=7.5 , generator=__UpperCAmelCase , output_type="np" , ) _A = output.images[0] _A = image[255:258, 383:386, -1] assert image.shape == (504, 760, 3) _A = np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : int ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : int ): '''simple docstring''' _A = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) _A = init_image.resize((768, 512) ) _A = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy" ) _A = "BAAI/AltDiffusion" _A = AltDiffusionImgaImgPipeline.from_pretrained( __UpperCAmelCase , safety_checker=__UpperCAmelCase , ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) pipe.enable_attention_slicing() _A = "A fantasy landscape, trending on artstation" _A = torch.manual_seed(0 ) _A = pipe( prompt=__UpperCAmelCase , image=__UpperCAmelCase , strength=0.75 , guidance_scale=7.5 , generator=__UpperCAmelCase , output_type="np" , ) _A = output.images[0] assert image.shape == (512, 768, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1E-2
79
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } __SCREAMING_SNAKE_CASE : List[Any] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = {} with open(_SCREAMING_SNAKE_CASE , """r""" ) as file: for line_number, line in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = line.strip() if line: snake_case_ = line.split() snake_case_ = line_number snake_case_ = words[0] snake_case_ = value return result def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: for attribute in key.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(_SCREAMING_SNAKE_CASE ): snake_case_ = PARAM_MAPPING[full_name.split(""".""" )[-1]] snake_case_ = """param""" if weight_type is not None and weight_type != "param": snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape elif weight_type is not None and weight_type == "param": snake_case_ = hf_pointer for attribute in hf_param_name.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = shape_pointer.shape # let's reduce dimension snake_case_ = value[0] else: snake_case_ = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": snake_case_ = value elif weight_type == "weight_g": snake_case_ = value elif weight_type == "weight_v": snake_case_ = value elif weight_type == "bias": snake_case_ = value elif weight_type == "param": for attribute in hf_param_name.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = value else: snake_case_ = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(_SCREAMING_SNAKE_CASE ): snake_case_ = PARAM_MAPPING[full_name.split(""".""" )[-1]] snake_case_ = """param""" if weight_type is not None and weight_type != "param": snake_case_ = """.""".join([key, weight_type] ) elif weight_type is not None and weight_type == "param": snake_case_ = """.""".join([key, hf_param_name] ) else: snake_case_ = key snake_case_ = value if """lm_head""" in full_key else value[0] __SCREAMING_SNAKE_CASE : int = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> List[str]: snake_case_ = False for key, mapped_key in MAPPING.items(): snake_case_ = """wav2vec2.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: snake_case_ = True if "*" in mapped_key: snake_case_ = name.split(_SCREAMING_SNAKE_CASE )[0].split(""".""" )[-2] snake_case_ = mapped_key.replace("""*""" , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: snake_case_ = """weight_g""" elif "weight_v" in name: snake_case_ = """weight_v""" elif "bias" in name: snake_case_ = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj snake_case_ = """weight""" else: snake_case_ = None if hf_dict is not None: rename_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return is_used return is_used def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = [] snake_case_ = fairseq_model.state_dict() snake_case_ = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): snake_case_ = False if "conv_layers" in name: load_conv_layer( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == """group""" , ) snake_case_ = True else: snake_case_ = load_wavaveca_layer(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(f"""Unused weights: {unused_weights}""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = full_name.split("""conv_layers.""" )[-1] snake_case_ = name.split(""".""" ) snake_case_ = int(items[0] ) snake_case_ = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_SCREAMING_SNAKE_CASE ) @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False ) -> int: if config_path is not None: snake_case_ = WavaVecaConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) else: snake_case_ = WavaVecaConfig() if is_seq_class: snake_case_ = read_txt_into_dict(_SCREAMING_SNAKE_CASE ) snake_case_ = idalabel snake_case_ = WavaVecaForSequenceClassification(_SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) elif is_finetuned: if dict_path: snake_case_ = Dictionary.load(_SCREAMING_SNAKE_CASE ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq snake_case_ = target_dict.pad_index snake_case_ = target_dict.bos_index snake_case_ = target_dict.eos_index snake_case_ = len(target_dict.symbols ) snake_case_ = os.path.join(_SCREAMING_SNAKE_CASE , """vocab.json""" ) if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) ) return os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) snake_case_ = target_dict.indices # fairseq has the <pad> and <s> switched snake_case_ = 0 snake_case_ = 1 with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaCTCTokenizer( _SCREAMING_SNAKE_CASE , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=_SCREAMING_SNAKE_CASE , ) snake_case_ = True if config.feat_extract_norm == """layer""" else False snake_case_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) snake_case_ = WavaVecaProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaForCTC(_SCREAMING_SNAKE_CASE ) else: snake_case_ = WavaVecaForPreTraining(_SCREAMING_SNAKE_CASE ) if is_finetuned or is_seq_class: snake_case_ , snake_case_ , snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: snake_case_ = argparse.Namespace(task="""audio_pretraining""" ) snake_case_ = fairseq.tasks.setup_task(_SCREAMING_SNAKE_CASE ) snake_case_ , snake_case_ , snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=_SCREAMING_SNAKE_CASE ) snake_case_ = model[0].eval() recursively_load_weights(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , not is_finetuned ) hf_wavavec.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) __SCREAMING_SNAKE_CASE : Any = parser.parse_args() __SCREAMING_SNAKE_CASE : List[Any] = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
347
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL a__ : Optional[int] = logging.get_logger(__name__) def _UpperCamelCase ( __A , __A ) -> str: '''simple docstring''' UpperCamelCase__ = b.T UpperCamelCase__ = np.sum(np.square(__A ) , axis=1 ) UpperCamelCase__ = np.sum(np.square(__A ) , axis=0 ) UpperCamelCase__ = np.matmul(__A , __A ) UpperCamelCase__ = aa[:, None] - 2 * ab + ba[None, :] return d def _UpperCamelCase ( __A , __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = x.reshape(-1 , 3 ) UpperCamelCase__ = squared_euclidean_distance(__A , __A ) return np.argmin(__A , axis=1 ) class lowercase_ ( a__ ): __UpperCAmelCase = ['pixel_values'] def __init__( self , a = None , a = True , a = None , a = PILImageResampling.BILINEAR , a = True , a = True , **a , ): super().__init__(**a ) UpperCamelCase__ = size if size is not None else {"height": 2_56, "width": 2_56} UpperCamelCase__ = get_size_dict(a ) UpperCamelCase__ = np.array(a ) if clusters is not None else None UpperCamelCase__ = do_resize UpperCamelCase__ = size UpperCamelCase__ = resample UpperCamelCase__ = do_normalize UpperCamelCase__ = do_color_quantize def __a ( self , a , a , a = PILImageResampling.BILINEAR , a = None , **a , ): UpperCamelCase__ = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(f'''Size dictionary must contain both height and width keys. Got {size.keys()}''' ) return resize( a , size=(size["height"], size["width"]) , resample=a , data_format=a , **a ) def __a ( self , a , a = None , ): UpperCamelCase__ = rescale(image=a , scale=1 / 127.5 , data_format=a ) UpperCamelCase__ = image - 1 return image def __a ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ): UpperCamelCase__ = do_resize if do_resize is not None else self.do_resize UpperCamelCase__ = size if size is not None else self.size UpperCamelCase__ = get_size_dict(a ) UpperCamelCase__ = resample if resample is not None else self.resample UpperCamelCase__ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase__ = do_color_quantize if do_color_quantize is not None else self.do_color_quantize UpperCamelCase__ = clusters if clusters is not None else self.clusters UpperCamelCase__ = np.array(a ) UpperCamelCase__ = make_list_of_images(a ) if not valid_images(a ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_color_quantize and clusters is None: raise ValueError("Clusters must be specified if do_color_quantize is True." ) # All transformations expect numpy arrays. UpperCamelCase__ = [to_numpy_array(a ) for image in images] if do_resize: UpperCamelCase__ = [self.resize(image=a , size=a , resample=a ) for image in images] if do_normalize: UpperCamelCase__ = [self.normalize(image=a ) for image in images] if do_color_quantize: UpperCamelCase__ = [to_channel_dimension_format(a , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) UpperCamelCase__ = np.array(a ) UpperCamelCase__ = color_quantize(a , a ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) UpperCamelCase__ = images.shape[0] UpperCamelCase__ = images.reshape(a , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. UpperCamelCase__ = list(a ) else: UpperCamelCase__ = [to_channel_dimension_format(a , a ) for image in images] UpperCamelCase__ = {"input_ids": images} return BatchFeature(data=a , tensor_type=a )
80
"""simple docstring""" import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class __A : '''simple docstring''' def __init__( self : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any=14 , UpperCAmelCase_ : Union[str, Any]=7 , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : str=99 , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : List[Any]=4 , UpperCAmelCase_ : Optional[int]=4 , UpperCAmelCase_ : int=4 , UpperCAmelCase_ : str=37 , UpperCAmelCase_ : Any="gelu" , UpperCAmelCase_ : str=0.1 , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : int=512 , UpperCAmelCase_ : Tuple=0.02 , ) ->List[str]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = rotary_dim snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = initializer_range snake_case_ = None snake_case_ = vocab_size - 1 snake_case_ = vocab_size - 1 snake_case_ = vocab_size - 1 def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_input_mask: snake_case_ = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=UpperCAmelCase_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""input_ids""": input_ids, """attention_mask""": attention_mask} return config, inputs_dict def lowerCAmelCase ( self : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict ) ->Tuple: """simple docstring""" snake_case_ = 20 snake_case_ = model_class_name(UpperCAmelCase_ ) snake_case_ = model.init_cache(input_ids.shape[0] , UpperCAmelCase_ ) snake_case_ = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) snake_case_ = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) snake_case_ = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) snake_case_ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="""i4""" ) snake_case_ = model( input_ids[:, -1:] , attention_mask=UpperCAmelCase_ , past_key_values=outputs_cache.past_key_values , position_ids=UpperCAmelCase_ , ) snake_case_ = model(UpperCAmelCase_ ) snake_case_ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = 20 snake_case_ = model_class_name(UpperCAmelCase_ ) snake_case_ = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) snake_case_ = model.init_cache(input_ids.shape[0] , UpperCAmelCase_ ) snake_case_ = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) snake_case_ = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) snake_case_ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="""i4""" ) snake_case_ = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) snake_case_ = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ ) snake_case_ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) @require_flax class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Any = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () __lowercase: List[str] = (FlaxGPTJForCausalLM,) if is_flax_available() else () def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = FlaxGPTJModelTester(self ) def lowerCAmelCase ( self : int ) ->List[Any]: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ , snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : List[str] ) ->Any: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ , snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) @tooslow def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" snake_case_ = GPTaTokenizer.from_pretrained("""gpt2""" , pad_token="""<|endoftext|>""" , padding_side="""left""" ) snake_case_ = tokenizer(["""Hello this is a long string""", """Hey"""] , return_tensors="""np""" , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ ) snake_case_ = FlaxGPTJForCausalLM.from_pretrained("""EleutherAI/gpt-j-6B""" ) snake_case_ = False snake_case_ = model.config.eos_token_id snake_case_ = jax.jit(model.generate ) snake_case_ = jit_generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , pad_token_id=tokenizer.pad_token_id ).sequences snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = [ """Hello this is a long string of text.\n\nI'm trying to get the text of the""", """Hey, I'm a little late to the party. I'm going to""", ] self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) @is_pt_flax_cross_test def lowerCAmelCase ( self : int ) ->str: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class snake_case_ = model_class.__name__[4:] # Skip the "Flax" at the beginning snake_case_ = getattr(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ , snake_case_ = pt_inputs["""input_ids"""].shape snake_case_ = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCAmelCase_ ): snake_case_ = 0 snake_case_ = 1 snake_case_ = 0 snake_case_ = 1 snake_case_ = pt_model_class(UpperCAmelCase_ ).eval() snake_case_ = model_class(UpperCAmelCase_ , dtype=jnp.floataa ) snake_case_ = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , UpperCAmelCase_ ) snake_case_ = fx_state with torch.no_grad(): snake_case_ = pt_model(**UpperCAmelCase_ ).to_tuple() snake_case_ = fx_model(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(UpperCAmelCase_ ) snake_case_ = model_class.from_pretrained(UpperCAmelCase_ , from_pt=UpperCAmelCase_ ) snake_case_ = fx_model_loaded(**UpperCAmelCase_ ).to_tuple() self.assertEqual( len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output_loaded, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class snake_case_ = model_class.__name__[4:] # Skip the "Flax" at the beginning snake_case_ = getattr(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = pt_model_class(UpperCAmelCase_ ).eval() snake_case_ = model_class(UpperCAmelCase_ , dtype=jnp.floataa ) snake_case_ = load_flax_weights_in_pytorch_model(UpperCAmelCase_ , fx_model.params ) snake_case_ , snake_case_ = pt_inputs["""input_ids"""].shape snake_case_ = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCAmelCase_ ): snake_case_ = 0 snake_case_ = 1 snake_case_ = 0 snake_case_ = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): snake_case_ = pt_model(**UpperCAmelCase_ ).to_tuple() snake_case_ = fx_model(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(UpperCAmelCase_ ) snake_case_ = pt_model_class.from_pretrained(UpperCAmelCase_ , from_flax=UpperCAmelCase_ ) with torch.no_grad(): snake_case_ = pt_model_loaded(**UpperCAmelCase_ ).to_tuple() self.assertEqual( len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ = model_class_name.from_pretrained("""EleutherAI/gpt-j-6B""" ) snake_case_ = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCAmelCase_ )
347
0
"""simple docstring""" from __future__ import annotations import math from collections.abc import Callable def _A ( lowercase , lowercase , lowercase , lowercase = 1_00 , ): """simple docstring""" a =x_start a =fnc(lowercase ) a =0.0 for _ in range(lowercase ): # Approximates curve as a sequence of linear lines and sums their length a =(x_end - x_start) / steps + xa a =fnc(lowercase ) length += math.hypot(xa - xa , fxa - fxa ) # Increment step a =xa a =fxa return length if __name__ == "__main__": def _A ( lowercase ): """simple docstring""" return math.sin(10 * x ) print("""f(x) = sin(10 * x)""") print("""The length of the curve from x = -10 to x = 10 is:""") lowerCamelCase_ : Tuple = 1_0 while i <= 1_0_0_0_0_0: print(F'With {i} steps: {line_length(f, -1_0, 1_0, i)}') i *= 1_0
81
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING __SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) class __A (snake_case__): '''simple docstring''' __lowercase: int = """upernet""" def __init__( self : str , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : str=512 , UpperCAmelCase_ : int=0.02 , UpperCAmelCase_ : Optional[Any]=[1, 2, 3, 6] , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Tuple=0.4 , UpperCAmelCase_ : Tuple=384 , UpperCAmelCase_ : Union[str, Any]=256 , UpperCAmelCase_ : str=1 , UpperCAmelCase_ : Tuple=False , UpperCAmelCase_ : Tuple=255 , **UpperCAmelCase_ : Dict , ) ->Union[str, Any]: """simple docstring""" super().__init__(**UpperCAmelCase_ ) if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) snake_case_ = CONFIG_MAPPING["""resnet"""](out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = backbone_config.get("""model_type""" ) snake_case_ = CONFIG_MAPPING[backbone_model_type] snake_case_ = config_class.from_dict(UpperCAmelCase_ ) snake_case_ = backbone_config snake_case_ = hidden_size snake_case_ = initializer_range snake_case_ = pool_scales snake_case_ = use_auxiliary_head snake_case_ = auxiliary_loss_weight snake_case_ = auxiliary_in_channels snake_case_ = auxiliary_channels snake_case_ = auxiliary_num_convs snake_case_ = auxiliary_concat_input snake_case_ = loss_ignore_index def lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.backbone_config.to_dict() snake_case_ = self.__class__.model_type return output
347
0
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin A__ = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right A__ = 25_00_04 A__ = 25_00_20 @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase = MBartTokenizer __lowerCamelCase = MBartTokenizerFast __lowerCamelCase = True __lowerCamelCase = True def snake_case ( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing _lowerCAmelCase = MBartTokenizer(_snake_case , keep_accents=_snake_case ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case ( self ): """simple docstring""" _lowerCAmelCase = MBartTokenizer(_snake_case , keep_accents=_snake_case ) _lowerCAmelCase = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(_snake_case , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_snake_case ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) _lowerCAmelCase = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( _snake_case , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) _lowerCAmelCase = tokenizer.convert_tokens_to_ids(_snake_case ) self.assertListEqual( _snake_case , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) _lowerCAmelCase = tokenizer.convert_ids_to_tokens(_snake_case ) self.assertListEqual( _snake_case , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def snake_case ( self ): """simple docstring""" if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return _lowerCAmelCase = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-mbart""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): _lowerCAmelCase = self.rust_tokenizer_class.from_pretrained(_snake_case , **_snake_case ) _lowerCAmelCase = self.tokenizer_class.from_pretrained(_snake_case , **_snake_case ) _lowerCAmelCase = tempfile.mkdtemp() _lowerCAmelCase = tokenizer_r.save_pretrained(_snake_case ) _lowerCAmelCase = tokenizer_p.save_pretrained(_snake_case ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) _lowerCAmelCase = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(_snake_case , _snake_case ) # Checks everything loads correctly in the same way _lowerCAmelCase = tokenizer_r.from_pretrained(_snake_case ) _lowerCAmelCase = tokenizer_p.from_pretrained(_snake_case ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_snake_case , _snake_case ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(_snake_case ) # Save tokenizer rust, legacy_format=True _lowerCAmelCase = tempfile.mkdtemp() _lowerCAmelCase = tokenizer_r.save_pretrained(_snake_case , legacy_format=_snake_case ) _lowerCAmelCase = tokenizer_p.save_pretrained(_snake_case ) # Checks it save with the same files self.assertSequenceEqual(_snake_case , _snake_case ) # Checks everything loads correctly in the same way _lowerCAmelCase = tokenizer_r.from_pretrained(_snake_case ) _lowerCAmelCase = tokenizer_p.from_pretrained(_snake_case ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_snake_case , _snake_case ) ) shutil.rmtree(_snake_case ) # Save tokenizer rust, legacy_format=False _lowerCAmelCase = tempfile.mkdtemp() _lowerCAmelCase = tokenizer_r.save_pretrained(_snake_case , legacy_format=_snake_case ) _lowerCAmelCase = tokenizer_p.save_pretrained(_snake_case ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way _lowerCAmelCase = tokenizer_r.from_pretrained(_snake_case ) _lowerCAmelCase = tokenizer_p.from_pretrained(_snake_case ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_snake_case , _snake_case ) ) shutil.rmtree(_snake_case ) @require_torch @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( unittest.TestCase ): __lowerCamelCase = '''facebook/mbart-large-en-ro''' __lowerCamelCase = [ ''' UN Chief Says There Is No Military Solution in Syria''', ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.''', ] __lowerCamelCase = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei''' ''' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor''' ''' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''', ] __lowerCamelCase = [8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2, EN_CODE] @classmethod def snake_case ( cls ): """simple docstring""" _lowerCAmelCase = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""en_XX""" , tgt_lang="""ro_RO""" ) _lowerCAmelCase = 1 return cls def snake_case ( self ): """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ar_AR"""] , 250001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""en_EN"""] , 250004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ro_RO"""] , 250020 ) def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , _snake_case ) def snake_case ( self ): """simple docstring""" self.assertIn(_snake_case , self.tokenizer.all_special_ids ) _lowerCAmelCase = [RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2] _lowerCAmelCase = self.tokenizer.decode(_snake_case , skip_special_tokens=_snake_case ) _lowerCAmelCase = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=_snake_case ) self.assertEqual(_snake_case , _snake_case ) self.assertNotIn(self.tokenizer.eos_token , _snake_case ) def snake_case ( self ): """simple docstring""" _lowerCAmelCase = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , _snake_case ) _lowerCAmelCase = 10 _lowerCAmelCase = self.tokenizer(_snake_case , max_length=_snake_case , truncation=_snake_case ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , _snake_case ) self.assertEqual(len(_snake_case ) , _snake_case ) def snake_case ( self ): """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [250026, 250001] ) def snake_case ( self ): """simple docstring""" _lowerCAmelCase = tempfile.mkdtemp() _lowerCAmelCase = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(_snake_case ) _lowerCAmelCase = MBartTokenizer.from_pretrained(_snake_case ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , _snake_case ) @require_torch def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=_snake_case , return_tensors="""pt""" ) _lowerCAmelCase = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=_snake_case , truncation=_snake_case , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) _lowerCAmelCase = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) self.assertIsInstance(_snake_case , _snake_case ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) _lowerCAmelCase = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , _snake_case ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.tokenizer(self.src_text , padding=_snake_case , truncation=_snake_case , max_length=3 , return_tensors="""pt""" ) _lowerCAmelCase = self.tokenizer( text_target=self.tgt_text , padding=_snake_case , truncation=_snake_case , max_length=10 , return_tensors="""pt""" ) _lowerCAmelCase = targets["""input_ids"""] _lowerCAmelCase = shift_tokens_right(_snake_case , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""en_XX""" , tgt_lang="""ar_AR""" ) self.assertEqual( nested_simplify(_snake_case ) , { # A, test, EOS, en_XX """input_ids""": [[62, 3034, 2, 250004]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 250001, } , )
82
"""simple docstring""" import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = """ylacombe/bark-small""" snake_case_ = tempfile.mkdtemp() snake_case_ = """en_speaker_1""" snake_case_ = """This is a test string""" snake_case_ = """speaker_embeddings_path.json""" snake_case_ = """speaker_embeddings""" def lowerCAmelCase ( self : List[str] , **UpperCAmelCase_ : str ) ->Optional[int]: """simple docstring""" return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = self.get_tokenizer() snake_case_ = BarkProcessor(tokenizer=UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) snake_case_ = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def lowerCAmelCase ( self : Dict ) ->int: """simple docstring""" snake_case_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) snake_case_ = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) snake_case_ = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) snake_case_ = 35 snake_case_ = 2 snake_case_ = 8 snake_case_ = { """semantic_prompt""": np.ones(UpperCAmelCase_ ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset snake_case_ = processor(text=self.input_string , voice_preset=UpperCAmelCase_ ) snake_case_ = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([] ) ).tolist() ) # test loading voice preset from npz file snake_case_ = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(UpperCAmelCase_ , **UpperCAmelCase_ ) snake_case_ = processor(text=self.input_string , voice_preset=UpperCAmelCase_ ) snake_case_ = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([] ) ).tolist() ) # test loading voice preset from the hub snake_case_ = processor(text=self.input_string , voice_preset=self.voice_preset ) def lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" snake_case_ = self.get_tokenizer() snake_case_ = BarkProcessor(tokenizer=UpperCAmelCase_ ) snake_case_ = processor(text=self.input_string ) snake_case_ = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
347
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class lowercase__ ( lowercase , unittest.TestCase ): lowercase__ = KandinskyVaaPipeline lowercase__ = [ """image_embeds""", """negative_image_embeds""", ] lowercase__ = ["""image_embeds""", """negative_image_embeds"""] lowercase__ = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] lowercase__ = False @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return 32 @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' return 32 @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' return self.time_input_dim @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return self.time_input_dim * 4 @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' return 100 @property def UpperCamelCase_ ( self : int ): '''simple docstring''' torch.manual_seed(0 ) _UpperCamelCase : Dict = { 'in_channels': 4, # Out channels is double in channels because predicts mean and variance 'out_channels': 8, 'addition_embed_type': 'image', 'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'), 'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'), 'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn', 'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2), 'layers_per_block': 1, 'encoder_hid_dim': self.text_embedder_hidden_size, 'encoder_hid_dim_type': 'image_proj', 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': None, } _UpperCamelCase : str = UNetaDConditionModel(**lowerCamelCase__ ) return model @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' torch.manual_seed(0 ) _UpperCamelCase : str = VQModel(**self.dummy_movq_kwargs ) return model def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' _UpperCamelCase : Tuple = self.dummy_unet _UpperCamelCase : List[Any] = self.dummy_movq _UpperCamelCase : Optional[Any] = DDIMScheduler( num_train_timesteps=1000 ,beta_schedule='linear' ,beta_start=0.0_0_0_8_5 ,beta_end=0.0_1_2 ,clip_sample=lowerCamelCase__ ,set_alpha_to_one=lowerCamelCase__ ,steps_offset=1 ,prediction_type='epsilon' ,thresholding=lowerCamelCase__ ,) _UpperCamelCase : List[str] = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def UpperCamelCase_ ( self : Any ,lowerCamelCase__ : Dict ,lowerCamelCase__ : str=0 ): '''simple docstring''' _UpperCamelCase : Tuple = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(lowerCamelCase__ ) ).to(lowerCamelCase__ ) _UpperCamelCase : Dict = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(seed + 1 ) ).to( lowerCamelCase__ ) if str(lowerCamelCase__ ).startswith('mps' ): _UpperCamelCase : str = torch.manual_seed(lowerCamelCase__ ) else: _UpperCamelCase : Tuple = torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ ) _UpperCamelCase : List[str] = { 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'generator': generator, 'height': 64, 'width': 64, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' _UpperCamelCase : List[Any] = 'cpu' _UpperCamelCase : Dict = self.get_dummy_components() _UpperCamelCase : Optional[int] = self.pipeline_class(**lowerCamelCase__ ) _UpperCamelCase : Optional[Any] = pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) _UpperCamelCase : Optional[Any] = pipe(**self.get_dummy_inputs(lowerCamelCase__ ) ) _UpperCamelCase : Dict = output.images _UpperCamelCase : Dict = pipe( **self.get_dummy_inputs(lowerCamelCase__ ) ,return_dict=lowerCamelCase__ ,)[0] _UpperCamelCase : Tuple = image[0, -3:, -3:, -1] _UpperCamelCase : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCamelCase : Any = np.array( [0.6_2_3_7_9_7_6, 1.0, 0.3_6_4_4_1_3_3_2, 1.0, 0.7_0_6_3_9_6_3_4, 0.2_9_8_7_7_1_8_6, 0.8_5_6_5_2_1_2_5, 0.5_2_1_6_8_4_3, 0.5_4_4_5_4_0_4_6] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F' expected_slice {expected_slice}, but got {image_slice.flatten()}' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}' @slow @require_torch_gpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' _UpperCamelCase : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy' ) _UpperCamelCase : Any = KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' ,torch_dtype=torch.floataa ) pipe_prior.to(lowerCamelCase__ ) _UpperCamelCase : List[str] = KandinskyVaaPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-decoder' ,torch_dtype=torch.floataa ) _UpperCamelCase : Union[str, Any] = pipeline.to(lowerCamelCase__ ) pipeline.set_progress_bar_config(disable=lowerCamelCase__ ) _UpperCamelCase : int = 'red cat, 4k photo' _UpperCamelCase : List[str] = torch.Generator(device='cuda' ).manual_seed(0 ) _UpperCamelCase , _UpperCamelCase : str = pipe_prior( lowerCamelCase__ ,generator=lowerCamelCase__ ,num_inference_steps=5 ,negative_prompt='' ,).to_tuple() _UpperCamelCase : Optional[int] = torch.Generator(device='cuda' ).manual_seed(0 ) _UpperCamelCase : Tuple = pipeline( image_embeds=lowerCamelCase__ ,negative_image_embeds=lowerCamelCase__ ,generator=lowerCamelCase__ ,num_inference_steps=100 ,output_type='np' ,) _UpperCamelCase : str = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(lowerCamelCase__ ,lowerCamelCase__ )
83
"""simple docstring""" import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 __SCREAMING_SNAKE_CASE : int = sys.version_info >= (3, 10) def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: return field(default_factory=lambda: default , metadata=_SCREAMING_SNAKE_CASE ) @dataclass class __A : '''simple docstring''' __lowercase: int __lowercase: float __lowercase: str __lowercase: bool @dataclass class __A : '''simple docstring''' __lowercase: int = 42 __lowercase: str = field(default="""toto""" , metadata={"""help""": """help message"""}) @dataclass class __A : '''simple docstring''' __lowercase: bool = False __lowercase: bool = True __lowercase: Optional[bool] = None class __A (snake_case__): '''simple docstring''' __lowercase: str = """titi""" __lowercase: Any = """toto""" class __A (snake_case__): '''simple docstring''' __lowercase: int = """titi""" __lowercase: Optional[Any] = """toto""" __lowercase: List[Any] = 42 @dataclass class __A : '''simple docstring''' __lowercase: BasicEnum = "toto" def lowerCAmelCase ( self : int ) ->List[Any]: """simple docstring""" snake_case_ = BasicEnum(self.foo ) @dataclass class __A : '''simple docstring''' __lowercase: MixedTypeEnum = "toto" def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = MixedTypeEnum(self.foo ) @dataclass class __A : '''simple docstring''' __lowercase: Optional[int] = None __lowercase: Optional[float] = field(default=snake_case__ , metadata={"""help""": """help message"""}) __lowercase: Optional[str] = None __lowercase: Optional[List[str]] = list_field(default=[]) __lowercase: Optional[List[int]] = list_field(default=[]) @dataclass class __A : '''simple docstring''' __lowercase: List[int] = list_field(default=[]) __lowercase: List[int] = list_field(default=[1, 2, 3]) __lowercase: List[str] = list_field(default=["""Hallo""", """Bonjour""", """Hello"""]) __lowercase: List[float] = list_field(default=[0.1, 0.2, 0.3]) @dataclass class __A : '''simple docstring''' __lowercase: List[int] = field() __lowercase: str = field() __lowercase: BasicEnum = field() def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" snake_case_ = BasicEnum(self.required_enum ) @dataclass class __A : '''simple docstring''' __lowercase: int __lowercase: "BasicEnum" = field() __lowercase: "Optional[bool]" = None __lowercase: "str" = field(default="""toto""" , metadata={"""help""": """help message"""}) __lowercase: "List[str]" = list_field(default=["""Hallo""", """Bonjour""", """Hello"""]) if is_python_no_less_than_3_10: @dataclass class __A : '''simple docstring''' __lowercase: bool = False __lowercase: bool = True __lowercase: bool | None = None @dataclass class __A : '''simple docstring''' __lowercase: int | None = None __lowercase: float | None = field(default=snake_case__ , metadata={"""help""": """help message"""}) __lowercase: str | None = None __lowercase: list[str] | None = list_field(default=[]) __lowercase: list[int] | None = list_field(default=[]) class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : argparse.ArgumentParser , UpperCAmelCase_ : argparse.ArgumentParser ) ->Optional[int]: """simple docstring""" self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): snake_case_ = {k: v for k, v in vars(UpperCAmelCase_ ).items() if k != """container"""} snake_case_ = {k: v for k, v in vars(UpperCAmelCase_ ).items() if k != """container"""} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("""choices""" , UpperCAmelCase_ ) and yy.get("""choices""" , UpperCAmelCase_ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["""type"""](UpperCAmelCase_ ) , yy["""type"""](UpperCAmelCase_ ) ) del xx["type"], yy["type"] self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : int ) ->Any: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--bar""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--baz""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--flag""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ , const=UpperCAmelCase_ , nargs="""?""" ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = ["""--foo""", """1""", """--baz""", """quux""", """--bar""", """0.5"""] ((snake_case_) , ) = parser.parse_args_into_dataclasses(UpperCAmelCase_ , look_for_args_file=UpperCAmelCase_ ) self.assertFalse(example.flag ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=42 , type=UpperCAmelCase_ ) expected.add_argument("""--baz""" , default="""toto""" , type=UpperCAmelCase_ , help="""help message""" ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ , const=UpperCAmelCase_ , nargs="""?""" ) expected.add_argument("""--baz""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ , const=UpperCAmelCase_ , nargs="""?""" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("""--no_baz""" , action="""store_false""" , default=UpperCAmelCase_ , dest="""baz""" ) expected.add_argument("""--opt""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ ) snake_case_ = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(UpperCAmelCase_ ) for dataclass_type in dataclass_types: snake_case_ = HfArgumentParser(UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """--no_baz"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """--baz"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """True""", """--baz""", """True""", """--opt""", """True"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) snake_case_ = parser.parse_args(["""--foo""", """False""", """--baz""", """False""", """--opt""", """False"""] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_ ) ) def lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=["""titi""", """toto""", 42] , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) snake_case_ = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) snake_case_ = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) snake_case_ = parser.parse_args_into_dataclasses(["""--foo""", """titi"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) snake_case_ = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) snake_case_ = parser.parse_args_into_dataclasses(["""--foo""", """42"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" @dataclass class __A : '''simple docstring''' __lowercase: Literal["titi", "toto", 42] = "toto" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=("""titi""", """toto""", 42) , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) snake_case_ = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) snake_case_ = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo_int""" , nargs="""+""" , default=[] , type=UpperCAmelCase_ ) expected.add_argument("""--bar_int""" , nargs="""+""" , default=[1, 2, 3] , type=UpperCAmelCase_ ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=UpperCAmelCase_ ) expected.add_argument("""--foo_float""" , nargs="""+""" , default=[0.1, 0.2, 0.3] , type=UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual( UpperCAmelCase_ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["""Hallo""", """Bonjour""", """Hello"""] , foo_float=[0.1, 0.2, 0.3] ) , ) snake_case_ = parser.parse_args("""--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7""".split() ) self.assertEqual(UpperCAmelCase_ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["""a""", """b""", """c"""] , foo_float=[0.1, 0.7] ) ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=UpperCAmelCase_ , type=UpperCAmelCase_ ) expected.add_argument("""--bar""" , default=UpperCAmelCase_ , type=UpperCAmelCase_ , help="""help message""" ) expected.add_argument("""--baz""" , default=UpperCAmelCase_ , type=UpperCAmelCase_ ) expected.add_argument("""--ces""" , nargs="""+""" , default=[] , type=UpperCAmelCase_ ) expected.add_argument("""--des""" , nargs="""+""" , default=[] , type=UpperCAmelCase_ ) snake_case_ = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(UpperCAmelCase_ ) for dataclass_type in dataclass_types: snake_case_ = HfArgumentParser(UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_args([] ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , bar=UpperCAmelCase_ , baz=UpperCAmelCase_ , ces=[] , des=[] ) ) snake_case_ = parser.parse_args("""--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3""".split() ) self.assertEqual(UpperCAmelCase_ , Namespace(foo=12 , bar=3.14 , baz="""42""" , ces=["""a""", """b""", """c"""] , des=[1, 2, 3] ) ) def lowerCAmelCase ( self : Optional[Any] ) ->Optional[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--required_list""" , nargs="""+""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument("""--required_str""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=UpperCAmelCase_ , ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=UpperCAmelCase_ , required=UpperCAmelCase_ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=UpperCAmelCase_ , ) expected.add_argument("""--opt""" , type=UpperCAmelCase_ , default=UpperCAmelCase_ ) expected.add_argument("""--baz""" , default="""toto""" , type=UpperCAmelCase_ , help="""help message""" ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=UpperCAmelCase_ ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } snake_case_ = parser.parse_dict(UpperCAmelCase_ )[0] snake_case_ = BasicExample(**UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, """extra""": 42, } self.assertRaises(UpperCAmelCase_ , parser.parse_dict , UpperCAmelCase_ , allow_extra_keys=UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = os.path.join(UpperCAmelCase_ , """temp_json""" ) os.mkdir(UpperCAmelCase_ ) with open(temp_local_path + """.json""" , """w+""" ) as f: json.dump(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_yaml_file(Path(temp_local_path + """.json""" ) )[0] snake_case_ = BasicExample(**UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) snake_case_ = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = os.path.join(UpperCAmelCase_ , """temp_yaml""" ) os.mkdir(UpperCAmelCase_ ) with open(temp_local_path + """.yaml""" , """w+""" ) as f: yaml.dump(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = parser.parse_yaml_file(Path(temp_local_path + """.yaml""" ) )[0] snake_case_ = BasicExample(**UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" snake_case_ = HfArgumentParser(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ )
347
0
"""simple docstring""" import baseaa def _snake_case ( lowercase__ : str ) -> bytes: '''simple docstring''' return baseaa.aaaencode(string.encode("""utf-8""" ) ) def _snake_case ( lowercase__ : bytes ) -> str: '''simple docstring''' return baseaa.aaadecode(lowercase__ ).decode("""utf-8""" ) if __name__ == "__main__": import doctest doctest.testmod()
84
"""simple docstring""" import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy __SCREAMING_SNAKE_CASE : Any = logging.getLogger(__name__) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , ) -> Optional[Any]: snake_case_ = bnb_quantization_config.load_in_abit snake_case_ = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( """You have a version of `bitsandbytes` that is not compatible with 8bit quantization,""" """ make sure you have the latest version of `bitsandbytes` installed.""" ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( """You have a version of `bitsandbytes` that is not compatible with 4bit quantization,""" """make sure you have the latest version of `bitsandbytes` installed.""" ) snake_case_ = [] # custom device map if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(device_map.keys() ) > 1: snake_case_ = [key for key, value in device_map.items() if value in ["""disk""", """cpu"""]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: snake_case_ = get_keys_to_not_convert(_SCREAMING_SNAKE_CASE ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(_SCREAMING_SNAKE_CASE ) snake_case_ = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: snake_case_ = [] snake_case_ = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(_SCREAMING_SNAKE_CASE ) # compatibility with peft snake_case_ = load_in_abit snake_case_ = load_in_abit snake_case_ = get_parameter_device(_SCREAMING_SNAKE_CASE ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( """It is not recommended to quantize a loaded model. """ """The model should be instantiated under the `init_empty_weights` context manager.""" ) snake_case_ = replace_with_bnb_layers(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE ) # convert param to the right dtype snake_case_ = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: snake_case_ = name.replace(""".weight""" , """""" ).replace(""".bias""" , """""" ) snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(_SCREAMING_SNAKE_CASE ): param.to(_SCREAMING_SNAKE_CASE ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info( f"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" """We move the model to cuda.""" ) return model elif weights_location is None: raise RuntimeError( f"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): snake_case_ = replace_with_bnb_layers( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE ) snake_case_ = get_quantized_model_device_map( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_memory=_SCREAMING_SNAKE_CASE , no_split_module_classes=_SCREAMING_SNAKE_CASE , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): snake_case_ = True snake_case_ = any(x in list(device_map.values() ) for x in ["""cpu""", """disk"""] ) load_checkpoint_in_model( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=bnb_quantization_config.torch_dtype , offload_folder=_SCREAMING_SNAKE_CASE , offload_state_dict=_SCREAMING_SNAKE_CASE , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(_SCREAMING_SNAKE_CASE , device_map=_SCREAMING_SNAKE_CASE , offload_dir=_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: if device_map is None: if torch.cuda.is_available(): snake_case_ = {"""""": torch.cuda.current_device()} else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info("""The device_map was not initialized.""" """Setting device_map to `{'':torch.cuda.current_device()}`.""" ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( """If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or """ """'sequential'.""" ) snake_case_ = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) snake_case_ = {} snake_case_ = special_dtypes snake_case_ = no_split_module_classes snake_case_ = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": snake_case_ = get_balanced_memory( _SCREAMING_SNAKE_CASE , low_zero=(device_map == """balanced_low_0""") , max_memory=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) snake_case_ = max_memory snake_case_ = infer_auto_device_map(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # check if don't have any quantized module on the cpu snake_case_ = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules snake_case_ = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( """ Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules in `torch_dtype`, you need to pass a custom `device_map` to `load_and_quantize_model`. Check https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk for more details. """ ) else: logger.info( """Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit""" ) del device_map_without_some_modules return device_map def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: if modules_to_not_convert is None: snake_case_ = [] snake_case_ , snake_case_ = _replace_with_bnb_layers( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , ) -> List[Any]: snake_case_ = False for name, module in model.named_children(): if current_key_name is None: snake_case_ = [] current_key_name.append(_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` snake_case_ = """.""".join(_SCREAMING_SNAKE_CASE ) snake_case_ = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: snake_case_ = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: snake_case_ = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=_SCREAMING_SNAKE_CASE , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: snake_case_ = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("""load_in_8bit and load_in_4bit can't be both False""" ) snake_case_ = module.weight.data if module.bias is not None: snake_case_ = module.bias.data bnb_module.requires_grad_(_SCREAMING_SNAKE_CASE ) setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = True if len(list(module.children() ) ) > 0: snake_case_ , snake_case_ = _replace_with_bnb_layers( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def _a ( _SCREAMING_SNAKE_CASE ) -> Any: # Create a copy of the model with init_empty_weights(): snake_case_ = deepcopy(_SCREAMING_SNAKE_CASE ) # this has 0 cost since it is done inside `init_empty_weights` context manager` snake_case_ = find_tied_parameters(_SCREAMING_SNAKE_CASE ) # For compatibility with Accelerate < 0.18 if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: snake_case_ = sum(_SCREAMING_SNAKE_CASE , [] ) snake_case_ = len(_SCREAMING_SNAKE_CASE ) > 0 # Check if it is a base model snake_case_ = False if hasattr(_SCREAMING_SNAKE_CASE , """base_model_prefix""" ): snake_case_ = not hasattr(_SCREAMING_SNAKE_CASE , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head snake_case_ = list(model.named_children() ) snake_case_ = [list_modules[-1][0]] # add last module together with tied weights snake_case_ = set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE ) snake_case_ = list(set(_SCREAMING_SNAKE_CASE ) ) + list(_SCREAMING_SNAKE_CASE ) # remove ".weight" from the keys snake_case_ = [""".weight""", """.bias"""] snake_case_ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: snake_case_ = name.replace(_SCREAMING_SNAKE_CASE , """""" ) filtered_module_names.append(_SCREAMING_SNAKE_CASE ) return filtered_module_names def _a ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: for m in model.modules(): if isinstance(_SCREAMING_SNAKE_CASE , bnb.nn.Linearabit ): return True return False def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: return next(parameter.parameters() ).device def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: # if it is not quantized, we quantize and offload the quantized weights and the SCB stats if fpaa_statistics is None: set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 0 , dtype=_SCREAMING_SNAKE_CASE , value=_SCREAMING_SNAKE_CASE ) snake_case_ = param_name snake_case_ = model if "." in tensor_name: snake_case_ = tensor_name.split(""".""" ) for split in splits[:-1]: snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if new_module is None: raise ValueError(f"""{module} has no attribute {split}.""" ) snake_case_ = new_module snake_case_ = splits[-1] # offload weights snake_case_ = False offload_weight(module._parameters[tensor_name] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) if hasattr(module._parameters[tensor_name] , """SCB""" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("""weight""" , """SCB""" ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE , ) else: offload_weight(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) offload_weight(_SCREAMING_SNAKE_CASE , param_name.replace("""weight""" , """SCB""" ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , """meta""" , dtype=_SCREAMING_SNAKE_CASE , value=torch.empty(*param.size() ) )
347
0
'''simple docstring''' _SCREAMING_SNAKE_CASE : Any = 0 # The first color of the flag. _SCREAMING_SNAKE_CASE : Dict = 1 # The second color of the flag. _SCREAMING_SNAKE_CASE : Tuple = 2 # The third color of the flag. _SCREAMING_SNAKE_CASE : Union[str, Any] = (red, white, blue) def UpperCamelCase_( snake_case : list ): '''simple docstring''' if not sequence: return [] if len(snake_case ) == 1: return list(snake_case ) snake_case_ = 0 snake_case_ = len(snake_case ) - 1 snake_case_ = 0 while mid <= high: if sequence[mid] == colors[0]: snake_case_ , snake_case_ = sequence[mid], sequence[low] low += 1 mid += 1 elif sequence[mid] == colors[1]: mid += 1 elif sequence[mid] == colors[2]: snake_case_ , snake_case_ = sequence[high], sequence[mid] high -= 1 else: snake_case_ = f'The elements inside the sequence must contains only {colors} values' raise ValueError(snake_case ) return sequence if __name__ == "__main__": import doctest doctest.testmod() _SCREAMING_SNAKE_CASE : Optional[int] = input("Enter numbers separated by commas:\n").strip() _SCREAMING_SNAKE_CASE : Tuple = [int(item.strip()) for item in user_input.split(",")] print(F"{dutch_national_flag_sort(unsorted)}")
85
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple = { 'microsoft/beit-base-patch16-224-pt22k': ( 'https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json' ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __A (snake_case__): '''simple docstring''' __lowercase: Optional[int] = """beit""" def __init__( self : List[str] , UpperCAmelCase_ : List[Any]=8_192 , UpperCAmelCase_ : Dict=768 , UpperCAmelCase_ : int=12 , UpperCAmelCase_ : Tuple=12 , UpperCAmelCase_ : List[Any]=3_072 , UpperCAmelCase_ : Tuple="gelu" , UpperCAmelCase_ : Dict=0.0 , UpperCAmelCase_ : List[str]=0.0 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : Optional[Any]=1E-12 , UpperCAmelCase_ : int=224 , UpperCAmelCase_ : Tuple=16 , UpperCAmelCase_ : List[str]=3 , UpperCAmelCase_ : int=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Tuple=False , UpperCAmelCase_ : int=False , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Dict=[3, 5, 7, 11] , UpperCAmelCase_ : Tuple=[1, 2, 3, 6] , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[Any]=0.4 , UpperCAmelCase_ : Optional[Any]=256 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : int=False , UpperCAmelCase_ : Tuple=255 , **UpperCAmelCase_ : List[str] , ) ->Optional[Any]: """simple docstring""" super().__init__(**UpperCAmelCase_ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = use_mask_token snake_case_ = use_absolute_position_embeddings snake_case_ = use_relative_position_bias snake_case_ = use_shared_relative_position_bias snake_case_ = layer_scale_init_value snake_case_ = drop_path_rate snake_case_ = use_mean_pooling # decode head attributes (semantic segmentation) snake_case_ = out_indices snake_case_ = pool_scales # auxiliary head attributes (semantic segmentation) snake_case_ = use_auxiliary_head snake_case_ = auxiliary_loss_weight snake_case_ = auxiliary_channels snake_case_ = auxiliary_num_convs snake_case_ = auxiliary_concat_input snake_case_ = semantic_loss_ignore_index class __A (snake_case__): '''simple docstring''' __lowercase: List[Any] = version.parse("""1.11""") @property def lowerCAmelCase ( self : Dict ) ->Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def lowerCAmelCase ( self : Any ) ->float: """simple docstring""" return 1E-4
347
0
"""simple docstring""" from __future__ import annotations def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : List[Any] = 2 __lowerCAmelCase : List[Any] = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCamelCase ) if n > 1: factors.append(_UpperCamelCase ) return factors if __name__ == "__main__": import doctest doctest.testmod()
86
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : List[Any] = {'vocab_file': 'spiece.model'} __SCREAMING_SNAKE_CASE : int = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', } } # TODO(PVP) - this should be removed in Transformers v5 __SCREAMING_SNAKE_CASE : Dict = { 't5-small': 512, 't5-base': 512, 't5-large': 512, 't5-3b': 512, 't5-11b': 512, } __SCREAMING_SNAKE_CASE : Optional[int] = '▁' class __A (snake_case__): '''simple docstring''' __lowercase: Optional[int] = VOCAB_FILES_NAMES __lowercase: Any = PRETRAINED_VOCAB_FILES_MAP __lowercase: Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase: List[str] = ["""input_ids""", """attention_mask"""] def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any]="</s>" , UpperCAmelCase_ : Optional[Any]="<unk>" , UpperCAmelCase_ : Any="<pad>" , UpperCAmelCase_ : Tuple=100 , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , UpperCAmelCase_ : Optional[int]=True , **UpperCAmelCase_ : Dict , ) ->None: """simple docstring""" if extra_ids > 0 and additional_special_tokens is None: snake_case_ = [F"""<extra_id_{i}>""" for i in range(UpperCAmelCase_ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens snake_case_ = len(set(filter(lambda UpperCAmelCase_ : bool("""extra_id""" in str(UpperCAmelCase_ ) ) , UpperCAmelCase_ ) ) ) if extra_tokens != extra_ids: raise ValueError( F"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are""" """ provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids""" """ tokens""" ) if legacy: logger.warning_once( F"""You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to""" """ read the related pull request available at https://github.com/huggingface/transformers/pull/24565""" ) snake_case_ = legacy snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , extra_ids=UpperCAmelCase_ , additional_special_tokens=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , legacy=UpperCAmelCase_ , **UpperCAmelCase_ , ) snake_case_ = vocab_file snake_case_ = extra_ids snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) @staticmethod def lowerCAmelCase ( UpperCAmelCase_ : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any] ) ->Union[str, Any]: """simple docstring""" if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: snake_case_ = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( """This tokenizer was incorrectly instantiated with a model max length of""" F""" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this""" """ behavior is kept to avoid breaking backwards compatibility when padding/encoding with""" """ `truncation is True`.\n- Be aware that you SHOULD NOT rely on""" F""" {pretrained_model_name_or_path} automatically truncating your input to""" F""" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences""" F""" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with""" """ `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please""" """ instantiate this tokenizer with `model_max_length` set to your preferred value.""" , UpperCAmelCase_ , ) return max_model_length @property def lowerCAmelCase ( self : Optional[Any] ) ->Optional[Any]: """simple docstring""" return self.sp_model.get_piece_size() + self._extra_ids def lowerCAmelCase ( self : Any ) ->Optional[int]: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(UpperCAmelCase_ )) + [1] return ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" return list( set(filter(lambda UpperCAmelCase_ : bool(re.search(R"""<extra_id_\d+>""" , UpperCAmelCase_ ) ) is not None , self.additional_special_tokens ) ) ) def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" return [self._convert_token_to_id(UpperCAmelCase_ ) for token in self.get_sentinel_tokens()] def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[int] ) ->List[int]: """simple docstring""" if len(UpperCAmelCase_ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F"""This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated""" """ eos tokens being added.""" ) return token_ids else: return token_ids + [self.eos_token_id] def lowerCAmelCase ( self : str , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = self._add_eos_if_not_present(UpperCAmelCase_ ) if token_ids_a is None: return token_ids_a else: snake_case_ = self._add_eos_if_not_present(UpperCAmelCase_ ) return token_ids_a + token_ids_a def __getstate__( self : Optional[Any] ) ->Tuple: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Optional[Any] , UpperCAmelCase_ : List[Any] ) ->List[Any]: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : "TextInput" , **UpperCAmelCase_ : Tuple ) ->List[str]: """simple docstring""" if not self.legacy: snake_case_ = SPIECE_UNDERLINE + text.replace(UpperCAmelCase_ , """ """ ) return super().tokenize(UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Any ) ->Tuple: """simple docstring""" if not self.legacy: snake_case_ = text.startswith(UpperCAmelCase_ ) if is_first: snake_case_ = text[1:] snake_case_ = self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) if not self.legacy and not is_first and not text.startswith(""" """ ) and tokens[0].startswith(UpperCAmelCase_ ): snake_case_ = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" if token.startswith("""<extra_id_""" ): snake_case_ = re.match(R"""<extra_id_(\d+)>""" , UpperCAmelCase_ ) snake_case_ = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(UpperCAmelCase_ ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" if index < self.sp_model.get_piece_size(): snake_case_ = self.sp_model.IdToPiece(UpperCAmelCase_ ) else: snake_case_ = F"""<extra_id_{self.vocab_size - 1 - index}>""" return token def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[str] ) ->Optional[Any]: """simple docstring""" snake_case_ = [] snake_case_ = """""" snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase_ ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(UpperCAmelCase_ ) snake_case_ = False out_string += self.sp_model.decode(UpperCAmelCase_ ) return out_string.strip() def lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,)
347
0
from __future__ import annotations from math import gcd def lowercase_ ( _lowerCamelCase : int , _lowerCamelCase : int = 2 , _lowerCamelCase : int = 1 , _lowerCamelCase : int = 3 , ): # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError("The input value cannot be less than 2") # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(_lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int) -> int: return (pow(_lowerCamelCase , 2) + step) % modulus for _ in range(_lowerCamelCase): # These track the position within the cycle detection logic. lowercase__ : Optional[int] = seed lowercase__ : int = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. lowercase__ : List[Any] = rand_fn(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase) lowercase__ : List[str] = rand_fn(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase) lowercase__ : int = rand_fn(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. lowercase__ : Any = gcd(hare - tortoise , _lowerCamelCase) if divisor == 1: # No common divisor yet, just keep searching. continue else: # We found a common divisor! if divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. lowercase__ : Dict = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse UpperCamelCase = argparse.ArgumentParser() parser.add_argument( '''num''', type=int, help='''The value to find a divisor of''', ) parser.add_argument( '''--attempts''', type=int, default=3, help='''The number of attempts before giving up''', ) UpperCamelCase = parser.parse_args() UpperCamelCase = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(f"{args.num} is probably prime") else: UpperCamelCase = args.num // divisor print(f"{args.num} = {divisor} * {quotient}")
87
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE = 1_000_000 ) -> int: snake_case_ = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , _SCREAMING_SNAKE_CASE ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
347
0
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __lowerCAmelCase : List[Any] = logging.get_logger(__name__) __lowerCAmelCase : List[str] = {'tokenizer_file': 'tokenizer.json'} __lowerCAmelCase : Optional[Any] = { 'tokenizer_file': { 'bigscience/tokenizer': 'https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json', 'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json', 'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json', 'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json', 'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json', 'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json', 'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json', }, } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = VOCAB_FILES_NAMES a__ = PRETRAINED_VOCAB_FILES_MAP a__ = ["""input_ids""", """attention_mask"""] a__ = None def __init__( self : Optional[Any] , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : str=None , UpperCamelCase__ : Optional[Any]="<unk>" , UpperCamelCase__ : Optional[Any]="<s>" , UpperCamelCase__ : List[str]="</s>" , UpperCamelCase__ : List[str]="<pad>" , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : List[Any]=False , **UpperCamelCase__ : Dict , ) -> int: """simple docstring""" super().__init__( UpperCamelCase__ , UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , unk_token=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , add_prefix_space=UpperCamelCase__ , clean_up_tokenization_spaces=UpperCamelCase__ , **UpperCamelCase__ , ) __magic_name__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , UpperCamelCase__ ) != add_prefix_space: __magic_name__ = getattr(UpperCamelCase__ , pre_tok_state.pop("""type""" ) ) __magic_name__ = add_prefix_space __magic_name__ = pre_tok_class(**UpperCamelCase__ ) __magic_name__ = add_prefix_space def _lowercase ( self : Optional[Any] , *UpperCamelCase__ : List[Any] , **UpperCamelCase__ : str ) -> BatchEncoding: """simple docstring""" __magic_name__ = kwargs.get("""is_split_into_words""" , UpperCamelCase__ ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with''' """ pretokenized inputs.""" ) return super()._batch_encode_plus(*UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : int , *UpperCamelCase__ : str , **UpperCamelCase__ : Union[str, Any] ) -> BatchEncoding: """simple docstring""" __magic_name__ = kwargs.get("""is_split_into_words""" , UpperCamelCase__ ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with''' """ pretokenized inputs.""" ) return super()._encode_plus(*UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : str , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" __magic_name__ = self._tokenizer.model.save(UpperCamelCase__ , name=UpperCamelCase__ ) return tuple(UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : "Conversation" ) -> List[int]: """simple docstring""" __magic_name__ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) + [self.eos_token_id] ) if len(UpperCamelCase__ ) > self.model_max_length: __magic_name__ = input_ids[-self.model_max_length :] return input_ids
88
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: print(f"""Vertex\tShortest Distance from vertex {src}""" ) for i, d in enumerate(_SCREAMING_SNAKE_CASE ): print(f"""{i}\t\t{d}""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: for j in range(_SCREAMING_SNAKE_CASE ): snake_case_ , snake_case_ , snake_case_ = (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 _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[float]: snake_case_ = [float("""inf""" )] * vertex_count snake_case_ = 0.0 for _ in range(vertex_count - 1 ): for j in range(_SCREAMING_SNAKE_CASE ): snake_case_ , snake_case_ , snake_case_ = (graph[j][k] for k in ["""src""", """dst""", """weight"""]) if distance[u] != float("""inf""" ) and distance[u] + w < distance[v]: snake_case_ = distance[u] + w snake_case_ = check_negative_cycle(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if negative_cycle_exists: raise Exception("""Negative cycle found""" ) return distance if __name__ == "__main__": import doctest doctest.testmod() __SCREAMING_SNAKE_CASE : int = int(input('Enter number of vertices: ').strip()) __SCREAMING_SNAKE_CASE : Dict = 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 : List[str] = ( int(x) for x in input('Enter source, destination, weight: ').strip().split(' ') ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'src': src, 'dst': dest, 'weight': weight} __SCREAMING_SNAKE_CASE : Union[str, Any] = int(input('\nEnter shortest path source:').strip()) __SCREAMING_SNAKE_CASE : str = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
347
0
'''simple docstring''' import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __magic_name__ : def __init__( self : Optional[int] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Union[str, Any]=13 ,_UpperCAmelCase : Optional[int]=30 ,_UpperCAmelCase : Union[str, Any]=2 ,_UpperCAmelCase : List[str]=3 ,_UpperCAmelCase : Any=True ,_UpperCAmelCase : Tuple=True ,_UpperCAmelCase : Tuple=32 ,_UpperCAmelCase : Union[str, Any]=5 ,_UpperCAmelCase : str=4 ,_UpperCAmelCase : int=37 ,_UpperCAmelCase : int="gelu" ,_UpperCAmelCase : List[str]=0.1 ,_UpperCAmelCase : Optional[Any]=0.1 ,_UpperCAmelCase : List[Any]=10 ,_UpperCAmelCase : str=0.02 ,_UpperCAmelCase : List[str]=None ,): _a : int = parent _a : str = batch_size _a : Tuple = image_size _a : str = patch_size _a : List[str] = num_channels _a : Union[str, Any] = is_training _a : Union[str, Any] = use_labels _a : List[Any] = hidden_size _a : Tuple = num_hidden_layers _a : List[str] = num_attention_heads _a : List[Any] = intermediate_size _a : Union[str, Any] = hidden_act _a : Optional[Any] = hidden_dropout_prob _a : Dict = attention_probs_dropout_prob _a : Optional[Any] = type_sequence_label_size _a : List[str] = initializer_range _a : List[Any] = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) _a : int = (image_size // patch_size) ** 2 _a : List[str] = num_patches + 1 def __lowercase ( self : str ): _a : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : Any = None if self.use_labels: _a : str = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) _a : List[str] = self.get_config() return config, pixel_values, labels def __lowercase ( self : List[str] ): return ViTMSNConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,initializer_range=self.initializer_range ,) def __lowercase ( self : Tuple ,_UpperCAmelCase : Any ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Any ): _a : Optional[int] = ViTMSNModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Tuple = model(_UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase ( self : Optional[Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ): _a : Optional[int] = self.type_sequence_label_size _a : Any = ViTMSNForImageClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Optional[Any] = model(_UpperCAmelCase ,labels=_UpperCAmelCase ) print('Pixel and labels shape: {pixel_values.shape}, {labels.shape}' ) print('Labels: {labels}' ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images _a : Tuple = 1 _a : Optional[Any] = ViTMSNForImageClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _a : Union[str, Any] = model(_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def __lowercase ( self : Dict ): _a : int = self.prepare_config_and_inputs() _a , _a , _a : List[str] = config_and_inputs _a : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __magic_name__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : Any = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () lowerCAmelCase : Optional[int] = ( {'feature-extraction': ViTMSNModel, 'image-classification': ViTMSNForImageClassification} if is_torch_available() else {} ) lowerCAmelCase : List[Any] = False lowerCAmelCase : Optional[int] = False lowerCAmelCase : Optional[int] = False lowerCAmelCase : Optional[int] = False def __lowercase ( self : Tuple ): _a : List[Any] = ViTMSNModelTester(self ) _a : Dict = ConfigTester(self ,config_class=_UpperCAmelCase ,has_text_modality=_UpperCAmelCase ,hidden_size=37 ) def __lowercase ( self : Optional[Any] ): self.config_tester.run_common_tests() @unittest.skip(reason='ViTMSN does not use inputs_embeds' ) def __lowercase ( self : str ): pass def __lowercase ( self : List[str] ): _a , _a : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : int = model_class(_UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) _a : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_UpperCAmelCase ,nn.Linear ) ) def __lowercase ( self : Optional[int] ): _a , _a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : int = model_class(_UpperCAmelCase ) _a : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : List[str] = [*signature.parameters.keys()] _a : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] ,_UpperCAmelCase ) def __lowercase ( self : int ): _a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def __lowercase ( self : Dict ): _a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase ) @slow def __lowercase ( self : List[Any] ): for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : List[str] = ViTMSNModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) def __lowerCamelCase ( ) -> Tuple: _a : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __magic_name__ ( unittest.TestCase ): @cached_property def __lowercase ( self : Optional[Any] ): return ViTImageProcessor.from_pretrained('facebook/vit-msn-small' ) if is_vision_available() else None @slow def __lowercase ( self : Tuple ): torch.manual_seed(2 ) _a : List[str] = ViTMSNForImageClassification.from_pretrained('facebook/vit-msn-small' ).to(_UpperCAmelCase ) _a : List[str] = self.default_image_processor _a : Dict = prepare_img() _a : Union[str, Any] = image_processor(images=_UpperCAmelCase ,return_tensors='pt' ).to(_UpperCAmelCase ) # forward pass with torch.no_grad(): _a : List[str] = model(**_UpperCAmelCase ) # verify the logits _a : Optional[int] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape ,_UpperCAmelCase ) _a : Any = torch.tensor([-0.08_03, -0.44_54, -0.23_75] ).to(_UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,_UpperCAmelCase ,atol=1E-4 ) )
89
"""simple docstring""" import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) __SCREAMING_SNAKE_CASE : List[str] = logging.getLogger(__name__) __SCREAMING_SNAKE_CASE : str = tf.data.AUTOTUNE def _a ( ) -> List[str]: snake_case_ = argparse.ArgumentParser(description="""Train a masked language model on TPU.""" ) parser.add_argument( """--pretrained_model_config""" , type=_SCREAMING_SNAKE_CASE , default="""roberta-base""" , help="""The model config to use. Note that we don't copy the model's weights, only the config!""" , ) parser.add_argument( """--tokenizer""" , type=_SCREAMING_SNAKE_CASE , default="""unigram-tokenizer-wikitext""" , help="""The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model's vocab size.""" , ) parser.add_argument( """--per_replica_batch_size""" , type=_SCREAMING_SNAKE_CASE , default=8 , help="""Batch size per TPU core.""" , ) parser.add_argument( """--no_tpu""" , action="""store_true""" , help="""If set, run on CPU and don't try to initialize a TPU. Useful for debugging on non-TPU instances.""" , ) parser.add_argument( """--tpu_name""" , type=_SCREAMING_SNAKE_CASE , help="""Name of TPU resource to initialize. Should be blank on Colab, and 'local' on TPU VMs.""" , default="""local""" , ) parser.add_argument( """--tpu_zone""" , type=_SCREAMING_SNAKE_CASE , help="""Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes.""" , ) parser.add_argument( """--gcp_project""" , type=_SCREAMING_SNAKE_CASE , help="""Google cloud project name. Only used for non-Colab TPU nodes.""" ) parser.add_argument( """--bfloat16""" , action="""store_true""" , help="""Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU.""" , ) parser.add_argument( """--train_dataset""" , type=_SCREAMING_SNAKE_CASE , help="""Path to training dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--shuffle_buffer_size""" , type=_SCREAMING_SNAKE_CASE , default=2**18 , help="""Size of the shuffle buffer (in samples)""" , ) parser.add_argument( """--eval_dataset""" , type=_SCREAMING_SNAKE_CASE , help="""Path to evaluation dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--num_epochs""" , type=_SCREAMING_SNAKE_CASE , default=1 , help="""Number of epochs to train for.""" , ) parser.add_argument( """--learning_rate""" , type=_SCREAMING_SNAKE_CASE , default=1E-4 , help="""Learning rate to use for training.""" , ) parser.add_argument( """--weight_decay_rate""" , type=_SCREAMING_SNAKE_CASE , default=1E-3 , help="""Weight decay rate to use for training.""" , ) parser.add_argument( """--max_length""" , type=_SCREAMING_SNAKE_CASE , default=512 , help="""Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py""" , ) parser.add_argument( """--mlm_probability""" , type=_SCREAMING_SNAKE_CASE , default=0.15 , help="""Fraction of tokens to mask during training.""" , ) parser.add_argument("""--output_dir""" , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help="""Path to save model checkpoints to.""" ) parser.add_argument("""--hub_model_id""" , type=_SCREAMING_SNAKE_CASE , help="""Model ID to upload to on the Hugging Face Hub.""" ) snake_case_ = parser.parse_args() return args def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: try: if args.tpu_name: snake_case_ = tf.distribute.cluster_resolver.TPUClusterResolver( args.tpu_name , zone=args.tpu_zone , project=args.gcp_project ) else: snake_case_ = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: raise RuntimeError( """Couldn't connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or """ """--gcp_project. When running on a TPU VM, use --tpu_name local.""" ) tf.config.experimental_connect_to_cluster(_SCREAMING_SNAKE_CASE ) tf.tpu.experimental.initialize_tpu_system(_SCREAMING_SNAKE_CASE ) return tpu def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = 0 for file in file_list: snake_case_ = file.split("""/""" )[-1] snake_case_ = re.search(r"""-\d+-(\d+)\.tfrecord""" , _SCREAMING_SNAKE_CASE ).group(1 ) snake_case_ = int(_SCREAMING_SNAKE_CASE ) num_samples += sample_count return num_samples def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Union[str, Any]: snake_case_ = count_samples(_SCREAMING_SNAKE_CASE ) snake_case_ = tf.data.Dataset.from_tensor_slices(_SCREAMING_SNAKE_CASE ) if shuffle: snake_case_ = dataset.shuffle(len(_SCREAMING_SNAKE_CASE ) ) snake_case_ = tf.data.TFRecordDataset(_SCREAMING_SNAKE_CASE , num_parallel_reads=_SCREAMING_SNAKE_CASE ) # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here snake_case_ = dataset.apply(tf.data.experimental.assert_cardinality(_SCREAMING_SNAKE_CASE ) ) snake_case_ = dataset.map(_SCREAMING_SNAKE_CASE , num_parallel_calls=_SCREAMING_SNAKE_CASE ) if shuffle: assert shuffle_buffer_size is not None snake_case_ = dataset.shuffle(args.shuffle_buffer_size ) snake_case_ = dataset.batch(_SCREAMING_SNAKE_CASE , drop_remainder=_SCREAMING_SNAKE_CASE ) snake_case_ = dataset.map(_SCREAMING_SNAKE_CASE , num_parallel_calls=_SCREAMING_SNAKE_CASE ) snake_case_ = dataset.prefetch(_SCREAMING_SNAKE_CASE ) return dataset def _a ( _SCREAMING_SNAKE_CASE ) -> List[Any]: if not args.no_tpu: snake_case_ = initialize_tpu(_SCREAMING_SNAKE_CASE ) snake_case_ = tf.distribute.TPUStrategy(_SCREAMING_SNAKE_CASE ) else: snake_case_ = tf.distribute.OneDeviceStrategy(device="""/gpu:0""" ) if args.bfloataa: tf.keras.mixed_precision.set_global_policy("""mixed_bfloat16""" ) snake_case_ = AutoTokenizer.from_pretrained(args.tokenizer ) snake_case_ = AutoConfig.from_pretrained(args.pretrained_model_config ) snake_case_ = tokenizer.vocab_size snake_case_ = tf.io.gfile.glob(os.path.join(args.train_dataset , """*.tfrecord""" ) ) if not training_records: raise ValueError(f"""No .tfrecord files found in {args.train_dataset}.""" ) snake_case_ = tf.io.gfile.glob(os.path.join(args.eval_dataset , """*.tfrecord""" ) ) if not eval_records: raise ValueError(f"""No .tfrecord files found in {args.eval_dataset}.""" ) snake_case_ = count_samples(_SCREAMING_SNAKE_CASE ) snake_case_ = num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync) snake_case_ = steps_per_epoch * args.num_epochs with strategy.scope(): snake_case_ = TFAutoModelForMaskedLM.from_config(_SCREAMING_SNAKE_CASE ) model(model.dummy_inputs ) # Pass some dummy inputs through the model to ensure all the weights are built snake_case_ , snake_case_ = create_optimizer( num_train_steps=_SCREAMING_SNAKE_CASE , num_warmup_steps=total_train_steps // 20 , init_lr=args.learning_rate , weight_decay_rate=args.weight_decay_rate , ) # Transformers models compute the right loss for their task by default when labels are passed, and will # use this for training unless you specify your own loss function in compile(). model.compile(optimizer=_SCREAMING_SNAKE_CASE , metrics=["""accuracy"""] ) def decode_fn(_SCREAMING_SNAKE_CASE ): snake_case_ = { """input_ids""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), """attention_mask""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), } return tf.io.parse_single_example(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can # use their methods in our data pipeline. snake_case_ = DataCollatorForLanguageModeling( tokenizer=_SCREAMING_SNAKE_CASE , mlm_probability=args.mlm_probability , mlm=_SCREAMING_SNAKE_CASE , return_tensors="""tf""" ) def mask_with_collator(_SCREAMING_SNAKE_CASE ): # TF really needs an isin() function snake_case_ = ( ~tf.cast(batch["""attention_mask"""] , tf.bool ) | (batch["""input_ids"""] == tokenizer.cls_token_id) | (batch["""input_ids"""] == tokenizer.sep_token_id) ) snake_case_ , snake_case_ = data_collator.tf_mask_tokens( batch["""input_ids"""] , vocab_size=len(_SCREAMING_SNAKE_CASE ) , mask_token_id=tokenizer.mask_token_id , special_tokens_mask=_SCREAMING_SNAKE_CASE , ) return batch snake_case_ = args.per_replica_batch_size * strategy.num_replicas_in_sync snake_case_ = prepare_dataset( _SCREAMING_SNAKE_CASE , decode_fn=_SCREAMING_SNAKE_CASE , mask_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , shuffle=_SCREAMING_SNAKE_CASE , shuffle_buffer_size=args.shuffle_buffer_size , ) snake_case_ = prepare_dataset( _SCREAMING_SNAKE_CASE , decode_fn=_SCREAMING_SNAKE_CASE , mask_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , shuffle=_SCREAMING_SNAKE_CASE , ) snake_case_ = [] if args.hub_model_id: callbacks.append( PushToHubCallback(output_dir=args.output_dir , hub_model_id=args.hub_model_id , tokenizer=_SCREAMING_SNAKE_CASE ) ) model.fit( _SCREAMING_SNAKE_CASE , validation_data=_SCREAMING_SNAKE_CASE , epochs=args.num_epochs , callbacks=_SCREAMING_SNAKE_CASE , ) model.save_pretrained(args.output_dir ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = parse_args() main(args)
347
0
import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis_float32 (there's also the fix_lavis branch) # also note: to convert Vicuna checkpoints, we had to include /home/niels/python_projects/checkpoints/FastChat/vicuna-7b in lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml # same for Vicuna-13b from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipImageProcessor, InstructBlipConfig, InstructBlipForConditionalGeneration, InstructBlipProcessor, InstructBlipQFormerConfig, InstructBlipVisionConfig, LlamaConfig, LlamaTokenizerFast, TaConfig, TaTokenizerFast, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def lowerCamelCase_ ( ) -> List[str]: """simple docstring""" __lowerCamelCase = 'https://raw.githubusercontent.com/salesforce/LAVIS/main/docs/_static/Confusing-Pictures.jpg' __lowerCamelCase = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ).convert('RGB' ) return image def lowerCamelCase_ ( UpperCamelCase__ : Any ) -> Optional[Any]: """simple docstring""" __lowerCamelCase = [] # fmt: off # vision encoder rename_keys.append(('visual_encoder.cls_token', 'vision_model.embeddings.class_embedding') ) rename_keys.append(('visual_encoder.pos_embed', 'vision_model.embeddings.position_embedding') ) rename_keys.append(('visual_encoder.patch_embed.proj.weight', 'vision_model.embeddings.patch_embedding.weight') ) rename_keys.append(('visual_encoder.patch_embed.proj.bias', 'vision_model.embeddings.patch_embedding.bias') ) rename_keys.append(('ln_vision.weight', 'vision_model.post_layernorm.weight') ) rename_keys.append(('ln_vision.bias', 'vision_model.post_layernorm.bias') ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((F"""visual_encoder.blocks.{i}.norm1.weight""", F"""vision_model.encoder.layers.{i}.layer_norm1.weight""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.norm1.bias""", F"""vision_model.encoder.layers.{i}.layer_norm1.bias""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.norm2.weight""", F"""vision_model.encoder.layers.{i}.layer_norm2.weight""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.norm2.bias""", F"""vision_model.encoder.layers.{i}.layer_norm2.bias""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.attn.qkv.weight""", F"""vision_model.encoder.layers.{i}.self_attn.qkv.weight""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.attn.proj.weight""", F"""vision_model.encoder.layers.{i}.self_attn.projection.weight""",) ) rename_keys.append((F"""visual_encoder.blocks.{i}.attn.proj.bias""", F"""vision_model.encoder.layers.{i}.self_attn.projection.bias""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.mlp.fc1.weight""", F"""vision_model.encoder.layers.{i}.mlp.fc1.weight""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.mlp.fc1.bias""", F"""vision_model.encoder.layers.{i}.mlp.fc1.bias""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.mlp.fc2.weight""", F"""vision_model.encoder.layers.{i}.mlp.fc2.weight""") ) rename_keys.append((F"""visual_encoder.blocks.{i}.mlp.fc2.bias""", F"""vision_model.encoder.layers.{i}.mlp.fc2.bias""") ) # QFormer rename_keys.append(('Qformer.bert.embeddings.LayerNorm.weight', 'qformer.embeddings.layernorm.weight') ) rename_keys.append(('Qformer.bert.embeddings.LayerNorm.bias', 'qformer.embeddings.layernorm.bias') ) # fmt: on return rename_keys def lowerCamelCase_ ( UpperCamelCase__ : List[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[int] ) -> Optional[int]: """simple docstring""" __lowerCamelCase = dct.pop(UpperCamelCase__ ) __lowerCamelCase = val def lowerCamelCase_ ( UpperCamelCase__ : Tuple , UpperCamelCase__ : int ) -> Dict: """simple docstring""" for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases __lowerCamelCase = state_dict.pop(F"""visual_encoder.blocks.{i}.attn.q_bias""" ) __lowerCamelCase = state_dict.pop(F"""visual_encoder.blocks.{i}.attn.v_bias""" ) # next, set bias in the state dict __lowerCamelCase = torch.cat((q_bias, torch.zeros_like(UpperCamelCase__ , requires_grad=UpperCamelCase__ ), v_bias) ) __lowerCamelCase = qkv_bias def lowerCamelCase_ ( UpperCamelCase__ : Dict ) -> Optional[Any]: """simple docstring""" __lowerCamelCase = 364 if 'coco' in model_name else 224 __lowerCamelCase = InstructBlipVisionConfig(image_size=UpperCamelCase__ ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "t5-xl" in model_name: __lowerCamelCase = TaConfig.from_pretrained('google/flan-t5-xl' , dense_act_fn='gelu' , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: __lowerCamelCase = TaConfig.from_pretrained('google/flan-t5-xxl' , dense_act_fn='gelu' , bos_token_id=1 ).to_dict() elif "vicuna-7b" in model_name: __lowerCamelCase = LlamaConfig.from_pretrained('decapoda-research/llama-7b-hf' , vocab_size=3_2001 ).to_dict() elif "vicuna-13b" in model_name: __lowerCamelCase = LlamaConfig.from_pretrained('decapoda-research/llama-13b-hf' , vocab_size=3_2001 ).to_dict() else: raise ValueError('Model name not supported' ) # the authors add one special "[DEC]" token to the vocab of Q-Former, hence vocab size = 30522 + 1 __lowerCamelCase = InstructBlipQFormerConfig(vocab_size=3_0523 ).to_dict() __lowerCamelCase = InstructBlipConfig(vision_config=UpperCamelCase__ , text_config=UpperCamelCase__ , qformer_config=UpperCamelCase__ ) return config, image_size @torch.no_grad() def lowerCamelCase_ ( UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : Union[str, Any]=False ) -> Optional[Any]: """simple docstring""" __lowerCamelCase = AutoTokenizer.from_pretrained('bert-base-uncased' , truncation_side='left' ) qformer_tokenizer.add_special_tokens({'bos_token': '[DEC]'} ) if "t5" in model_name: __lowerCamelCase = TaTokenizerFast.from_pretrained('google/flan-t5-xl' , truncation_side='left' ) elif "vicuna" in model_name: # the following was used in the original implementation: # tokenizer = LlamaTokenizer.from_pretrained("huggyllama/llama-7b", use_fast=False, truncation_side="left") # tokenizer.add_special_tokens({"pad_token": "[PAD]"}) # tokenizer.add_special_tokens({"bos_token": "</s>"}) # tokenizer.add_special_tokens({"eos_token": "</s>"}) # tokenizer.add_special_tokens({"unk_token": "</s>"}) __lowerCamelCase = LlamaTokenizerFast.from_pretrained( 'huggyllama/llama-7b' , truncation_side='left' , bos_token='</s>' , unk_token='</s>' ) tokenizer.add_special_tokens({'pad_token': '[PAD]'} ) __lowerCamelCase , __lowerCamelCase = get_blipa_config(UpperCamelCase__ ) __lowerCamelCase = InstructBlipForConditionalGeneration(UpperCamelCase__ ).eval() __lowerCamelCase = { 'instructblip-vicuna-7b': ('blip2_vicuna_instruct', 'vicuna7b'), 'instructblip-vicuna-13b': ('blip2_vicuna_instruct', 'vicuna13b'), 'instructblip-flan-t5-xl': ('blip2_t5_instruct', 'flant5xl'), 'instructblip-flan-t5-xxl': ('blip2_t5_instruct', 'flant5xxl'), } __lowerCamelCase , __lowerCamelCase = model_name_to_original[model_name] # load original model print('Loading original model...' ) __lowerCamelCase = 'cuda:1' if torch.cuda.is_available() else 'cpu' __lowerCamelCase = 'cuda:2' if torch.cuda.is_available() else 'cpu' __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = load_model_and_preprocess( name=UpperCamelCase__ , model_type=UpperCamelCase__ , is_eval=UpperCamelCase__ , device=UpperCamelCase__ ) original_model.eval() print('Done!' ) # update state dict keys __lowerCamelCase = original_model.state_dict() __lowerCamelCase = create_rename_keys(UpperCamelCase__ ) for src, dest in rename_keys: rename_key(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): __lowerCamelCase = state_dict.pop(UpperCamelCase__ ) if key.startswith('Qformer.bert' ): __lowerCamelCase = key.replace('Qformer.bert' , 'qformer' ) if "attention.self" in key: __lowerCamelCase = key.replace('self' , 'attention' ) if "llm_proj" in key: __lowerCamelCase = key.replace('llm_proj' , 'language_projection' ) if "t5_proj" in key: __lowerCamelCase = key.replace('t5_proj' , 'language_projection' ) if key.startswith('llm_model' ): __lowerCamelCase = key.replace('llm_model' , 'language_model' ) if key.startswith('t5' ): __lowerCamelCase = key.replace('t5' , 'language' ) __lowerCamelCase = val # read in qv biases read_in_q_v_bias(UpperCamelCase__ , UpperCamelCase__ ) # note: weights get loaded in torch.float32 by default hf_model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) __lowerCamelCase = load_demo_image() __lowerCamelCase = 'What is unusual about this image?' # create processor __lowerCamelCase = BlipImageProcessor( size={'height': image_size, 'width': image_size} , image_mean=UpperCamelCase__ , image_std=UpperCamelCase__ ) __lowerCamelCase = InstructBlipProcessor( image_processor=UpperCamelCase__ , tokenizer=UpperCamelCase__ , qformer_tokenizer=UpperCamelCase__ , ) __lowerCamelCase = processor(images=UpperCamelCase__ , text=UpperCamelCase__ , return_tensors='pt' ).to(UpperCamelCase__ ) # make sure processor creates exact same pixel values __lowerCamelCase = vis_processors['eval'](UpperCamelCase__ ).unsqueeze(0 ).to(UpperCamelCase__ ) __lowerCamelCase = inputs.pixel_values assert torch.allclose(original_pixel_values.to(pixel_values.device ) , UpperCamelCase__ ) original_model.to(UpperCamelCase__ ) hf_model.to(UpperCamelCase__ ) with torch.no_grad(): if "vicuna" in model_name: __lowerCamelCase = original_model({'image': original_pixel_values, 'text_input': [prompt]} ).logits __lowerCamelCase = hf_model(**UpperCamelCase__ ).logits else: __lowerCamelCase = original_model( {'image': original_pixel_values, 'text_input': [prompt], 'text_output': ['\n']} ).logits __lowerCamelCase = tokenizer('\n' , return_tensors='pt' ).input_ids.to(UpperCamelCase__ ) __lowerCamelCase = label_input_ids.masked_fill(label_input_ids == tokenizer.pad_token_id , -100 ) __lowerCamelCase = hf_model(**UpperCamelCase__ , labels=UpperCamelCase__ ).logits print('First values of original logits:' , original_logits[0, :3, :3] ) print('First values of HF logits:' , logits[0, :3, :3] ) # assert values assert original_logits.shape == logits.shape __lowerCamelCase = 1E-4 if 'vicuna' in model_name else 1E-5 assert torch.allclose(original_logits.to(logits.device ) , UpperCamelCase__ , atol=UpperCamelCase__ ) print('Looks ok!' ) print('Generating with original model...' ) __lowerCamelCase = original_model.generate({'image': original_pixel_values, 'prompt': prompt} , num_beams=5 ) # important: we need to cast the weights of the HF model to the appropriate type print('Generating with HF model...' ) __lowerCamelCase = hf_model.generate( **UpperCamelCase__ , do_sample=UpperCamelCase__ , num_beams=5 , max_length=256 , min_length=1 , top_p=0.9 , repetition_penalty=1.5 , length_penalty=1.0 , temperature=1 , ) if "vicuna" in model_name: # convert output id 0 to 2 (eos_token_id) # TODO add this in the generate method? __lowerCamelCase = 2 print('Original generation:' , UpperCamelCase__ ) __lowerCamelCase = processor.batch_decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) __lowerCamelCase = [text.strip() for text in output_text] print('HF generation:' , UpperCamelCase__ ) if pytorch_dump_folder_path is not None: processor.save_pretrained(UpperCamelCase__ ) hf_model.save_pretrained(UpperCamelCase__ ) if push_to_hub: processor.push_to_hub(F"""Salesforce/{model_name}""" ) hf_model.push_to_hub(F"""Salesforce/{model_name}""" ) if __name__ == "__main__": __A = argparse.ArgumentParser() __A = [ "instructblip-vicuna-7b", "instructblip-vicuna-13b", "instructblip-flan-t5-xl", "instructblip-flan-t5-xxl", ] parser.add_argument( "--model_name", default="instructblip-flan-t5-xl", choices=choices, type=str, help="Path to hf config.json of model to convert", ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model and processor to the hub after converting", ) __A = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
90
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float: if density <= 0: raise ValueError("""Impossible fluid density""" ) if bulk_modulus <= 0: raise ValueError("""Impossible bulk modulus""" ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
347
0
"""simple docstring""" from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase_ : Any = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Tuple , *lowercase_ : str , **lowercase_ : List[Any]): '''simple docstring''' super().__init__(*lowercase_ , **lowercase_) requires_backends(self , '''vision''') self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == '''tf''' else MODEL_FOR_VISION_2_SEQ_MAPPING) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : str=None , lowercase_ : Dict=None , lowercase_ : Optional[int]=None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = {} SCREAMING_SNAKE_CASE_ : Tuple = {} if prompt is not None: SCREAMING_SNAKE_CASE_ : Tuple = prompt if generate_kwargs is not None: SCREAMING_SNAKE_CASE_ : int = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( '''\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,''' ''' please use only one''') SCREAMING_SNAKE_CASE_ : Optional[Any] = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self : Any , lowercase_ : Union[str, List[str], "Image.Image", List["Image.Image"]] , **lowercase_ : Any): '''simple docstring''' return super().__call__(lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Optional[int] , lowercase_ : List[str]=None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = load_image(lowercase_) if prompt is not None: if not isinstance(lowercase_ , lowercase_): raise ValueError( F'Received an invalid text input, got - {type(lowercase_)} - but expected a single string. ' '''Note also that one single text can be provided for conditional image to text generation.''') SCREAMING_SNAKE_CASE_ : Optional[int] = self.model.config.model_type if model_type == "git": SCREAMING_SNAKE_CASE_ : Dict = self.image_processor(images=lowercase_ , return_tensors=self.framework) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer(text=lowercase_ , add_special_tokens=lowercase_).input_ids SCREAMING_SNAKE_CASE_ : Optional[int] = [self.tokenizer.cls_token_id] + input_ids SCREAMING_SNAKE_CASE_ : Tuple = torch.tensor(lowercase_).unsqueeze(0) model_inputs.update({'''input_ids''': input_ids}) elif model_type == "pix2struct": SCREAMING_SNAKE_CASE_ : str = self.image_processor(images=lowercase_ , header_text=lowercase_ , return_tensors=self.framework) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation SCREAMING_SNAKE_CASE_ : int = self.image_processor(images=lowercase_ , return_tensors=self.framework) SCREAMING_SNAKE_CASE_ : int = self.tokenizer(lowercase_ , return_tensors=self.framework) model_inputs.update(lowercase_) else: raise ValueError(F'Model type {model_type} does not support conditional text generation') else: SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor(images=lowercase_ , return_tensors=self.framework) if self.model.config.model_type == "git" and prompt is None: SCREAMING_SNAKE_CASE_ : List[str] = None return model_inputs def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[str] , lowercase_ : Optional[int]=None): '''simple docstring''' if ( "input_ids" in model_inputs and isinstance(model_inputs['''input_ids'''] , lowercase_) and all(x is None for x in model_inputs['''input_ids''']) ): SCREAMING_SNAKE_CASE_ : List[str] = None if generate_kwargs is None: SCREAMING_SNAKE_CASE_ : Optional[int] = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. SCREAMING_SNAKE_CASE_ : int = model_inputs.pop(self.model.main_input_name) SCREAMING_SNAKE_CASE_ : Optional[int] = self.model.generate(lowercase_ , **lowercase_ , **lowercase_) return model_outputs def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] for output_ids in model_outputs: SCREAMING_SNAKE_CASE_ : Optional[Any] = { '''generated_text''': self.tokenizer.decode( lowercase_ , skip_special_tokens=lowercase_ , ) } records.append(lowercase_) return records
91
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if num < 0: return False snake_case_ = num snake_case_ = 0 while num > 0: snake_case_ = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
347
0
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
92
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin __SCREAMING_SNAKE_CASE : Tuple = get_tests_dir('fixtures/test_sentencepiece_bpe_char.model') @require_sentencepiece @require_tokenizers class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Tuple = SpeechTaTokenizer __lowercase: int = False __lowercase: List[str] = True def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing snake_case_ = SpeechTaTokenizer(UpperCAmelCase_ ) snake_case_ = AddedToken("""<mask>""" , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) snake_case_ = mask_token tokenizer.add_special_tokens({"""mask_token""": mask_token} ) tokenizer.add_tokens(["""<ctc_blank>"""] ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = """this is a test""" snake_case_ = """this is a test""" return input_text, output_text def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Any=False , UpperCAmelCase_ : Tuple=20 , UpperCAmelCase_ : Dict=5 ) ->List[Any]: """simple docstring""" snake_case_ , snake_case_ = self.get_input_output_texts(UpperCAmelCase_ ) snake_case_ = tokenizer.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ ) snake_case_ = tokenizer.decode(UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ ) return text, ids def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" snake_case_ = """<pad>""" snake_case_ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_ ) , UpperCAmelCase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_ ) , UpperCAmelCase_ ) def lowerCAmelCase ( self : int ) ->str: """simple docstring""" snake_case_ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-4] , """œ""" ) self.assertEqual(vocab_keys[-2] , """<mask>""" ) self.assertEqual(vocab_keys[-1] , """<ctc_blank>""" ) self.assertEqual(len(UpperCAmelCase_ ) , 81 ) def lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = self.get_tokenizers(do_lower_case=UpperCAmelCase_ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case_ = tokenizer.vocab_size snake_case_ = len(UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) snake_case_ = ["""aaaaa bbbbbb""", """cccccccccdddddddd"""] snake_case_ = tokenizer.add_tokens(UpperCAmelCase_ ) snake_case_ = tokenizer.vocab_size snake_case_ = len(UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , 0 ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , len(UpperCAmelCase_ ) ) self.assertEqual(UpperCAmelCase_ , all_size + len(UpperCAmelCase_ ) ) snake_case_ = tokenizer.encode("""aaaaa bbbbbb low cccccccccdddddddd l""" , add_special_tokens=UpperCAmelCase_ ) self.assertGreaterEqual(len(UpperCAmelCase_ ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) snake_case_ = {"""eos_token""": """>>>>|||<||<<|<<""", """pad_token""": """<<<<<|||>|>>>>|>"""} snake_case_ = tokenizer.add_special_tokens(UpperCAmelCase_ ) snake_case_ = tokenizer.vocab_size snake_case_ = len(UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , 0 ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , len(UpperCAmelCase_ ) ) self.assertEqual(UpperCAmelCase_ , all_size_a + len(UpperCAmelCase_ ) ) snake_case_ = tokenizer.encode( """>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l""" , add_special_tokens=UpperCAmelCase_ ) self.assertGreaterEqual(len(UpperCAmelCase_ ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" pass def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" pass def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = self.get_tokenizer() snake_case_ = tokenizer.tokenize("""This is a test""" ) # fmt: off self.assertListEqual(UpperCAmelCase_ , [SPIECE_UNDERLINE, """T""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """a""", SPIECE_UNDERLINE, """t""", """e""", """s""", """t"""] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) snake_case_ = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( UpperCAmelCase_ , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """92000""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) snake_case_ = tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) # fmt: off self.assertListEqual(UpperCAmelCase_ , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on snake_case_ = tokenizer.convert_ids_to_tokens(UpperCAmelCase_ ) self.assertListEqual( UpperCAmelCase_ , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """<unk>""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) @slow def lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" snake_case_ = [ """Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides """ """general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural """ """Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained """ """models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.""", """BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly """ """conditioning on both left and right context in all layers.""", """The quick brown fox jumps over the lazy dog.""", ] # fmt: off snake_case_ = { """input_ids""": [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], """attention_mask""": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase_ , model_name="""microsoft/speecht5_asr""" , revision="""c5ef64c71905caeccde0e4462ef3f9077224c524""" , sequences=UpperCAmelCase_ , )
347
0
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowerCAmelCase__ : lowerCAmelCase_ = 42 # setable values lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = None @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE ) @dataclass class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = 42 class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = [e.name for e in FlaxKarrasDiffusionSchedulers] lowerCAmelCase_ = 42 @property def _snake_case ( self ): """simple docstring""" return True @register_to_config def __init__( self , __SCREAMING_SNAKE_CASE = 10_00 , __SCREAMING_SNAKE_CASE = 0.0_001 , __SCREAMING_SNAKE_CASE = 0.02 , __SCREAMING_SNAKE_CASE = "linear" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "fixed_small" , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = "epsilon" , __SCREAMING_SNAKE_CASE = jnp.floataa , ): """simple docstring""" lowercase_ : Dict = dtype def _snake_case ( self , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if common is None: lowercase_ : Tuple = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution lowercase_ : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) lowercase_ : List[Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" return sample def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = () ): """simple docstring""" lowercase_ : Optional[Any] = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 lowercase_ : int = (jnp.arange(0 , __SCREAMING_SNAKE_CASE ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : List[Any] = state.common.alphas_cumprod[t] lowercase_ : str = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowercase_ : int = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: lowercase_ : str = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": lowercase_ : int = jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": lowercase_ : List[str] = jnp.log(jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) ) elif variance_type == "fixed_large": lowercase_ : List[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log lowercase_ : List[Any] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": lowercase_ : Optional[Any] = variance lowercase_ : Union[str, Any] = state.common.betas[t] lowercase_ : Union[str, Any] = (predicted_variance + 1) / 2 lowercase_ : Any = frac * max_log + (1 - frac) * min_log return variance def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , ): """simple docstring""" lowercase_ : Optional[int] = timestep if key is None: lowercase_ : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: lowercase_ , lowercase_ : Optional[Any] = jnp.split(__SCREAMING_SNAKE_CASE , sample.shape[1] , axis=1 ) else: lowercase_ : int = None # 1. compute alphas, betas lowercase_ : Any = state.common.alphas_cumprod[t] lowercase_ : Optional[int] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) lowercase_ : int = 1 - alpha_prod_t lowercase_ : str = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": lowercase_ : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowercase_ : Any = model_output elif self.config.prediction_type == "v_prediction": lowercase_ : List[Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowercase_ : Optional[Any] = jnp.clip(__SCREAMING_SNAKE_CASE , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t lowercase_ : Optional[Any] = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : Optional[Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): lowercase_ : str = jax.random.split(__SCREAMING_SNAKE_CASE , num=1 ) lowercase_ : List[Any] = jax.random.normal(__SCREAMING_SNAKE_CASE , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , predicted_variance=__SCREAMING_SNAKE_CASE ) ** 0.5) * noise lowercase_ : Optional[Any] = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) lowercase_ : Any = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__SCREAMING_SNAKE_CASE , state=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return add_noise_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return get_velocity_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
93
"""simple docstring""" import datasets __SCREAMING_SNAKE_CASE : Tuple = '\\n@InProceedings{conneau2018xnli,\n author = "Conneau, Alexis\n and Rinott, Ruty\n and Lample, Guillaume\n and Williams, Adina\n and Bowman, Samuel R.\n and Schwenk, Holger\n and Stoyanov, Veselin",\n title = "XNLI: Evaluating Cross-lingual Sentence Representations",\n booktitle = "Proceedings of the 2018 Conference on Empirical Methods\n in Natural Language Processing",\n year = "2018",\n publisher = "Association for Computational Linguistics",\n location = "Brussels, Belgium",\n}\n' __SCREAMING_SNAKE_CASE : Dict = '\\nXNLI is a subset of a few thousand examples from MNLI which has been translated\ninto a 14 different languages (some low-ish resource). As with MNLI, the goal is\nto predict textual entailment (does sentence A imply/contradict/neither sentence\nB) and is a classification task (given two sentences, predict one of three\nlabels).\n' __SCREAMING_SNAKE_CASE : List[str] = '\nComputes XNLI score which is just simple accuracy.\nArgs:\n predictions: Predicted labels.\n references: Ground truth labels.\nReturns:\n \'accuracy\': accuracy\nExamples:\n\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> xnli_metric = datasets.load_metric("xnli")\n >>> results = xnli_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n' def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: return (preds == labels).mean() @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __A (datasets.Metric): '''simple docstring''' def lowerCAmelCase ( self : str ) ->Any: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), """references""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), } ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" , ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" return {"accuracy": simple_accuracy(UpperCAmelCase_ , UpperCAmelCase_ )}
347
0
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available snake_case : int = {'''configuration_van''': ['''VAN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''VanConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case : Dict = [ '''VAN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''VanForImageClassification''', '''VanModel''', '''VanPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_van import ( VAN_PRETRAINED_MODEL_ARCHIVE_LIST, VanForImageClassification, VanModel, VanPreTrainedModel, ) else: import sys snake_case : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
94
"""simple docstring""" from ..utils import DummyObject, requires_backends class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : List[str] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""sentencepiece"""] def __init__( self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Tuple ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : Any , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : List[Any] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Dict = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[str] = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : int ) ->List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Tuple , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Dict ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Union[str, Any] ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[Any] = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : Optional[Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""sentencepiece"""] def __init__( self : Optional[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : str , **UpperCAmelCase_ : int ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Optional[int] , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Tuple = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : List[Any] ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : List[str] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Tuple = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Optional[Any] ) ->str: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Optional[Any] ) ->int: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = ["""sentencepiece"""] def __init__( self : Optional[Any] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : Optional[Any] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Dict ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : List[str] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any] ) ->List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : Any , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Optional[Any] ) ->List[str]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Dict = ["""sentencepiece"""] def __init__( self : int , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Union[str, Any] ) ->List[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""sentencepiece"""] def __init__( self : List[Any] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Optional[int] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = ["""sentencepiece"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : str ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""sentencepiece"""] def __init__( self : Tuple , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Optional[int] ) ->Dict: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Dict = ["""sentencepiece"""] def __init__( self : Optional[int] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : List[str] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""sentencepiece"""] def __init__( self : Dict , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Optional[int] ) ->Any: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[str] = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Union[str, Any] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ["""sentencepiece"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""sentencepiece"""] def __init__( self : List[str] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Optional[int] ) ->str: """simple docstring""" requires_backends(self , ["""sentencepiece"""] )
347
0
def _A ( SCREAMING_SNAKE_CASE : Any ): """simple docstring""" a__ : Any =[0] * len(SCREAMING_SNAKE_CASE ) a__ : List[Any] =[] a__ : Dict =[1] * len(SCREAMING_SNAKE_CASE ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(SCREAMING_SNAKE_CASE ) ): if indegree[i] == 0: queue.append(SCREAMING_SNAKE_CASE ) while queue: a__ : int =queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: a__ : str =long_dist[vertex] + 1 if indegree[x] == 0: queue.append(SCREAMING_SNAKE_CASE ) print(max(SCREAMING_SNAKE_CASE ) ) # Adjacency list of Graph UpperCAmelCase : Union[str, Any] = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
95
"""simple docstring""" import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor __SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) class __A (snake_case__): '''simple docstring''' def __init__( self : str , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int ) ->None: """simple docstring""" warnings.warn( """The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use MobileViTImageProcessor instead.""" , UpperCAmelCase_ , ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ )
347
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase__ = { """configuration_time_series_transformer""": [ """TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TimeSeriesTransformerConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ """TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TimeSeriesTransformerForPrediction""", """TimeSeriesTransformerModel""", """TimeSeriesTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys lowercase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
96
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Any: snake_case_ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"""blocks.{i}.norm1.weight""", f"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """vit.embeddings.cls_token"""), ("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" snake_case_ = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) return rename_keys def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Tuple: for i in range(config.num_hidden_layers ): if base_model: snake_case_ = """""" else: snake_case_ = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case_ = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" ) snake_case_ = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict snake_case_ = in_proj_weight[ : config.hidden_size, : ] snake_case_ = in_proj_bias[: config.hidden_size] snake_case_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case_ = in_proj_weight[ -config.hidden_size :, : ] snake_case_ = in_proj_bias[-config.hidden_size :] def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: snake_case_ = dct.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = val def _a ( ) -> Any: snake_case_ = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = ViTConfig() snake_case_ = False # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size if vit_name[-5:] == "in21k": snake_case_ = True snake_case_ = int(vit_name[-12:-10] ) snake_case_ = int(vit_name[-9:-6] ) else: snake_case_ = 1_000 snake_case_ = """huggingface/label-files""" snake_case_ = """imagenet-1k-id2label.json""" snake_case_ = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) snake_case_ = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} snake_case_ = idalabel snake_case_ = {v: k for k, v in idalabel.items()} snake_case_ = int(vit_name[-6:-4] ) snake_case_ = int(vit_name[-3:] ) # size of the architecture if "deit" in vit_name: if vit_name[9:].startswith("""tiny""" ): snake_case_ = 192 snake_case_ = 768 snake_case_ = 12 snake_case_ = 3 elif vit_name[9:].startswith("""small""" ): snake_case_ = 384 snake_case_ = 1_536 snake_case_ = 12 snake_case_ = 6 else: pass else: if vit_name[4:].startswith("""small""" ): snake_case_ = 768 snake_case_ = 2_304 snake_case_ = 8 snake_case_ = 8 elif vit_name[4:].startswith("""base""" ): pass elif vit_name[4:].startswith("""large""" ): snake_case_ = 1_024 snake_case_ = 4_096 snake_case_ = 24 snake_case_ = 16 elif vit_name[4:].startswith("""huge""" ): snake_case_ = 1_280 snake_case_ = 5_120 snake_case_ = 32 snake_case_ = 16 # load original model from timm snake_case_ = timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ) timm_model.eval() # load state_dict of original model, remove and rename some keys snake_case_ = timm_model.state_dict() if base_model: remove_classification_head_(_SCREAMING_SNAKE_CASE ) snake_case_ = create_rename_keys(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for src, dest in rename_keys: rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) read_in_q_k_v(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load HuggingFace model if vit_name[-5:] == "in21k": snake_case_ = ViTModel(_SCREAMING_SNAKE_CASE ).eval() else: snake_case_ = ViTForImageClassification(_SCREAMING_SNAKE_CASE ).eval() model.load_state_dict(_SCREAMING_SNAKE_CASE ) # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor if "deit" in vit_name: snake_case_ = DeiTImageProcessor(size=config.image_size ) else: snake_case_ = ViTImageProcessor(size=config.image_size ) snake_case_ = image_processor(images=prepare_img() , return_tensors="""pt""" ) snake_case_ = encoding["""pixel_values"""] snake_case_ = model(_SCREAMING_SNAKE_CASE ) if base_model: snake_case_ = timm_model.forward_features(_SCREAMING_SNAKE_CASE ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(_SCREAMING_SNAKE_CASE , outputs.pooler_output , atol=1E-3 ) else: snake_case_ = timm_model(_SCREAMING_SNAKE_CASE ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_SCREAMING_SNAKE_CASE , outputs.logits , atol=1E-3 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(f"""Saving model {vit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--vit_name', default='vit_base_patch16_224', type=str, help='Name of the ViT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) __SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
347
0
'''simple docstring''' def a ( __a , __a , __a=False ) -> str: '''simple docstring''' if isinstance(__a , __a ) and isinstance(__a , __a ): UpperCamelCase__ :List[str] = len(set_a.intersection(__a ) ) if alternative_union: UpperCamelCase__ :Optional[Any] = len(__a ) + len(__a ) else: UpperCamelCase__ :Union[str, Any] = len(set_a.union(__a ) ) return intersection / union if isinstance(__a , (list, tuple) ) and isinstance(__a , (list, tuple) ): UpperCamelCase__ :Tuple = [element for element in set_a if element in set_b] if alternative_union: UpperCamelCase__ :Dict = len(__a ) + len(__a ) return len(__a ) / union else: UpperCamelCase__ :List[Any] = set_a + [element for element in set_b if element not in set_a] return len(__a ) / len(__a ) return len(__a ) / len(__a ) return None if __name__ == "__main__": __snake_case = {'''a''', '''b''', '''c''', '''d''', '''e'''} __snake_case = {'''c''', '''d''', '''e''', '''f''', '''h''', '''i'''} print(jaccard_similarity(set_a, set_b))
97
"""simple docstring""" import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __A (unittest.TestCase): '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple=13 , UpperCAmelCase_ : List[Any]=7 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Dict=99 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : Tuple=5 , UpperCAmelCase_ : Union[str, Any]=4 , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : int="gelu" , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : Dict=512 , UpperCAmelCase_ : Optional[Any]=16 , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : str=0.02 , UpperCAmelCase_ : str=4 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_attention_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_choices def lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_attention_mask: snake_case_ = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = 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 , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Union[str, Any] = True __lowercase: int = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" snake_case_ = FlaxRoFormerModelTester(self ) @slow def lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=UpperCAmelCase_ ) snake_case_ = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCAmelCase_ ) @require_flax class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" snake_case_ = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) snake_case_ = jnp.array([[0, 1, 2, 3, 4, 5]] ) snake_case_ = model(UpperCAmelCase_ )[0] snake_case_ = 50_000 snake_case_ = (1, 6, vocab_size) self.assertEqual(output.shape , UpperCAmelCase_ ) snake_case_ = jnp.array( [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) )
347
0
"""simple docstring""" import requests from bsa import BeautifulSoup def a_ ( lowerCamelCase , lowerCamelCase ): UpperCAmelCase__ = BeautifulSoup(requests.get(lowerCamelCase , params=lowerCamelCase ).content , 'html.parser' ) UpperCAmelCase__ = soup.find('div' , attrs={'class': 'gs_ri'} ) UpperCAmelCase__ = div.find('div' , attrs={'class': 'gs_fl'} ).find_all('a' ) return anchors[2].get_text() if __name__ == "__main__": lowerCAmelCase__ : Optional[int] = { 'title': ( 'Precisely geometry controlled microsupercapacitors for ultrahigh areal ' 'capacitance, volumetric capacitance, and energy density' ), 'journal': 'Chem. Mater.', 'volume': 30, 'pages': '3979-3990', 'year': 2_018, 'hl': 'en', } print(get_citation('https://scholar.google.com/scholar_lookup', params=params))
98
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> bool: snake_case_ = get_failure_array(_SCREAMING_SNAKE_CASE ) # 2) Step through text searching for pattern snake_case_ , snake_case_ = 0, 0 # index into text, pattern while i < len(_SCREAMING_SNAKE_CASE ): if pattern[j] == text[i]: if j == (len(_SCREAMING_SNAKE_CASE ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: snake_case_ = failure[j - 1] continue i += 1 return False def _a ( _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = [0] snake_case_ = 0 snake_case_ = 1 while j < len(_SCREAMING_SNAKE_CASE ): if pattern[i] == pattern[j]: i += 1 elif i > 0: snake_case_ = failure[i - 1] continue j += 1 failure.append(_SCREAMING_SNAKE_CASE ) return failure if __name__ == "__main__": # Test 1) __SCREAMING_SNAKE_CASE : Optional[int] = 'abc1abc12' __SCREAMING_SNAKE_CASE : Optional[int] = 'alskfjaldsabc1abc1abc12k23adsfabcabc' __SCREAMING_SNAKE_CASE : List[str] = 'alskfjaldsk23adsfabcabc' assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) __SCREAMING_SNAKE_CASE : int = 'ABABX' __SCREAMING_SNAKE_CASE : Optional[Any] = 'ABABZABABYABABX' assert kmp(pattern, text) # Test 3) __SCREAMING_SNAKE_CASE : Any = 'AAAB' __SCREAMING_SNAKE_CASE : List[Any] = 'ABAAAAAB' assert kmp(pattern, text) # Test 4) __SCREAMING_SNAKE_CASE : Optional[int] = 'abcdabcy' __SCREAMING_SNAKE_CASE : str = 'abcxabcdabxabcdabcdabcy' assert kmp(pattern, text) # Test 5) __SCREAMING_SNAKE_CASE : Any = 'aabaabaaa' assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
347
0
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def A_ ( A__ ) -> float: return np.dot(A__ , A__ ) class A__ : """simple docstring""" def __init__( self , *, lowercase = np.inf , lowercase = "linear" , lowercase = 0.0 , ) -> None: '''simple docstring''' a__ : Tuple = regularization a__ : Optional[Any] = gamma if kernel == "linear": a__ : Optional[Any] = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError('rbf kernel requires gamma') if not isinstance(self.gamma , (float, int)): raise ValueError('gamma must be float or int') if not self.gamma > 0: raise ValueError('gamma must be > 0') a__ : str = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: a__ : Optional[int] = F'Unknown kernel: {kernel}' raise ValueError(lowercase) def __lowercase ( self , lowercase , lowercase) -> float: '''simple docstring''' return np.dot(lowercase , lowercase) def __lowercase ( self , lowercase , lowercase) -> float: '''simple docstring''' return np.exp(-(self.gamma * norm_squared(vectora - vectora))) def __lowercase ( self , lowercase , lowercase) -> None: '''simple docstring''' a__ : List[str] = observations a__ : Dict = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((a__) , ) : Optional[int] = np.shape(lowercase) def to_minimize(lowercase) -> float: a__ : Tuple = 0 ((a__) , ) : Optional[int] = np.shape(lowercase) for i in range(lowercase): for j in range(lowercase): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j]) ) return 1 / 2 * s - sum(lowercase) a__ : Optional[Any] = LinearConstraint(lowercase , 0 , 0) a__ : str = Bounds(0 , self.regularization) a__ : List[str] = minimize( lowercase , np.ones(lowercase) , bounds=lowercase , constraints=[ly_contraint]).x a__ : Dict = l_star # calculating mean offset of separation plane to points a__ : int = 0 for i in range(lowercase): for j in range(lowercase): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j]) a__ : List[str] = s / n def __lowercase ( self , lowercase) -> int: '''simple docstring''' a__ : int = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , lowercase) for n in range(len(self.classes))) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
99
"""simple docstring""" from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class __A (snake_case__): '''simple docstring''' @slow @require_torch def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = EncoderDecoderModel.from_encoder_decoder_pretrained("""prajjwal1/bert-tiny""" , """prajjwal1/bert-tiny""" ) snake_case_ = BertTokenizer.from_pretrained("""bert-base-uncased""" ) snake_case_ = bertabert.config.encoder.vocab_size snake_case_ = tokenizer.sep_token_id snake_case_ = tokenizer.cls_token_id snake_case_ = 128 snake_case_ = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""train[:1%]""" ) snake_case_ = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""validation[:1%]""" ) snake_case_ = train_dataset.select(range(32 ) ) snake_case_ = val_dataset.select(range(16 ) ) snake_case_ = 4 def _map_to_encoder_decoder_inputs(UpperCAmelCase_ : int ): # Tokenizer will automatically set [BOS] <text> [EOS] snake_case_ = tokenizer(batch["""article"""] , padding="""max_length""" , truncation=UpperCAmelCase_ , max_length=512 ) snake_case_ = tokenizer(batch["""highlights"""] , padding="""max_length""" , truncation=UpperCAmelCase_ , max_length=128 ) snake_case_ = inputs.input_ids snake_case_ = inputs.attention_mask snake_case_ = outputs.input_ids snake_case_ = outputs.input_ids.copy() snake_case_ = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["""labels"""] ] snake_case_ = outputs.attention_mask assert all(len(UpperCAmelCase_ ) == 512 for x in inputs.input_ids ) assert all(len(UpperCAmelCase_ ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(UpperCAmelCase_ : Union[str, Any] ): snake_case_ = pred.label_ids snake_case_ = pred.predictions # all unnecessary tokens are removed snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = sum([int(pred_str[i] == label_str[i] ) for i in range(len(UpperCAmelCase_ ) )] ) / len(UpperCAmelCase_ ) return {"accuracy": accuracy} # map train dataset snake_case_ = train_dataset.map( _map_to_encoder_decoder_inputs , batched=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , remove_columns=["""article""", """highlights"""] , ) train_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) # same for validation dataset snake_case_ = val_dataset.map( _map_to_encoder_decoder_inputs , batched=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , remove_columns=["""article""", """highlights"""] , ) val_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) snake_case_ = self.get_auto_remove_tmp_dir() snake_case_ = SeqaSeqTrainingArguments( output_dir=UpperCAmelCase_ , per_device_train_batch_size=UpperCAmelCase_ , per_device_eval_batch_size=UpperCAmelCase_ , predict_with_generate=UpperCAmelCase_ , evaluation_strategy="""steps""" , do_train=UpperCAmelCase_ , do_eval=UpperCAmelCase_ , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer snake_case_ = SeqaSeqTrainer( model=UpperCAmelCase_ , args=UpperCAmelCase_ , compute_metrics=_compute_metrics , train_dataset=UpperCAmelCase_ , eval_dataset=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ , ) # start training trainer.train()
347
0
"""simple docstring""" from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch __magic_name__ = logging.get_logger(__name__) @add_end_docstrings( __a , R''' top_k (`int`, defaults to 5): The number of predictions to return. targets (`str` or `List[str]`, *optional*): When passed, the model will limit the scores to the passed targets instead of looking up in the whole vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting token will be used (with a warning, and that might be slower). ''' , ) class SCREAMING_SNAKE_CASE_ ( __a ): """simple docstring""" def snake_case_ ( self , lowerCAmelCase__): if self.framework == "tf": __SCREAMING_SNAKE_CASE = tf.where(input_ids == self.tokenizer.mask_token_id).numpy() elif self.framework == "pt": __SCREAMING_SNAKE_CASE = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=lowerCAmelCase__) else: raise ValueError("""Unsupported framework""") return masked_index def snake_case_ ( self , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = self.get_masked_index(lowerCAmelCase__) __SCREAMING_SNAKE_CASE = np.prod(masked_index.shape) if numel < 1: raise PipelineException( """fill-mask""" , self.model.base_model_prefix , f"No mask_token ({self.tokenizer.mask_token}) found on the input" , ) def snake_case_ ( self , lowerCAmelCase__): if isinstance(lowerCAmelCase__ , lowerCAmelCase__): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input["""input_ids"""][0]) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(lowerCAmelCase__) def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__=None , **lowerCAmelCase__): if return_tensors is None: __SCREAMING_SNAKE_CASE = self.framework __SCREAMING_SNAKE_CASE = self.tokenizer(lowerCAmelCase__ , return_tensors=lowerCAmelCase__) self.ensure_exactly_one_mask_token(lowerCAmelCase__) return model_inputs def snake_case_ ( self , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = self.model(**lowerCAmelCase__) __SCREAMING_SNAKE_CASE = model_inputs["""input_ids"""] return model_outputs def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__=5 , lowerCAmelCase__=None): # Cap top_k if there are targets if target_ids is not None and target_ids.shape[0] < top_k: __SCREAMING_SNAKE_CASE = target_ids.shape[0] __SCREAMING_SNAKE_CASE = model_outputs["""input_ids"""][0] __SCREAMING_SNAKE_CASE = model_outputs["""logits"""] if self.framework == "tf": __SCREAMING_SNAKE_CASE = tf.where(input_ids == self.tokenizer.mask_token_id).numpy()[:, 0] __SCREAMING_SNAKE_CASE = outputs.numpy() __SCREAMING_SNAKE_CASE = outputs[0, masked_index, :] __SCREAMING_SNAKE_CASE = stable_softmax(lowerCAmelCase__ , axis=-1) if target_ids is not None: __SCREAMING_SNAKE_CASE = tf.gather_nd(tf.squeeze(lowerCAmelCase__ , 0) , target_ids.reshape(-1 , 1)) __SCREAMING_SNAKE_CASE = tf.expand_dims(lowerCAmelCase__ , 0) __SCREAMING_SNAKE_CASE = tf.math.top_k(lowerCAmelCase__ , k=lowerCAmelCase__) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = topk.values.numpy(), topk.indices.numpy() else: __SCREAMING_SNAKE_CASE = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=lowerCAmelCase__).squeeze(-1) # Fill mask pipeline supports only one ${mask_token} per sample __SCREAMING_SNAKE_CASE = outputs[0, masked_index, :] __SCREAMING_SNAKE_CASE = logits.softmax(dim=-1) if target_ids is not None: __SCREAMING_SNAKE_CASE = probs[..., target_ids] __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = probs.topk(lowerCAmelCase__) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist())): __SCREAMING_SNAKE_CASE = [] for v, p in zip(_values , _predictions): # Copy is important since we're going to modify this array in place __SCREAMING_SNAKE_CASE = input_ids.numpy().copy() if target_ids is not None: __SCREAMING_SNAKE_CASE = target_ids[p].tolist() __SCREAMING_SNAKE_CASE = p # Filter padding out: __SCREAMING_SNAKE_CASE = tokens[np.where(tokens != self.tokenizer.pad_token_id)] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back __SCREAMING_SNAKE_CASE = self.tokenizer.decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__) __SCREAMING_SNAKE_CASE = {"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p]), """sequence""": sequence} row.append(lowerCAmelCase__) result.append(lowerCAmelCase__) if single_mask: return result[0] return result def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__=None): if isinstance(lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = [targets] try: __SCREAMING_SNAKE_CASE = self.tokenizer.get_vocab() except Exception: __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = [] for target in targets: __SCREAMING_SNAKE_CASE = vocab.get(lowerCAmelCase__ , lowerCAmelCase__) if id_ is None: __SCREAMING_SNAKE_CASE = self.tokenizer( lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , return_token_type_ids=lowerCAmelCase__ , max_length=1 , truncation=lowerCAmelCase__ , )["""input_ids"""] if len(lowerCAmelCase__) == 0: logger.warning( f"The specified target token `{target}` does not exist in the model vocabulary. " """We cannot replace it with anything meaningful, ignoring it""") continue __SCREAMING_SNAKE_CASE = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( f"The specified target token `{target}` does not exist in the model vocabulary. " f"Replacing with `{self.tokenizer.convert_ids_to_tokens(id_)}`.") target_ids.append(id_) __SCREAMING_SNAKE_CASE = list(set(lowerCAmelCase__)) if len(lowerCAmelCase__) == 0: raise ValueError("""At least one target must be provided when passed.""") __SCREAMING_SNAKE_CASE = np.array(lowerCAmelCase__) return target_ids def snake_case_ ( self , lowerCAmelCase__=None , lowerCAmelCase__=None): __SCREAMING_SNAKE_CASE = {} if targets is not None: __SCREAMING_SNAKE_CASE = self.get_target_ids(lowerCAmelCase__ , lowerCAmelCase__) __SCREAMING_SNAKE_CASE = target_ids if top_k is not None: __SCREAMING_SNAKE_CASE = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( """fill-mask""" , self.model.base_model_prefix , """The tokenizer does not define a `mask_token`.""") return {}, {}, postprocess_params def __call__( self , lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__): __SCREAMING_SNAKE_CASE = super().__call__(lowerCAmelCase__ , **lowerCAmelCase__) if isinstance(lowerCAmelCase__ , lowerCAmelCase__) and len(lowerCAmelCase__) == 1: return outputs[0] return outputs
100
"""simple docstring""" # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys __SCREAMING_SNAKE_CASE : Tuple = subprocess.check_output('git merge-base main HEAD'.split()).decode('utf-8') __SCREAMING_SNAKE_CASE : Tuple = subprocess.check_output(f"""git diff --name-only {fork_point_sha}""".split()).decode('utf-8').split() __SCREAMING_SNAKE_CASE : Any = '|'.join(sys.argv[1:]) __SCREAMING_SNAKE_CASE : Optional[Any] = re.compile(Rf"""^({joined_dirs}).*?\.py$""") __SCREAMING_SNAKE_CASE : List[str] = [x for x in modified_files if regex.match(x)] print(' '.join(relevant_modified_files), end='')
347
0