code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" import numpy as np lowerCAmelCase_ = [ ['''a''', '''b''', '''c''', '''d''', '''e'''], ['''f''', '''g''', '''h''', '''i''', '''k'''], ['''l''', '''m''', '''n''', '''o''', '''p'''], ['''q''', '''r''', '''s''', '''t''', '''u'''], ['''v''', '''w''', '''x''', '''y''', '''z'''], ] class _snake_case : """simple docstring""" def __init__( self : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = np.array(_A) def _lowerCAmelCase ( self : Optional[Any] , _A : str): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = np.where(letter == self.SQUARE) _SCREAMING_SNAKE_CASE : Optional[int] = np.concatenate([indexa + 1, indexa + 1]) return indexes def _lowerCAmelCase ( self : Union[str, Any] , _A : int , _A : int): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = self.SQUARE[indexa - 1, indexa - 1] return letter def _lowerCAmelCase ( self : Union[str, Any] , _A : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = message.lower() _SCREAMING_SNAKE_CASE : int = message.replace(""" """ , """""") _SCREAMING_SNAKE_CASE : List[Any] = message.replace("""j""" , """i""") _SCREAMING_SNAKE_CASE : Dict = np.empty((2, len(_A))) for letter_index in range(len(_A)): _SCREAMING_SNAKE_CASE : Optional[int] = self.letter_to_numbers(message[letter_index]) _SCREAMING_SNAKE_CASE : Union[str, Any] = numbers[0] _SCREAMING_SNAKE_CASE : Union[str, Any] = numbers[1] _SCREAMING_SNAKE_CASE : Dict = first_step.reshape(2 * len(_A)) _SCREAMING_SNAKE_CASE : int = """""" for numbers_index in range(len(_A)): _SCREAMING_SNAKE_CASE : int = int(second_step[numbers_index * 2]) _SCREAMING_SNAKE_CASE : Optional[int] = int(second_step[(numbers_index * 2) + 1]) _SCREAMING_SNAKE_CASE : Tuple = self.numbers_to_letter(_A , _A) _SCREAMING_SNAKE_CASE : List[Any] = encoded_message + letter return encoded_message def _lowerCAmelCase ( self : Tuple , _A : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = message.lower() message.replace(""" """ , """""") _SCREAMING_SNAKE_CASE : Tuple = np.empty(2 * len(_A)) for letter_index in range(len(_A)): _SCREAMING_SNAKE_CASE : str = self.letter_to_numbers(message[letter_index]) _SCREAMING_SNAKE_CASE : Optional[Any] = numbers[0] _SCREAMING_SNAKE_CASE : int = numbers[1] _SCREAMING_SNAKE_CASE : int = first_step.reshape((2, len(_A))) _SCREAMING_SNAKE_CASE : List[str] = """""" for numbers_index in range(len(_A)): _SCREAMING_SNAKE_CASE : Union[str, Any] = int(second_step[0, numbers_index]) _SCREAMING_SNAKE_CASE : int = int(second_step[1, numbers_index]) _SCREAMING_SNAKE_CASE : List[str] = self.numbers_to_letter(_A , _A) _SCREAMING_SNAKE_CASE : Tuple = decoded_message + letter return decoded_message
635
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = ['''model.decoder.embed_positions.weights'''] def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[int]: if "emb" in name: _SCREAMING_SNAKE_CASE : List[Any] = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: _SCREAMING_SNAKE_CASE : List[str] = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: _SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: _SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: _SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: _SCREAMING_SNAKE_CASE : int = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: _SCREAMING_SNAKE_CASE : Dict = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: _SCREAMING_SNAKE_CASE : Dict = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: _SCREAMING_SNAKE_CASE : Tuple = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: _SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: _SCREAMING_SNAKE_CASE : str = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple[Dict, Dict]: _SCREAMING_SNAKE_CASE : str = list(state_dict.keys() ) _SCREAMING_SNAKE_CASE : Tuple = {} for key in keys: _SCREAMING_SNAKE_CASE : Dict = state_dict.pop(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : int = rename_keys(__SCREAMING_SNAKE_CASE ) if "in_proj_weight" in key: # split fused qkv proj _SCREAMING_SNAKE_CASE : str = val[:hidden_size, :] _SCREAMING_SNAKE_CASE : Any = val[hidden_size : 2 * hidden_size, :] _SCREAMING_SNAKE_CASE : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: _SCREAMING_SNAKE_CASE : int = val else: _SCREAMING_SNAKE_CASE : Dict = val return state_dict, enc_dec_proj_state_dict def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> MusicgenDecoderConfig: if checkpoint == "small": # default config values _SCREAMING_SNAKE_CASE : Optional[Any] = 1_024 _SCREAMING_SNAKE_CASE : str = 24 _SCREAMING_SNAKE_CASE : Any = 16 elif checkpoint == "medium": _SCREAMING_SNAKE_CASE : Dict = 1_536 _SCREAMING_SNAKE_CASE : Union[str, Any] = 48 _SCREAMING_SNAKE_CASE : Optional[Any] = 24 elif checkpoint == "large": _SCREAMING_SNAKE_CASE : List[Any] = 2_048 _SCREAMING_SNAKE_CASE : Optional[int] = 48 _SCREAMING_SNAKE_CASE : str = 32 else: raise ValueError(F"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) _SCREAMING_SNAKE_CASE : Optional[Any] = MusicgenDecoderConfig( hidden_size=__SCREAMING_SNAKE_CASE , ffn_dim=hidden_size * 4 , num_hidden_layers=__SCREAMING_SNAKE_CASE , num_attention_heads=__SCREAMING_SNAKE_CASE , ) return config @torch.no_grad() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="cpu" )-> str: _SCREAMING_SNAKE_CASE : str = MusicGen.get_pretrained(__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[str] = decoder_config_from_checkpoint(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[Any] = fairseq_model.lm.state_dict() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = rename_state_dict( __SCREAMING_SNAKE_CASE , hidden_size=decoder_config.hidden_size ) _SCREAMING_SNAKE_CASE : Tuple = TaEncoderModel.from_pretrained("""t5-base""" ) _SCREAMING_SNAKE_CASE : List[Any] = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) _SCREAMING_SNAKE_CASE : str = MusicgenForCausalLM(__SCREAMING_SNAKE_CASE ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = decoder.load_state_dict(__SCREAMING_SNAKE_CASE , strict=__SCREAMING_SNAKE_CASE ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ValueError(F"""Missing key(s) in state_dict: {missing_keys}""" ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ValueError(F"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model _SCREAMING_SNAKE_CASE : Dict = MusicgenForConditionalGeneration(text_encoder=__SCREAMING_SNAKE_CASE , audio_encoder=__SCREAMING_SNAKE_CASE , decoder=__SCREAMING_SNAKE_CASE ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(__SCREAMING_SNAKE_CASE ) # check we can do a forward pass _SCREAMING_SNAKE_CASE : Optional[Any] = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) _SCREAMING_SNAKE_CASE : Dict = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[int] = model(input_ids=__SCREAMING_SNAKE_CASE , decoder_input_ids=__SCREAMING_SNAKE_CASE ).logits if logits.shape != (8, 1, 2_048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor _SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained("""t5-base""" ) _SCREAMING_SNAKE_CASE : List[str] = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) _SCREAMING_SNAKE_CASE : Optional[int] = MusicgenProcessor(feature_extractor=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE ) # set the appropriate bos/pad token ids _SCREAMING_SNAKE_CASE : Optional[Any] = 2_048 _SCREAMING_SNAKE_CASE : List[Any] = 2_048 # set other default generation config params _SCREAMING_SNAKE_CASE : Any = int(30 * audio_encoder.config.frame_rate ) _SCREAMING_SNAKE_CASE : Tuple = True _SCREAMING_SNAKE_CASE : int = 3.0 if pytorch_dump_folder is not None: Path(__SCREAMING_SNAKE_CASE ).mkdir(exist_ok=__SCREAMING_SNAKE_CASE ) logger.info(F"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) processor.save_pretrained(__SCREAMING_SNAKE_CASE ) if repo_id: logger.info(F"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(__SCREAMING_SNAKE_CASE ) processor.push_to_hub(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint''', default='''small''', type=str, help='''Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.''', ) parser.add_argument( '''--pytorch_dump_folder''', required=True, default=None, type=str, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) parser.add_argument( '''--device''', default='''cpu''', type=str, help='''Torch device to run the conversion, either cpu or cuda.''' ) lowerCAmelCase_ = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
635
1
"""simple docstring""" import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader, TensorDataset from utils_ner import TokenClassificationTask lowerCAmelCase_ = logging.getLogger(__name__) class _snake_case ( __snake_case ): """simple docstring""" a = "token-classification" def __init__( self : Dict , _A : int): """simple docstring""" if type(_A) == dict: _SCREAMING_SNAKE_CASE : Dict = Namespace(**_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = import_module("""tasks""") try: _SCREAMING_SNAKE_CASE : Any = getattr(_A , hparams.task_type) _SCREAMING_SNAKE_CASE : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( f"""Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. """ f"""Available tasks classes are: {TokenClassificationTask.__subclasses__()}""") _SCREAMING_SNAKE_CASE : Any = self.token_classification_task.get_labels(hparams.labels) _SCREAMING_SNAKE_CASE : Dict = CrossEntropyLoss().ignore_index super().__init__(_A , len(self.labels) , self.mode) def _lowerCAmelCase ( self : Optional[Any] , **_A : Dict): """simple docstring""" return self.model(**_A) def _lowerCAmelCase ( self : Optional[Any] , _A : Any , _A : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type != "distilbert": _SCREAMING_SNAKE_CASE : Dict = ( batch[2] if self.config.model_type in ["""bert""", """xlnet"""] else None ) # XLM and RoBERTa don"t use token_type_ids _SCREAMING_SNAKE_CASE : Optional[Any] = self(**_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = outputs[0] # tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]} return {"loss": loss} def _lowerCAmelCase ( self : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = self.hparams for mode in ["train", "dev", "test"]: _SCREAMING_SNAKE_CASE : List[str] = self._feature_file(_A) if os.path.exists(_A) and not args.overwrite_cache: logger.info("""Loading features from cached file %s""" , _A) _SCREAMING_SNAKE_CASE : List[str] = torch.load(_A) else: logger.info("""Creating features from dataset file at %s""" , args.data_dir) _SCREAMING_SNAKE_CASE : List[Any] = self.token_classification_task.read_examples_from_file(args.data_dir , _A) _SCREAMING_SNAKE_CASE : Optional[int] = self.token_classification_task.convert_examples_to_features( _A , self.labels , args.max_seq_length , self.tokenizer , cls_token_at_end=bool(self.config.model_type in ["""xlnet"""]) , cls_token=self.tokenizer.cls_token , cls_token_segment_id=2 if self.config.model_type in ["""xlnet"""] else 0 , sep_token=self.tokenizer.sep_token , sep_token_extra=_A , pad_on_left=bool(self.config.model_type in ["""xlnet"""]) , pad_token=self.tokenizer.pad_token_id , pad_token_segment_id=self.tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info("""Saving features into cached file %s""" , _A) torch.save(_A , _A) def _lowerCAmelCase ( self : Dict , _A : int , _A : int , _A : bool = False): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = self._feature_file(_A) logger.info("""Loading features from cached file %s""" , _A) _SCREAMING_SNAKE_CASE : List[Any] = torch.load(_A) _SCREAMING_SNAKE_CASE : List[str] = torch.tensor([f.input_ids for f in features] , dtype=torch.long) _SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([f.attention_mask for f in features] , dtype=torch.long) if features[0].token_type_ids is not None: _SCREAMING_SNAKE_CASE : Dict = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long) else: _SCREAMING_SNAKE_CASE : Any = torch.tensor([0 for f in features] , dtype=torch.long) # HACK(we will not use this anymore soon) _SCREAMING_SNAKE_CASE : Tuple = torch.tensor([f.label_ids for f in features] , dtype=torch.long) return DataLoader( TensorDataset(_A , _A , _A , _A) , batch_size=_A) def _lowerCAmelCase ( self : Dict , _A : Any , _A : str): """simple docstring""" """Compute validation""" "" _SCREAMING_SNAKE_CASE : Tuple = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type != "distilbert": _SCREAMING_SNAKE_CASE : Optional[int] = ( batch[2] if self.config.model_type in ["""bert""", """xlnet"""] else None ) # XLM and RoBERTa don"t use token_type_ids _SCREAMING_SNAKE_CASE : int = self(**_A) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = outputs[:2] _SCREAMING_SNAKE_CASE : Tuple = logits.detach().cpu().numpy() _SCREAMING_SNAKE_CASE : Any = inputs["""labels"""].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def _lowerCAmelCase ( self : int , _A : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = torch.stack([x["""val_loss"""] for x in outputs]).mean() _SCREAMING_SNAKE_CASE : Union[str, Any] = np.concatenate([x["""pred"""] for x in outputs] , axis=0) _SCREAMING_SNAKE_CASE : int = np.argmax(_A , axis=2) _SCREAMING_SNAKE_CASE : Tuple = np.concatenate([x["""target"""] for x in outputs] , axis=0) _SCREAMING_SNAKE_CASE : Optional[Any] = dict(enumerate(self.labels)) _SCREAMING_SNAKE_CASE : str = [[] for _ in range(out_label_ids.shape[0])] _SCREAMING_SNAKE_CASE : List[Any] = [[] for _ in range(out_label_ids.shape[0])] for i in range(out_label_ids.shape[0]): for j in range(out_label_ids.shape[1]): if out_label_ids[i, j] != self.pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]]) preds_list[i].append(label_map[preds[i][j]]) _SCREAMING_SNAKE_CASE : Dict = { """val_loss""": val_loss_mean, """accuracy_score""": accuracy_score(_A , _A), """precision""": precision_score(_A , _A), """recall""": recall_score(_A , _A), """f1""": fa_score(_A , _A), } _SCREAMING_SNAKE_CASE : Tuple = dict(results.items()) _SCREAMING_SNAKE_CASE : int = results return ret, preds_list, out_label_list def _lowerCAmelCase ( self : Optional[int] , _A : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = self._eval_end(_A) _SCREAMING_SNAKE_CASE : Dict = ret["""log"""] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def _lowerCAmelCase ( self : int , _A : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self._eval_end(_A) # Converting to the dict required by pl # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\ # pytorch_lightning/trainer/logging.py#L139 _SCREAMING_SNAKE_CASE : str = ret["""log"""] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def _lowerCAmelCase ( _A : Optional[int] , _A : int): """simple docstring""" BaseTransformer.add_model_specific_args(_A , _A) parser.add_argument( """--task_type""" , default="""NER""" , type=_A , help="""Task type to fine tune in training (e.g. NER, POS, etc)""") parser.add_argument( """--max_seq_length""" , default=1_2_8 , type=_A , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--labels""" , default="""""" , type=_A , help="""Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.""" , ) parser.add_argument( """--gpus""" , default=0 , type=_A , help="""The number of GPUs allocated for this, it is by default 0 meaning none""" , ) parser.add_argument( """--overwrite_cache""" , action="""store_true""" , help="""Overwrite the cached training and evaluation sets""") return parser if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() add_generic_args(parser, os.getcwd()) lowerCAmelCase_ = NERTransformer.add_model_specific_args(parser, os.getcwd()) lowerCAmelCase_ = parser.parse_args() lowerCAmelCase_ = NERTransformer(args) lowerCAmelCase_ = generic_train(model, args) if args.do_predict: # See https://github.com/huggingface/transformers/issues/3159 # pl use this default format to create a checkpoint: # https://github.com/PyTorchLightning/pytorch-lightning/blob/master\ # /pytorch_lightning/callbacks/model_checkpoint.py#L322 lowerCAmelCase_ = sorted(glob.glob(os.path.join(args.output_dir, '''checkpoint-epoch=*.ckpt'''), recursive=True)) lowerCAmelCase_ = model.load_from_checkpoint(checkpoints[-1]) trainer.test(model)
635
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''asapp/sew-tiny-100k''': '''https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json''', # See all SEW models at https://huggingface.co/models?filter=sew } class _snake_case ( __snake_case ): """simple docstring""" a = "sew" def __init__( self : List[Any] , _A : Tuple=3_2 , _A : str=7_6_8 , _A : Dict=1_2 , _A : Tuple=1_2 , _A : Optional[Any]=3_0_7_2 , _A : List[str]=2 , _A : Dict="gelu" , _A : Union[str, Any]=0.1 , _A : Optional[int]=0.1 , _A : Optional[int]=0.1 , _A : Optional[int]=0.0 , _A : str=0.1 , _A : Tuple=0.1 , _A : Optional[int]=0.02 , _A : Dict=1e-5 , _A : str="group" , _A : Tuple="gelu" , _A : Union[str, Any]=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , _A : Optional[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , _A : Any=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , _A : Tuple=False , _A : Tuple=1_2_8 , _A : int=1_6 , _A : Union[str, Any]=True , _A : Optional[Any]=0.05 , _A : List[Any]=1_0 , _A : Union[str, Any]=2 , _A : Tuple=0.0 , _A : Union[str, Any]=1_0 , _A : Optional[int]=0 , _A : Union[str, Any]="mean" , _A : Optional[int]=False , _A : List[Any]=False , _A : int=2_5_6 , _A : str=0 , _A : Optional[int]=1 , _A : List[Any]=2 , **_A : Dict , ): """simple docstring""" super().__init__(**_A , pad_token_id=_A , bos_token_id=_A , eos_token_id=_A) _SCREAMING_SNAKE_CASE : str = hidden_size _SCREAMING_SNAKE_CASE : Optional[int] = feat_extract_norm _SCREAMING_SNAKE_CASE : Optional[int] = feat_extract_activation _SCREAMING_SNAKE_CASE : Dict = list(_A) _SCREAMING_SNAKE_CASE : int = list(_A) _SCREAMING_SNAKE_CASE : int = list(_A) _SCREAMING_SNAKE_CASE : str = conv_bias _SCREAMING_SNAKE_CASE : Tuple = num_conv_pos_embeddings _SCREAMING_SNAKE_CASE : List[str] = num_conv_pos_embedding_groups _SCREAMING_SNAKE_CASE : Tuple = len(self.conv_dim) _SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers _SCREAMING_SNAKE_CASE : List[str] = intermediate_size _SCREAMING_SNAKE_CASE : str = squeeze_factor _SCREAMING_SNAKE_CASE : Dict = hidden_act _SCREAMING_SNAKE_CASE : str = num_attention_heads _SCREAMING_SNAKE_CASE : Dict = hidden_dropout _SCREAMING_SNAKE_CASE : Tuple = attention_dropout _SCREAMING_SNAKE_CASE : int = activation_dropout _SCREAMING_SNAKE_CASE : Any = feat_proj_dropout _SCREAMING_SNAKE_CASE : str = final_dropout _SCREAMING_SNAKE_CASE : Union[str, Any] = layerdrop _SCREAMING_SNAKE_CASE : Any = layer_norm_eps _SCREAMING_SNAKE_CASE : int = initializer_range _SCREAMING_SNAKE_CASE : List[Any] = vocab_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect.""" """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,""" f"""but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride)""" f"""= {len(self.conv_stride)}`, `len(config.conv_kernel) = {len(self.conv_kernel)}`.""") # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _SCREAMING_SNAKE_CASE : List[Any] = apply_spec_augment _SCREAMING_SNAKE_CASE : List[Any] = mask_time_prob _SCREAMING_SNAKE_CASE : List[str] = mask_time_length _SCREAMING_SNAKE_CASE : List[Any] = mask_time_min_masks _SCREAMING_SNAKE_CASE : List[Any] = mask_feature_prob _SCREAMING_SNAKE_CASE : int = mask_feature_length _SCREAMING_SNAKE_CASE : List[Any] = mask_feature_min_masks # ctc loss _SCREAMING_SNAKE_CASE : int = ctc_loss_reduction _SCREAMING_SNAKE_CASE : Optional[int] = ctc_zero_infinity # sequence classification _SCREAMING_SNAKE_CASE : Dict = use_weighted_layer_sum _SCREAMING_SNAKE_CASE : List[str] = classifier_proj_size @property def _lowerCAmelCase ( self : Any): """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1)
635
1
"""simple docstring""" def lowerCamelCase_(__SCREAMING_SNAKE_CASE = 1_000 )-> int: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = 1, 1 _SCREAMING_SNAKE_CASE : Union[str, Any] = [] for i in range(1 , n + 1 ): _SCREAMING_SNAKE_CASE : int = prev_numerator + 2 * prev_denominator _SCREAMING_SNAKE_CASE : Optional[int] = prev_numerator + prev_denominator if len(str(__SCREAMING_SNAKE_CASE ) ) > len(str(__SCREAMING_SNAKE_CASE ) ): result.append(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = numerator _SCREAMING_SNAKE_CASE : Union[str, Any] = denominator return len(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(F"{solution() = }")
635
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCAmelCase_ = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
1
"""simple docstring""" import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class _snake_case ( __snake_case ): """simple docstring""" a = "" a = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) a = None # compression type in fsspec. ex: "gzip" a = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self : List[str] , _A : str = "" , _A : Optional[str] = None , _A : Optional[dict] = None , **_A : Any): """simple docstring""" super().__init__(self , **_A) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode _SCREAMING_SNAKE_CASE : List[Any] = fsspec.open( _A , mode="""rb""" , protocol=_A , compression=self.compression , client_kwargs={ """requote_redirect_url""": False, # see https://github.com/huggingface/datasets/pull/5459 """trust_env""": True, # Enable reading proxy env variables. **(target_options or {}).pop("""client_kwargs""" , {}), # To avoid issues if it was already passed. } , **(target_options or {}) , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.basename(self.file.path.split("""::""")[0]) _SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.compressed_name[: self.compressed_name.rindex(""".""")] if """.""" in self.compressed_name else self.compressed_name ) _SCREAMING_SNAKE_CASE : Optional[int] = None @classmethod def _lowerCAmelCase ( cls : Any , _A : Tuple): """simple docstring""" return super()._strip_protocol(_A).lstrip("""/""") def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" if self.dir_cache is None: _SCREAMING_SNAKE_CASE : Union[str, Any] = {**self.file.fs.info(self.file.path), """name""": self.uncompressed_name} _SCREAMING_SNAKE_CASE : List[str] = {f["""name"""]: f} def _lowerCAmelCase ( self : Optional[int] , _A : str): """simple docstring""" return self.file.open().read() def _lowerCAmelCase ( self : str , _A : str , _A : str = "rb" , _A : Dict=None , _A : Tuple=True , _A : List[str]=None , **_A : Tuple , ): """simple docstring""" _SCREAMING_SNAKE_CASE : int = self._strip_protocol(_A) if mode != "rb": raise ValueError(f"""Tried to read with mode {mode} on file {self.file.path} opened with mode 'rb'""") return self.file.open() class _snake_case ( __snake_case ): """simple docstring""" a = "bz2" a = "bz2" a = ".bz2" class _snake_case ( __snake_case ): """simple docstring""" a = "gzip" a = "gzip" a = ".gz" class _snake_case ( __snake_case ): """simple docstring""" a = "lz4" a = "lz4" a = ".lz4" class _snake_case ( __snake_case ): """simple docstring""" a = "xz" a = "xz" a = ".xz" class _snake_case ( __snake_case ): """simple docstring""" a = "zstd" a = "zstd" a = ".zst" def __init__( self : int , _A : str , _A : str = "rb" , _A : Optional[str] = None , _A : Optional[dict] = None , _A : int = DEFAULT_BLOCK_SIZE , **_A : Dict , ): """simple docstring""" super().__init__( fo=_A , mode=_A , target_protocol=_A , target_options=_A , block_size=_A , **_A , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 _SCREAMING_SNAKE_CASE : Optional[int] = self.file.__enter__ class _snake_case : """simple docstring""" def __init__( self : Tuple , _A : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = file_ def __enter__( self : Optional[Any]): """simple docstring""" self._file.__enter__() return self def __exit__( self : Any , *_A : Tuple , **_A : Optional[int]): """simple docstring""" self._file.__exit__(*_A , **_A) def __iter__( self : int): """simple docstring""" return iter(self._file) def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" return next(self._file) def __getattr__( self : Dict , _A : str): """simple docstring""" return getattr(self._file , _A) def fixed_enter(*_A : Tuple , **_A : Any): return WrappedFile(_enter(*_A , **_A)) _SCREAMING_SNAKE_CASE : Optional[Any] = fixed_enter
635
"""simple docstring""" import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: _SCREAMING_SNAKE_CASE : List[str] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Union[str, Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _SCREAMING_SNAKE_CASE : List[Any] = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: _SCREAMING_SNAKE_CASE : int = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : str = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : List[Any] = features.copy() if features else default_expected_features _SCREAMING_SNAKE_CASE : List[Any] = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) _SCREAMING_SNAKE_CASE : Optional[Any] = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: _SCREAMING_SNAKE_CASE : Tuple = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : int = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : Dict = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , split=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""" , [str, list] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> str: if issubclass(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = parquet_path elif issubclass(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = [parquet_path] _SCREAMING_SNAKE_CASE : Optional[Any] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Union[str, Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : str = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=("train",) )-> Union[str, Any]: assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for split in splits: _SCREAMING_SNAKE_CASE : int = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Optional[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _SCREAMING_SNAKE_CASE : Tuple = ParquetDatasetReader( {"""train""": parquet_path} , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: _SCREAMING_SNAKE_CASE : Optional[int] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Optional[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : List[str] = features.copy() if features else default_expected_features _SCREAMING_SNAKE_CASE : str = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) _SCREAMING_SNAKE_CASE : int = ParquetDatasetReader({"""train""": parquet_path} , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: if split: _SCREAMING_SNAKE_CASE : Union[str, Any] = {split: parquet_path} else: _SCREAMING_SNAKE_CASE : Optional[int] = """train""" _SCREAMING_SNAKE_CASE : Any = {"""train""": parquet_path, """test""": parquet_path} _SCREAMING_SNAKE_CASE : List[str] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : List[str] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : Union[str, Any] = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[Any]: _SCREAMING_SNAKE_CASE : List[str] = ParquetDatasetWriter(__SCREAMING_SNAKE_CASE , tmp_path / """foo.parquet""" ) assert writer.write() > 0 _SCREAMING_SNAKE_CASE : Tuple = pq.ParquetFile(tmp_path / """foo.parquet""" ) _SCREAMING_SNAKE_CASE : str = pf.read() assert dataset.data.table == output_table def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Dict = str(shared_datadir / """test_image_rgb.jpg""" ) _SCREAMING_SNAKE_CASE : Optional[Any] = {"""image""": [image_path]} _SCREAMING_SNAKE_CASE : Optional[Any] = Features({"""image""": Image()} ) _SCREAMING_SNAKE_CASE : Optional[int] = Dataset.from_dict(__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = ParquetDatasetWriter(__SCREAMING_SNAKE_CASE , tmp_path / """foo.parquet""" ) assert writer.write() > 0 _SCREAMING_SNAKE_CASE : List[str] = Dataset.from_parquet(str(tmp_path / """foo.parquet""" ) ) assert dataset.features == reloaded_dataset.features _SCREAMING_SNAKE_CASE : List[Any] = ParquetDatasetReader(str(tmp_path / """foo.parquet""" ) , streaming=__SCREAMING_SNAKE_CASE ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( """feature, expected""" , [ (Features({"""foo""": Value("""int32""" )} ), None), (Features({"""image""": Image(), """foo""": Value("""int32""" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"""nested""": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> int: assert get_writer_batch_size(__SCREAMING_SNAKE_CASE ) == expected
635
1
"""simple docstring""" from collections import namedtuple lowerCAmelCase_ = namedtuple('''from_to''', '''from_ to''') lowerCAmelCase_ = { '''cubicmeter''': from_to(1, 1), '''litre''': from_to(0.0_01, 1000), '''kilolitre''': from_to(1, 1), '''gallon''': from_to(0.0_04_54, 2_64.1_72), '''cubicyard''': from_to(0.7_64_55, 1.3_07_95), '''cubicfoot''': from_to(0.0_28, 35.31_47), '''cup''': from_to(0.0_00_23_65_88, 42_26.75), } def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> float: if from_type not in METRIC_CONVERSION: raise ValueError( F"""Invalid 'from_type' value: {from_type!r} Supported values are:\n""" + """, """.join(__SCREAMING_SNAKE_CASE ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F"""Invalid 'to_type' value: {to_type!r}. Supported values are:\n""" + """, """.join(__SCREAMING_SNAKE_CASE ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
635
"""simple docstring""" def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise TypeError("""only integers accepted as input""" ) else: _SCREAMING_SNAKE_CASE : List[Any] = str(abs(__SCREAMING_SNAKE_CASE ) ) _SCREAMING_SNAKE_CASE : List[str] = [list(__SCREAMING_SNAKE_CASE ) for char in range(len(__SCREAMING_SNAKE_CASE ) )] for index in range(len(__SCREAMING_SNAKE_CASE ) ): num_transpositions[index].pop(__SCREAMING_SNAKE_CASE ) return max( int("""""".join(list(__SCREAMING_SNAKE_CASE ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('''doctest''').testmod()
635
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase_ = { '''configuration_canine''': ['''CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CanineConfig'''], '''tokenization_canine''': ['''CanineTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''CANINE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CanineForMultipleChoice''', '''CanineForQuestionAnswering''', '''CanineForSequenceClassification''', '''CanineForTokenClassification''', '''CanineLayer''', '''CanineModel''', '''CaninePreTrainedModel''', '''load_tf_weights_in_canine''', ] if TYPE_CHECKING: from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig from .tokenization_canine import CanineTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_canine import ( CANINE_PRETRAINED_MODEL_ARCHIVE_LIST, CanineForMultipleChoice, CanineForQuestionAnswering, CanineForSequenceClassification, CanineForTokenClassification, CanineLayer, CanineModel, CaninePreTrainedModel, load_tf_weights_in_canine, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
"""simple docstring""" import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers import AutoModelForCausalLM @require_torch class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : Any = -1 _SCREAMING_SNAKE_CASE : List[str] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : Dict = model.generate(_A , max_new_tokens=1_0 , do_sample=_A) _SCREAMING_SNAKE_CASE : Dict = tokenizer.decode(greedy_ids[0]) with CaptureStdout() as cs: _SCREAMING_SNAKE_CASE : Any = TextStreamer(_A) model.generate(_A , max_new_tokens=1_0 , do_sample=_A , streamer=_A) # The greedy text should be printed to stdout, except for the final "\n" in the streamer _SCREAMING_SNAKE_CASE : str = cs.out[:-1] self.assertEqual(_A , _A) def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : Any = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : List[Any] = -1 _SCREAMING_SNAKE_CASE : str = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = model.generate(_A , max_new_tokens=1_0 , do_sample=_A) _SCREAMING_SNAKE_CASE : Any = tokenizer.decode(greedy_ids[0]) _SCREAMING_SNAKE_CASE : List[Any] = TextIteratorStreamer(_A) _SCREAMING_SNAKE_CASE : Any = {"""input_ids""": input_ids, """max_new_tokens""": 1_0, """do_sample""": False, """streamer""": streamer} _SCREAMING_SNAKE_CASE : List[Any] = Thread(target=model.generate , kwargs=_A) thread.start() _SCREAMING_SNAKE_CASE : Any = """""" for new_text in streamer: streamer_text += new_text self.assertEqual(_A , _A) def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : Any = -1 _SCREAMING_SNAKE_CASE : Any = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = model.generate(_A , max_new_tokens=1_0 , do_sample=_A) _SCREAMING_SNAKE_CASE : str = greedy_ids[:, input_ids.shape[1] :] _SCREAMING_SNAKE_CASE : Dict = tokenizer.decode(new_greedy_ids[0]) with CaptureStdout() as cs: _SCREAMING_SNAKE_CASE : Any = TextStreamer(_A , skip_prompt=_A) model.generate(_A , max_new_tokens=1_0 , do_sample=_A , streamer=_A) # The greedy text should be printed to stdout, except for the final "\n" in the streamer _SCREAMING_SNAKE_CASE : Optional[int] = cs.out[:-1] self.assertEqual(_A , _A) def _lowerCAmelCase ( self : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained("""distilgpt2""") _SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForCausalLM.from_pretrained("""distilgpt2""").to(_A) _SCREAMING_SNAKE_CASE : int = -1 _SCREAMING_SNAKE_CASE : List[str] = torch.ones((1, 5) , device=_A).long() * model.config.bos_token_id with CaptureStdout() as cs: _SCREAMING_SNAKE_CASE : Optional[int] = TextStreamer(_A , skip_special_tokens=_A) model.generate(_A , max_new_tokens=1 , do_sample=_A , streamer=_A) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token _SCREAMING_SNAKE_CASE : Optional[Any] = cs.out[:-1] # Remove the final "\n" _SCREAMING_SNAKE_CASE : Tuple = tokenizer(_A , return_tensors="""pt""") self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1)) def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : List[Any] = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : Tuple = -1 _SCREAMING_SNAKE_CASE : Dict = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : int = TextIteratorStreamer(_A , timeout=0.001) _SCREAMING_SNAKE_CASE : List[Any] = {"""input_ids""": input_ids, """max_new_tokens""": 1_0, """do_sample""": False, """streamer""": streamer} _SCREAMING_SNAKE_CASE : List[str] = Thread(target=model.generate , kwargs=_A) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(_A): _SCREAMING_SNAKE_CASE : str = """""" for new_text in streamer: streamer_text += new_text
635
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor lowerCAmelCase_ = logging.get_logger(__name__) class _snake_case ( __snake_case ): """simple docstring""" def __init__( self : Tuple , *_A : Tuple , **_A : Union[str, Any]): """simple docstring""" warnings.warn( """The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use FlavaImageProcessor instead.""" , _A , ) super().__init__(*_A , **_A)
635
"""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 torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _snake_case ( __snake_case ): """simple docstring""" a = "facebook/bart-large-mnli" a = ( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) a = "text_classifier" a = AutoTokenizer a = AutoModelForSequenceClassification a = ["text", ["text"]] a = ["text"] def _lowerCAmelCase ( self : int): """simple docstring""" super().setup() _SCREAMING_SNAKE_CASE : Any = self.model.config _SCREAMING_SNAKE_CASE : Any = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail"""): _SCREAMING_SNAKE_CASE : List[Any] = int(_A) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""") def _lowerCAmelCase ( self : Optional[Any] , _A : Tuple , _A : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = labels return self.pre_processor( [text] * len(_A) , [f"""This example is {label}""" for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def _lowerCAmelCase ( self : Tuple , _A : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : str = outputs.logits _SCREAMING_SNAKE_CASE : List[Any] = torch.argmax(logits[:, 2]).item() return self._labels[label_id]
635
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''facebook/vit-mae-base''': '''https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json''', # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class _snake_case ( __snake_case ): """simple docstring""" a = "vit_mae" def __init__( self : Union[str, Any] , _A : List[Any]=7_6_8 , _A : Union[str, Any]=1_2 , _A : str=1_2 , _A : int=3_0_7_2 , _A : List[Any]="gelu" , _A : Dict=0.0 , _A : int=0.0 , _A : Optional[int]=0.02 , _A : Union[str, Any]=1e-12 , _A : List[str]=2_2_4 , _A : Dict=1_6 , _A : Any=3 , _A : Optional[int]=True , _A : List[Any]=1_6 , _A : Any=5_1_2 , _A : Any=8 , _A : int=2_0_4_8 , _A : Any=0.75 , _A : Tuple=False , **_A : List[str] , ): """simple docstring""" super().__init__(**_A) _SCREAMING_SNAKE_CASE : int = hidden_size _SCREAMING_SNAKE_CASE : str = num_hidden_layers _SCREAMING_SNAKE_CASE : Union[str, Any] = num_attention_heads _SCREAMING_SNAKE_CASE : Optional[int] = intermediate_size _SCREAMING_SNAKE_CASE : List[str] = hidden_act _SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob _SCREAMING_SNAKE_CASE : Tuple = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : List[Any] = initializer_range _SCREAMING_SNAKE_CASE : Optional[Any] = layer_norm_eps _SCREAMING_SNAKE_CASE : Optional[Any] = image_size _SCREAMING_SNAKE_CASE : Optional[Any] = patch_size _SCREAMING_SNAKE_CASE : Any = num_channels _SCREAMING_SNAKE_CASE : Optional[Any] = qkv_bias _SCREAMING_SNAKE_CASE : Optional[int] = decoder_num_attention_heads _SCREAMING_SNAKE_CASE : List[str] = decoder_hidden_size _SCREAMING_SNAKE_CASE : List[str] = decoder_num_hidden_layers _SCREAMING_SNAKE_CASE : Any = decoder_intermediate_size _SCREAMING_SNAKE_CASE : int = mask_ratio _SCREAMING_SNAKE_CASE : List[Any] = norm_pix_loss
635
"""simple docstring""" import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class _snake_case ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = AutoImageProcessor.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""") _SCREAMING_SNAKE_CASE : str = AutoModelForImageClassification.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""") model.to(_A) from datasets import load_dataset _SCREAMING_SNAKE_CASE : Any = load_dataset("""nielsr/rvlcdip-demo""") _SCREAMING_SNAKE_CASE : Any = dataset["""train"""][0]["""image"""].convert("""RGB""") _SCREAMING_SNAKE_CASE : str = image_processor(_A , return_tensors="""pt""").to(_A) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE : Any = model(**_A) _SCREAMING_SNAKE_CASE : List[Any] = outputs.logits _SCREAMING_SNAKE_CASE : List[str] = torch.Size((1, 1_6)) self.assertEqual(logits.shape , _A) _SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [-0.4_158, -0.4_092, -0.4_347] , device=_A , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , _A , atol=1e-4))
635
1
"""simple docstring""" import inspect import unittest from transformers import YolosConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import YolosForObjectDetection, YolosModel from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _snake_case : """simple docstring""" def __init__( self : str , _A : Tuple , _A : Optional[int]=1_3 , _A : List[Any]=[3_0, 3_0] , _A : List[str]=2 , _A : Dict=3 , _A : List[str]=True , _A : Optional[Any]=True , _A : Optional[int]=3_2 , _A : Tuple=5 , _A : Union[str, Any]=4 , _A : Union[str, Any]=3_7 , _A : Optional[Any]="gelu" , _A : Tuple=0.1 , _A : int=0.1 , _A : List[str]=1_0 , _A : Dict=0.02 , _A : List[Any]=3 , _A : List[Any]=None , _A : Dict=8 , _A : Optional[Any]=1_0 , ): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = parent _SCREAMING_SNAKE_CASE : int = batch_size _SCREAMING_SNAKE_CASE : Optional[int] = image_size _SCREAMING_SNAKE_CASE : Optional[int] = patch_size _SCREAMING_SNAKE_CASE : str = num_channels _SCREAMING_SNAKE_CASE : Optional[Any] = is_training _SCREAMING_SNAKE_CASE : List[Any] = use_labels _SCREAMING_SNAKE_CASE : Tuple = hidden_size _SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers _SCREAMING_SNAKE_CASE : Optional[int] = num_attention_heads _SCREAMING_SNAKE_CASE : List[Any] = intermediate_size _SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act _SCREAMING_SNAKE_CASE : int = hidden_dropout_prob _SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : Optional[Any] = type_sequence_label_size _SCREAMING_SNAKE_CASE : Any = initializer_range _SCREAMING_SNAKE_CASE : Optional[int] = num_labels _SCREAMING_SNAKE_CASE : Dict = scope _SCREAMING_SNAKE_CASE : Tuple = n_targets _SCREAMING_SNAKE_CASE : List[str] = num_detection_tokens # we set the expected sequence length (which is used in several tests) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens _SCREAMING_SNAKE_CASE : Union[str, Any] = (image_size[1] // patch_size) * (image_size[0] // patch_size) _SCREAMING_SNAKE_CASE : Union[str, Any] = num_patches + 1 + self.num_detection_tokens def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]) _SCREAMING_SNAKE_CASE : Union[str, Any] = None if self.use_labels: # labels is a list of Dict (each Dict being the labels for a given example in the batch) _SCREAMING_SNAKE_CASE : Optional[Any] = [] for i in range(self.batch_size): _SCREAMING_SNAKE_CASE : Union[str, Any] = {} _SCREAMING_SNAKE_CASE : List[Any] = torch.randint( high=self.num_labels , size=(self.n_targets,) , device=_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.rand(self.n_targets , 4 , device=_A) labels.append(_A) _SCREAMING_SNAKE_CASE : Tuple = self.get_config() return config, pixel_values, labels def _lowerCAmelCase ( self : List[str]): """simple docstring""" return YolosConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_A , initializer_range=self.initializer_range , num_detection_tokens=self.num_detection_tokens , num_labels=self.num_labels , ) def _lowerCAmelCase ( self : Tuple , _A : Tuple , _A : Union[str, Any] , _A : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = YolosModel(config=_A) model.to(_A) model.eval() _SCREAMING_SNAKE_CASE : List[str] = model(_A) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.expected_seq_len, self.hidden_size)) def _lowerCAmelCase ( self : List[Any] , _A : int , _A : Any , _A : str): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = YolosForObjectDetection(_A) model.to(_A) model.eval() _SCREAMING_SNAKE_CASE : int = model(pixel_values=_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = model(_A) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1)) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4)) _SCREAMING_SNAKE_CASE : str = model(pixel_values=_A , labels=_A) self.parent.assertEqual(result.loss.shape , ()) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1)) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4)) def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = self.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = config_and_inputs _SCREAMING_SNAKE_CASE : Optional[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _snake_case ( __snake_case , __snake_case , unittest.TestCase ): """simple docstring""" a = (YolosModel, YolosForObjectDetection) if is_torch_available() else () a = ( {"feature-extraction": YolosModel, "object-detection": YolosForObjectDetection} if is_torch_available() else {} ) a = False a = False a = False a = False def _lowerCAmelCase ( self : Union[str, Any] , _A : Tuple , _A : List[Any] , _A : Dict=False): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = super()._prepare_for_class(_A , _A , return_labels=_A) if return_labels: if model_class.__name__ == "YolosForObjectDetection": _SCREAMING_SNAKE_CASE : str = [] for i in range(self.model_tester.batch_size): _SCREAMING_SNAKE_CASE : Optional[int] = {} _SCREAMING_SNAKE_CASE : Optional[Any] = torch.ones( size=(self.model_tester.n_targets,) , device=_A , dtype=torch.long) _SCREAMING_SNAKE_CASE : Tuple = torch.ones( self.model_tester.n_targets , 4 , device=_A , dtype=torch.float) labels.append(_A) _SCREAMING_SNAKE_CASE : int = labels return inputs_dict def _lowerCAmelCase ( self : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : str = YolosModelTester(self) _SCREAMING_SNAKE_CASE : Optional[Any] = ConfigTester(self , config_class=_A , has_text_modality=_A , hidden_size=3_7) def _lowerCAmelCase ( self : Tuple): """simple docstring""" self.config_tester.run_common_tests() def _lowerCAmelCase ( self : Union[str, Any]): """simple docstring""" pass def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Optional[int] = model_class(_A) self.assertIsInstance(model.get_input_embeddings() , (nn.Module)) _SCREAMING_SNAKE_CASE : Dict = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_A , nn.Linear)) def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : List[str] = model_class(_A) _SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _SCREAMING_SNAKE_CASE : Dict = [*signature.parameters.keys()] _SCREAMING_SNAKE_CASE : Any = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _A) def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A) def _lowerCAmelCase ( self : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE : str = True # in YOLOS, the seq_len is different _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.expected_seq_len for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Optional[int] = True _SCREAMING_SNAKE_CASE : Dict = False _SCREAMING_SNAKE_CASE : Tuple = True _SCREAMING_SNAKE_CASE : int = model_class(_A) model.to(_A) model.eval() with torch.no_grad(): _SCREAMING_SNAKE_CASE : Tuple = model(**self._prepare_for_class(_A , _A)) _SCREAMING_SNAKE_CASE : int = outputs.attentions self.assertEqual(len(_A) , self.model_tester.num_hidden_layers) # check that output_attentions also work using config del inputs_dict["output_attentions"] _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : List[Any] = model_class(_A) model.to(_A) model.eval() with torch.no_grad(): _SCREAMING_SNAKE_CASE : Dict = model(**self._prepare_for_class(_A , _A)) _SCREAMING_SNAKE_CASE : Tuple = outputs.attentions self.assertEqual(len(_A) , self.model_tester.num_hidden_layers) self.assertListEqual( list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) _SCREAMING_SNAKE_CASE : Tuple = len(_A) # Check attention is always last and order is fine _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : List[Any] = True _SCREAMING_SNAKE_CASE : int = model_class(_A) model.to(_A) model.eval() with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[int] = model(**self._prepare_for_class(_A , _A)) _SCREAMING_SNAKE_CASE : Union[str, Any] = 1 self.assertEqual(out_len + added_hidden_states , len(_A)) _SCREAMING_SNAKE_CASE : int = outputs.attentions self.assertEqual(len(_A) , self.model_tester.num_hidden_layers) self.assertListEqual( list(self_attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def _lowerCAmelCase ( self : Tuple): """simple docstring""" def check_hidden_states_output(_A : Optional[Any] , _A : Optional[int] , _A : str): _SCREAMING_SNAKE_CASE : Optional[Any] = model_class(_A) model.to(_A) model.eval() with torch.no_grad(): _SCREAMING_SNAKE_CASE : Tuple = model(**self._prepare_for_class(_A , _A)) _SCREAMING_SNAKE_CASE : List[str] = outputs.hidden_states _SCREAMING_SNAKE_CASE : int = getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1) self.assertEqual(len(_A) , _A) # YOLOS has a different seq_length _SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.expected_seq_len self.assertListEqual( list(hidden_states[0].shape[-2:]) , [seq_length, self.model_tester.hidden_size] , ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : List[Any] = True check_hidden_states_output(_A , _A , _A) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _SCREAMING_SNAKE_CASE : Tuple = True check_hidden_states_output(_A , _A , _A) def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_object_detection(*_A) @slow def _lowerCAmelCase ( self : Union[str, Any]): """simple docstring""" for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE : List[str] = YolosModel.from_pretrained(_A) self.assertIsNotNone(_A) def lowerCamelCase_()-> List[str]: _SCREAMING_SNAKE_CASE : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _snake_case ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" return AutoImageProcessor.from_pretrained("""hustvl/yolos-small""") if is_vision_available() else None @slow def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" _SCREAMING_SNAKE_CASE : int = YolosForObjectDetection.from_pretrained("""hustvl/yolos-small""").to(_A) _SCREAMING_SNAKE_CASE : List[Any] = self.default_image_processor _SCREAMING_SNAKE_CASE : Any = prepare_img() _SCREAMING_SNAKE_CASE : Any = image_processor(images=_A , return_tensors="""pt""").to(_A) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE : Union[str, Any] = model(inputs.pixel_values) # verify outputs _SCREAMING_SNAKE_CASE : str = torch.Size((1, 1_0_0, 9_2)) self.assertEqual(outputs.logits.shape , _A) _SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[-24.0_248, -10.3_024, -14.8_290], [-42.0_392, -16.8_200, -27.4_334], [-27.2_743, -11.8_154, -18.7_148]] , device=_A , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[0.2_559, 0.5_455, 0.4_706], [0.2_989, 0.7_279, 0.1_875], [0.7_732, 0.4_017, 0.4_462]] , device=_A) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , _A , atol=1e-4)) self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3] , _A , atol=1e-4)) # verify postprocessing _SCREAMING_SNAKE_CASE : Optional[int] = image_processor.post_process_object_detection( _A , threshold=0.3 , target_sizes=[image.size[::-1]])[0] _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([0.9_994, 0.9_790, 0.9_964, 0.9_972, 0.9_861]).to(_A) _SCREAMING_SNAKE_CASE : Optional[int] = [7_5, 7_5, 1_7, 6_3, 1_7] _SCREAMING_SNAKE_CASE : str = torch.tensor([335.0_609, 79.3_848, 375.4_216, 187.2_495]).to(_A) self.assertEqual(len(results["""scores"""]) , 5) self.assertTrue(torch.allclose(results["""scores"""] , _A , atol=1e-4)) self.assertSequenceEqual(results["""labels"""].tolist() , _A) self.assertTrue(torch.allclose(results["""boxes"""][0, :] , _A))
635
"""simple docstring""" import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class _snake_case ( __snake_case ): """simple docstring""" a = "M-CLIP" def __init__( self : Optional[Any] , _A : List[str]=1_0_2_4 , _A : Union[str, Any]=7_6_8 , **_A : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = transformerDimSize _SCREAMING_SNAKE_CASE : List[str] = imageDimSize super().__init__(**_A) class _snake_case ( __snake_case ): """simple docstring""" a = MCLIPConfig def __init__( self : Dict , _A : Optional[Any] , *_A : Any , **_A : Dict): """simple docstring""" super().__init__(_A , *_A , **_A) _SCREAMING_SNAKE_CASE : Tuple = XLMRobertaModel(_A) _SCREAMING_SNAKE_CASE : List[Any] = torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims) def _lowerCAmelCase ( self : Union[str, Any] , _A : str , _A : int): """simple docstring""" _SCREAMING_SNAKE_CASE : str = self.transformer(input_ids=_A , attention_mask=_A)[0] _SCREAMING_SNAKE_CASE : Optional[Any] = (embs * attention_mask.unsqueeze(2)).sum(dim=1) / attention_mask.sum(dim=1)[:, None] return self.LinearTransformation(_A), embs
635
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowerCAmelCase_ = { '''configuration_convnext''': ['''CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ConvNextConfig''', '''ConvNextOnnxConfig'''] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''ConvNextFeatureExtractor'''] lowerCAmelCase_ = ['''ConvNextImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ConvNextForImageClassification''', '''ConvNextModel''', '''ConvNextPreTrainedModel''', '''ConvNextBackbone''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''TFConvNextForImageClassification''', '''TFConvNextModel''', '''TFConvNextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig, ConvNextOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_convnext import ConvNextFeatureExtractor from .image_processing_convnext import ConvNextImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convnext import ( CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvNextBackbone, ConvNextForImageClassification, ConvNextModel, ConvNextPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
635
"""simple docstring""" from decimal import Decimal, getcontext from math import ceil, factorial def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> str: if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise TypeError("""Undefined for non-integers""" ) elif precision < 1: raise ValueError("""Undefined for non-natural numbers""" ) _SCREAMING_SNAKE_CASE : int = precision _SCREAMING_SNAKE_CASE : Dict = ceil(precision / 14 ) _SCREAMING_SNAKE_CASE : int = 426_880 * Decimal(10_005 ).sqrt() _SCREAMING_SNAKE_CASE : Union[str, Any] = 1 _SCREAMING_SNAKE_CASE : str = 13_591_409 _SCREAMING_SNAKE_CASE : Tuple = Decimal(__SCREAMING_SNAKE_CASE ) for k in range(1 , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = factorial(6 * k ) // (factorial(3 * k ) * factorial(__SCREAMING_SNAKE_CASE ) ** 3) linear_term += 545_140_134 exponential_term *= -262_537_412_640_768_000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": lowerCAmelCase_ = 50 print(F"The first {n} digits of pi is: {pi(n)}")
635
1
"""simple docstring""" def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> list[list]: _SCREAMING_SNAKE_CASE : Any = current_set.copy() for row_index, row in enumerate(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = row[0] for column_index, column in enumerate(__SCREAMING_SNAKE_CASE ): if magnitude == 0: _SCREAMING_SNAKE_CASE : List[Any] = column continue _SCREAMING_SNAKE_CASE : List[str] = column / magnitude # Subtract to cancel term _SCREAMING_SNAKE_CASE : int = current_set[0] _SCREAMING_SNAKE_CASE : List[str] = [first_row] _SCREAMING_SNAKE_CASE : List[str] = current_set[1::] for row in current_set: _SCREAMING_SNAKE_CASE : Tuple = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(__SCREAMING_SNAKE_CASE ) continue for column_index in range(len(__SCREAMING_SNAKE_CASE ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(__SCREAMING_SNAKE_CASE ) # Create next recursion iteration set if len(final_set[0] ) != 3: _SCREAMING_SNAKE_CASE : List[Any] = final_set[0] _SCREAMING_SNAKE_CASE : Union[str, Any] = [] _SCREAMING_SNAKE_CASE : int = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) _SCREAMING_SNAKE_CASE : Optional[Any] = simplify(__SCREAMING_SNAKE_CASE ) for i in range(len(__SCREAMING_SNAKE_CASE ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[str] = resultant return final_set def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> list: if len(__SCREAMING_SNAKE_CASE ) == 0: raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = len(__SCREAMING_SNAKE_CASE ) + 1 if any(len(__SCREAMING_SNAKE_CASE ) != _length for item in equations ): raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) for row in equations: if any(not isinstance(__SCREAMING_SNAKE_CASE , (int, float) ) for column in row ): raise ValueError("""solve_simultaneous() requires lists of integers""" ) if len(__SCREAMING_SNAKE_CASE ) == 1: return [equations[0][-1] / equations[0][0]] _SCREAMING_SNAKE_CASE : Optional[int] = equations.copy() if any(0 in row for row in data_set ): _SCREAMING_SNAKE_CASE : List[Any] = data_set.copy() _SCREAMING_SNAKE_CASE : Union[str, Any] = [] for row_index, row in enumerate(__SCREAMING_SNAKE_CASE ): if 0 not in row: _SCREAMING_SNAKE_CASE : Optional[Any] = data_set.pop(__SCREAMING_SNAKE_CASE ) break if not full_row: raise ValueError("""solve_simultaneous() requires at least 1 full equation""" ) data_set.insert(0 , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[Any] = data_set.copy() _SCREAMING_SNAKE_CASE : Dict = simplify(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[str] = simplified[::-1] _SCREAMING_SNAKE_CASE : list = [] for row in simplified: _SCREAMING_SNAKE_CASE : Optional[int] = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue _SCREAMING_SNAKE_CASE : List[str] = row.copy()[: len(__SCREAMING_SNAKE_CASE ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(__SCREAMING_SNAKE_CASE ) == 0: solutions.append(0 ) continue _SCREAMING_SNAKE_CASE : int = temp_row[1::] _SCREAMING_SNAKE_CASE : str = temp_row[::-1] for column_index, column in enumerate(__SCREAMING_SNAKE_CASE ): current_solution -= column * solutions[column_index] solutions.append(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[int] = [] for item in solutions: final.append(float(round(__SCREAMING_SNAKE_CASE , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase_ = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
635
"""simple docstring""" import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file _SCREAMING_SNAKE_CASE : Optional[int] = TapasConfig.from_json_file(__SCREAMING_SNAKE_CASE ) # set absolute/relative position embeddings parameter _SCREAMING_SNAKE_CASE : Dict = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": _SCREAMING_SNAKE_CASE : str = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "WTQ": # run_task_main.py hparams _SCREAMING_SNAKE_CASE : Optional[int] = 4 _SCREAMING_SNAKE_CASE : Any = True # hparam_utils.py hparams _SCREAMING_SNAKE_CASE : Any = 0.66_46_94 _SCREAMING_SNAKE_CASE : str = 0.20_79_51 _SCREAMING_SNAKE_CASE : str = 0.12_11_94 _SCREAMING_SNAKE_CASE : List[Any] = True _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = 0.0_35_25_13 _SCREAMING_SNAKE_CASE : Optional[Any] = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams _SCREAMING_SNAKE_CASE : int = 4 _SCREAMING_SNAKE_CASE : Tuple = False # hparam_utils.py hparams _SCREAMING_SNAKE_CASE : Any = 36.45_19 _SCREAMING_SNAKE_CASE : Union[str, Any] = 0.90_34_21 _SCREAMING_SNAKE_CASE : Optional[Any] = 2_22.0_88 _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Optional[int] = True _SCREAMING_SNAKE_CASE : Dict = 0.76_31_41 _SCREAMING_SNAKE_CASE : Union[str, Any] = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "TABFACT": _SCREAMING_SNAKE_CASE : int = TapasForSequenceClassification(config=__SCREAMING_SNAKE_CASE ) elif task == "MLM": _SCREAMING_SNAKE_CASE : int = TapasForMaskedLM(config=__SCREAMING_SNAKE_CASE ) elif task == "INTERMEDIATE_PRETRAINING": _SCREAMING_SNAKE_CASE : int = TapasModel(config=__SCREAMING_SNAKE_CASE ) else: raise ValueError(F"""Task {task} not supported.""" ) print(F"""Building PyTorch model from configuration: {config}""" ) # Load weights from tf checkpoint load_tf_weights_in_tapas(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Save pytorch-model (weights and configuration) print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) # Save tokenizer files print(F"""Save tokenizer files to {pytorch_dump_path}""" ) _SCREAMING_SNAKE_CASE : str = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + """vocab.txt""" , model_max_length=512 ) tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) print("""Used relative position embeddings:""" , model.config.reset_position_index_per_cell ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--task''', default='''SQA''', type=str, help='''Model task for which to convert a checkpoint. Defaults to SQA.''' ) parser.add_argument( '''--reset_position_index_per_cell''', default=False, action='''store_true''', help='''Whether to use relative position embeddings or not. Defaults to True.''', ) parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--tapas_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained TAPAS model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) lowerCAmelCase_ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
635
1
"""simple docstring""" from __future__ import annotations import unittest import numpy as np from transformers import LayoutLMConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.layoutlm.modeling_tf_layoutlm import ( TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMForMaskedLM, TFLayoutLMForQuestionAnswering, TFLayoutLMForSequenceClassification, TFLayoutLMForTokenClassification, TFLayoutLMModel, ) class _snake_case : """simple docstring""" def __init__( self : Union[str, Any] , _A : Optional[int] , _A : Tuple=1_3 , _A : Tuple=7 , _A : List[Any]=True , _A : Optional[Any]=True , _A : List[Any]=True , _A : int=True , _A : List[str]=9_9 , _A : List[str]=3_2 , _A : Optional[int]=2 , _A : Any=4 , _A : List[Any]=3_7 , _A : Any="gelu" , _A : Union[str, Any]=0.1 , _A : Any=0.1 , _A : List[str]=5_1_2 , _A : int=1_6 , _A : Optional[Any]=2 , _A : Dict=0.02 , _A : List[Any]=3 , _A : List[str]=4 , _A : Optional[Any]=None , _A : List[Any]=1_0_0_0 , ): """simple docstring""" _SCREAMING_SNAKE_CASE : str = parent _SCREAMING_SNAKE_CASE : Any = batch_size _SCREAMING_SNAKE_CASE : Tuple = seq_length _SCREAMING_SNAKE_CASE : Optional[Any] = is_training _SCREAMING_SNAKE_CASE : List[Any] = use_input_mask _SCREAMING_SNAKE_CASE : Dict = use_token_type_ids _SCREAMING_SNAKE_CASE : List[str] = use_labels _SCREAMING_SNAKE_CASE : List[Any] = vocab_size _SCREAMING_SNAKE_CASE : str = hidden_size _SCREAMING_SNAKE_CASE : Dict = num_hidden_layers _SCREAMING_SNAKE_CASE : int = num_attention_heads _SCREAMING_SNAKE_CASE : int = intermediate_size _SCREAMING_SNAKE_CASE : Optional[int] = hidden_act _SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob _SCREAMING_SNAKE_CASE : Any = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : Optional[Any] = max_position_embeddings _SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size _SCREAMING_SNAKE_CASE : Optional[Any] = type_sequence_label_size _SCREAMING_SNAKE_CASE : List[str] = initializer_range _SCREAMING_SNAKE_CASE : List[str] = num_labels _SCREAMING_SNAKE_CASE : Optional[int] = num_choices _SCREAMING_SNAKE_CASE : Union[str, Any] = scope _SCREAMING_SNAKE_CASE : Any = range_bbox def _lowerCAmelCase ( self : int): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) # convert bbox to numpy since TF does not support item assignment _SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox).numpy() # Ensure that bbox is legal for i in range(bbox.shape[0]): for j in range(bbox.shape[1]): if bbox[i, j, 3] < bbox[i, j, 1]: _SCREAMING_SNAKE_CASE : List[Any] = bbox[i, j, 3] _SCREAMING_SNAKE_CASE : Dict = bbox[i, j, 1] _SCREAMING_SNAKE_CASE : Any = t if bbox[i, j, 2] < bbox[i, j, 0]: _SCREAMING_SNAKE_CASE : Any = bbox[i, j, 2] _SCREAMING_SNAKE_CASE : List[str] = bbox[i, j, 0] _SCREAMING_SNAKE_CASE : Optional[Any] = t _SCREAMING_SNAKE_CASE : str = tf.convert_to_tensor(_A) _SCREAMING_SNAKE_CASE : str = None if self.use_input_mask: _SCREAMING_SNAKE_CASE : List[Any] = random_attention_mask([self.batch_size, self.seq_length]) _SCREAMING_SNAKE_CASE : List[str] = None if self.use_token_type_ids: _SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) _SCREAMING_SNAKE_CASE : Union[str, Any] = None _SCREAMING_SNAKE_CASE : List[Any] = None _SCREAMING_SNAKE_CASE : Optional[int] = None if self.use_labels: _SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size) _SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) _SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size] , self.num_choices) _SCREAMING_SNAKE_CASE : Optional[int] = LayoutLMConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowerCAmelCase ( self : Any , _A : Optional[int] , _A : List[str] , _A : Optional[int] , _A : str , _A : Optional[int] , _A : Dict , _A : int , _A : Union[str, Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = TFLayoutLMModel(config=_A) _SCREAMING_SNAKE_CASE : Optional[int] = model(_A , _A , attention_mask=_A , token_type_ids=_A) _SCREAMING_SNAKE_CASE : List[Any] = model(_A , _A , token_type_ids=_A) _SCREAMING_SNAKE_CASE : Dict = model(_A , _A) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size)) def _lowerCAmelCase ( self : Optional[int] , _A : Optional[int] , _A : str , _A : Tuple , _A : Optional[int] , _A : Dict , _A : List[Any] , _A : Tuple , _A : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = TFLayoutLMForMaskedLM(config=_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = model(_A , _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 _lowerCAmelCase ( self : Dict , _A : Dict , _A : Dict , _A : Dict , _A : Optional[Any] , _A : Tuple , _A : Optional[Any] , _A : Union[str, Any] , _A : Union[str, Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = self.num_labels _SCREAMING_SNAKE_CASE : Optional[Any] = TFLayoutLMForSequenceClassification(config=_A) _SCREAMING_SNAKE_CASE : List[str] = model(_A , _A , attention_mask=_A , token_type_ids=_A) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _lowerCAmelCase ( self : Dict , _A : List[str] , _A : Dict , _A : str , _A : str , _A : Optional[int] , _A : Dict , _A : Optional[Any] , _A : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : int = self.num_labels _SCREAMING_SNAKE_CASE : Dict = TFLayoutLMForTokenClassification(config=_A) _SCREAMING_SNAKE_CASE : List[str] = model(_A , _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 _lowerCAmelCase ( self : Optional[Any] , _A : List[str] , _A : Any , _A : List[Any] , _A : List[Any] , _A : Any , _A : Any , _A : Optional[int] , _A : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = TFLayoutLMForQuestionAnswering(config=_A) _SCREAMING_SNAKE_CASE : Tuple = model(_A , _A , attention_mask=_A , token_type_ids=_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 _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : str = self.prepare_config_and_inputs() ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) : List[str] = config_and_inputs _SCREAMING_SNAKE_CASE : List[Any] = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_tf class _snake_case ( __snake_case , __snake_case , unittest.TestCase ): """simple docstring""" a = ( ( TFLayoutLMModel, TFLayoutLMForMaskedLM, TFLayoutLMForTokenClassification, TFLayoutLMForSequenceClassification, TFLayoutLMForQuestionAnswering, ) if is_tf_available() else () ) a = ( { "feature-extraction": TFLayoutLMModel, "fill-mask": TFLayoutLMForMaskedLM, "text-classification": TFLayoutLMForSequenceClassification, "token-classification": TFLayoutLMForTokenClassification, "zero-shot": TFLayoutLMForSequenceClassification, } if is_tf_available() else {} ) a = False a = True a = 10 def _lowerCAmelCase ( self : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = TFLayoutLMModelTester(self) _SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_A , hidden_size=3_7) def _lowerCAmelCase ( self : List[Any]): """simple docstring""" self.config_tester.run_common_tests() def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A) def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_A) def _lowerCAmelCase ( self : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_A) def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_A) def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_A) @slow def _lowerCAmelCase ( self : Any): """simple docstring""" for model_name in TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE : Dict = TFLayoutLMModel.from_pretrained(_A) self.assertIsNotNone(_A) @unittest.skip("""Onnx compliancy broke with TF 2.10""") def _lowerCAmelCase ( self : Any): """simple docstring""" pass def lowerCamelCase_()-> Union[str, Any]: # Here we prepare a batch of 2 sequences to test a LayoutLM forward pass on: # fmt: off _SCREAMING_SNAKE_CASE : str = tf.convert_to_tensor([[101,1_019,1_014,1_016,1_037,12_849,4_747,1_004,14_246,2_278,5_439,4_524,5_002,2_930,2_193,2_930,4_341,3_208,1_005,1_055,2_171,2_848,11_300,3_531,102],[101,4_070,4_034,7_020,1_024,3_058,1_015,1_013,2_861,1_013,6_070,19_274,2_772,6_205,27_814,16_147,16_147,4_343,2_047,10_283,10_969,14_389,1_012,2_338,102]] ) # noqa: E231 _SCREAMING_SNAKE_CASE : Optional[int] = tf.convert_to_tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],] ) # noqa: E231 _SCREAMING_SNAKE_CASE : Tuple = tf.convert_to_tensor([[[0,0,0,0],[423,237,440,251],[427,272,441,287],[419,115,437,129],[961,885,992,912],[256,38,330,58],[256,38,330,58],[336,42,353,57],[360,39,401,56],[360,39,401,56],[411,39,471,59],[479,41,528,59],[533,39,630,60],[67,113,134,131],[141,115,209,132],[68,149,133,166],[141,149,187,164],[195,148,287,165],[195,148,287,165],[195,148,287,165],[295,148,349,165],[441,149,492,166],[497,149,546,164],[64,201,125,218],[1_000,1_000,1_000,1_000]],[[0,0,0,0],[662,150,754,166],[665,199,742,211],[519,213,554,228],[519,213,554,228],[134,433,187,454],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[314,469,376,482],[504,684,582,706],[941,825,973,900],[941,825,973,900],[941,825,973,900],[941,825,973,900],[610,749,652,765],[130,659,168,672],[176,657,237,672],[238,657,312,672],[443,653,628,672],[443,653,628,672],[716,301,825,317],[1_000,1_000,1_000,1_000]]] ) # noqa: E231 _SCREAMING_SNAKE_CASE : str = tf.convert_to_tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]] ) # noqa: E231 # these are sequence labels (i.e. at the token level) _SCREAMING_SNAKE_CASE : Optional[Any] = tf.convert_to_tensor([[-100,10,10,10,9,1,-100,7,7,-100,7,7,4,2,5,2,8,8,-100,-100,5,0,3,2,-100],[-100,12,12,12,-100,12,10,-100,-100,-100,-100,10,12,9,-100,-100,-100,10,10,10,9,12,-100,10,-100]] ) # noqa: E231 # fmt: on return input_ids, attention_mask, bbox, token_type_ids, labels @require_tf class _snake_case ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = TFLayoutLMModel.from_pretrained("""microsoft/layoutlm-base-uncased""") _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = prepare_layoutlm_batch_inputs() # forward pass _SCREAMING_SNAKE_CASE : Optional[Any] = model(input_ids=_A , bbox=_A , attention_mask=_A , token_type_ids=_A) # test the sequence output on [0, :3, :3] _SCREAMING_SNAKE_CASE : List[Any] = tf.convert_to_tensor( [[0.1_785, -0.1_947, -0.0_425], [-0.3_254, -0.2_807, 0.2_553], [-0.5_391, -0.3_322, 0.3_364]] , ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , _A , atol=1e-3)) # test the pooled output on [1, :3] _SCREAMING_SNAKE_CASE : Tuple = tf.convert_to_tensor([-0.6_580, -0.0_214, 0.8_552]) self.assertTrue(np.allclose(outputs.pooler_output[1, :3] , _A , atol=1e-3)) @slow def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = TFLayoutLMForSequenceClassification.from_pretrained("""microsoft/layoutlm-base-uncased""" , num_labels=2) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = prepare_layoutlm_batch_inputs() # forward pass _SCREAMING_SNAKE_CASE : List[str] = model( input_ids=_A , bbox=_A , attention_mask=_A , token_type_ids=_A , labels=tf.convert_to_tensor([1, 1]) , ) # test whether we get a loss as a scalar _SCREAMING_SNAKE_CASE : str = outputs.loss _SCREAMING_SNAKE_CASE : Dict = (2,) self.assertEqual(loss.shape , _A) # test the shape of the logits _SCREAMING_SNAKE_CASE : Any = outputs.logits _SCREAMING_SNAKE_CASE : List[str] = (2, 2) self.assertEqual(logits.shape , _A) @slow def _lowerCAmelCase ( self : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = TFLayoutLMForTokenClassification.from_pretrained("""microsoft/layoutlm-base-uncased""" , num_labels=1_3) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = prepare_layoutlm_batch_inputs() # forward pass _SCREAMING_SNAKE_CASE : int = model( input_ids=_A , bbox=_A , attention_mask=_A , token_type_ids=_A , labels=_A) # test the shape of the logits _SCREAMING_SNAKE_CASE : List[Any] = outputs.logits _SCREAMING_SNAKE_CASE : Optional[Any] = tf.convert_to_tensor((2, 2_5, 1_3)) self.assertEqual(logits.shape , _A) @slow def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = TFLayoutLMForQuestionAnswering.from_pretrained("""microsoft/layoutlm-base-uncased""") _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = prepare_layoutlm_batch_inputs() # forward pass _SCREAMING_SNAKE_CASE : List[str] = model(input_ids=_A , bbox=_A , attention_mask=_A , token_type_ids=_A) # test the shape of the logits _SCREAMING_SNAKE_CASE : Optional[int] = tf.convert_to_tensor((2, 2_5)) self.assertEqual(outputs.start_logits.shape , _A) self.assertEqual(outputs.end_logits.shape , _A)
635
"""simple docstring""" from typing import Any import numpy as np def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> bool: return np.array_equal(__SCREAMING_SNAKE_CASE , matrix.conjugate().T ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Any: _SCREAMING_SNAKE_CASE : Optional[int] = v.conjugate().T _SCREAMING_SNAKE_CASE : Optional[int] = v_star.dot(__SCREAMING_SNAKE_CASE ) assert isinstance(__SCREAMING_SNAKE_CASE , np.ndarray ) return (v_star_dot.dot(__SCREAMING_SNAKE_CASE )) / (v_star.dot(__SCREAMING_SNAKE_CASE )) def lowerCamelCase_()-> None: _SCREAMING_SNAKE_CASE : Optional[Any] = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) _SCREAMING_SNAKE_CASE : int = np.array([[1], [2], [3]] ) assert is_hermitian(__SCREAMING_SNAKE_CASE ), F"""{a} is not hermitian.""" print(rayleigh_quotient(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) _SCREAMING_SNAKE_CASE : int = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(__SCREAMING_SNAKE_CASE ), F"""{a} is not hermitian.""" assert rayleigh_quotient(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
635
1
"""simple docstring""" import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller lowerCAmelCase_ = 3 def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: print("""Generating primitive root of p""" ) while True: _SCREAMING_SNAKE_CASE : Any = random.randrange(3 , __SCREAMING_SNAKE_CASE ) if pow(__SCREAMING_SNAKE_CASE , 2 , __SCREAMING_SNAKE_CASE ) == 1: continue if pow(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) == 1: continue return g def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> tuple[tuple[int, int, int, int], tuple[int, int]]: print("""Generating prime p...""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = rabin_miller.generate_large_prime(__SCREAMING_SNAKE_CASE ) # select large prime number. _SCREAMING_SNAKE_CASE : int = primitive_root(__SCREAMING_SNAKE_CASE ) # one primitive root on modulo p. _SCREAMING_SNAKE_CASE : Any = random.randrange(3 , __SCREAMING_SNAKE_CASE ) # private_key -> have to be greater than 2 for safety. _SCREAMING_SNAKE_CASE : List[str] = cryptomath.find_mod_inverse(pow(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[int] = (key_size, e_a, e_a, p) _SCREAMING_SNAKE_CASE : Dict = (key_size, d) return public_key, private_key def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> None: if os.path.exists(F"""{name}_pubkey.txt""" ) or os.path.exists(F"""{name}_privkey.txt""" ): print("""\nWARNING:""" ) print( F"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n""" """Use a different name or delete these files and re-run this program.""" ) sys.exit() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = generate_key(__SCREAMING_SNAKE_CASE ) print(F"""\nWriting public key to file {name}_pubkey.txt...""" ) with open(F"""{name}_pubkey.txt""" , """w""" ) as fo: fo.write(F"""{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}""" ) print(F"""Writing private key to file {name}_privkey.txt...""" ) with open(F"""{name}_privkey.txt""" , """w""" ) as fo: fo.write(F"""{private_key[0]},{private_key[1]}""" ) def lowerCamelCase_()-> None: print("""Making key files...""" ) make_key_files("""elgamal""" , 2_048 ) print("""Key files generation successful""" ) if __name__ == "__main__": main()
635
"""simple docstring""" from __future__ import annotations def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , )-> tuple: if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError("""You cannot supply more or less than 2 values""" ) elif electron_conc < 0: raise ValueError("""Electron concentration cannot be negative in a semiconductor""" ) elif hole_conc < 0: raise ValueError("""Hole concentration cannot be negative in a semiconductor""" ) elif intrinsic_conc < 0: raise ValueError( """Intrinsic concentration cannot be negative in a semiconductor""" ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
635
1
"""simple docstring""" import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow lowerCAmelCase_ = False class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Dict , _A : int=3_2): """simple docstring""" set_seed(0) _SCREAMING_SNAKE_CASE : int = UNetaDModel(sample_size=_A , in_channels=3 , out_channels=3) _SCREAMING_SNAKE_CASE : Tuple = torch.optim.SGD(model.parameters() , lr=0.0_001) return model, optimizer @slow def _lowerCAmelCase ( self : Union[str, Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : int = """cpu""" # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable _SCREAMING_SNAKE_CASE : int = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=_A , ) _SCREAMING_SNAKE_CASE : Optional[Any] = DDIMScheduler( num_train_timesteps=1_0_0_0 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=_A , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0) _SCREAMING_SNAKE_CASE : List[str] = [torch.randn((4, 3, 3_2, 3_2)).clip(-1 , 1).to(_A) for _ in range(4)] _SCREAMING_SNAKE_CASE : Union[str, Any] = [torch.randn((4, 3, 3_2, 3_2)).to(_A) for _ in range(4)] _SCREAMING_SNAKE_CASE : str = [torch.randint(0 , 1_0_0_0 , (4,)).long().to(_A) for _ in range(4)] # train with a DDPM scheduler _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self.get_model_optimizer(resolution=3_2) model.train().to(_A) for i in range(4): optimizer.zero_grad() _SCREAMING_SNAKE_CASE : Optional[Any] = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i]) _SCREAMING_SNAKE_CASE : Optional[Any] = model(_A , timesteps[i]).sample _SCREAMING_SNAKE_CASE : List[Any] = torch.nn.functional.mse_loss(_A , noise[i]) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self.get_model_optimizer(resolution=3_2) model.train().to(_A) for i in range(4): optimizer.zero_grad() _SCREAMING_SNAKE_CASE : Tuple = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i]) _SCREAMING_SNAKE_CASE : List[str] = model(_A , timesteps[i]).sample _SCREAMING_SNAKE_CASE : str = torch.nn.functional.mse_loss(_A , noise[i]) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(_A , _A , atol=1e-5)) self.assertTrue(torch.allclose(_A , _A , atol=1e-5))
635
"""simple docstring""" import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCAmelCase_ = 16 lowerCAmelCase_ = 32 def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 16 )-> str: _SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetDict( { """train""": dataset["""train"""].select(__SCREAMING_SNAKE_CASE ), """validation""": dataset["""train"""].select(__SCREAMING_SNAKE_CASE ), """test""": dataset["""validation"""], } ) def tokenize_function(__SCREAMING_SNAKE_CASE ): # max_length=None => use the model max length (it's actually the default) _SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _SCREAMING_SNAKE_CASE : str = datasets.map( __SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _SCREAMING_SNAKE_CASE : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__SCREAMING_SNAKE_CASE ): # On TPU it's best to pad everything to the same length or training will be very slow. _SCREAMING_SNAKE_CASE : Any = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _SCREAMING_SNAKE_CASE : Optional[Any] = 16 elif accelerator.mixed_precision != "no": _SCREAMING_SNAKE_CASE : Any = 8 else: _SCREAMING_SNAKE_CASE : Optional[int] = None return tokenizer.pad( __SCREAMING_SNAKE_CASE , padding="""longest""" , max_length=__SCREAMING_SNAKE_CASE , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" , ) # Instantiate dataloaders. _SCREAMING_SNAKE_CASE : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__SCREAMING_SNAKE_CASE , collate_fn=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[int] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__SCREAMING_SNAKE_CASE , collate_fn=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = DataLoader( tokenized_datasets["""test"""] , shuffle=__SCREAMING_SNAKE_CASE , collate_fn=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE ) return train_dataloader, eval_dataloader, test_dataloader def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: # New Code # _SCREAMING_SNAKE_CASE : Union[str, Any] = [] # Download the dataset _SCREAMING_SNAKE_CASE : Union[str, Any] = load_dataset("""glue""" , """mrpc""" ) # Create our splits _SCREAMING_SNAKE_CASE : Dict = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator _SCREAMING_SNAKE_CASE : Any = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _SCREAMING_SNAKE_CASE : Tuple = config["""lr"""] _SCREAMING_SNAKE_CASE : Tuple = int(config["""num_epochs"""] ) _SCREAMING_SNAKE_CASE : int = int(config["""seed"""] ) _SCREAMING_SNAKE_CASE : int = int(config["""batch_size"""] ) _SCREAMING_SNAKE_CASE : List[str] = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation _SCREAMING_SNAKE_CASE : Any = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _SCREAMING_SNAKE_CASE : List[str] = batch_size // MAX_GPU_BATCH_SIZE _SCREAMING_SNAKE_CASE : List[str] = MAX_GPU_BATCH_SIZE set_seed(__SCREAMING_SNAKE_CASE ) # New Code # # Create our folds: _SCREAMING_SNAKE_CASE : List[str] = kfold.split(np.zeros(datasets["""train"""].num_rows ) , datasets["""train"""]["""label"""] ) _SCREAMING_SNAKE_CASE : Optional[Any] = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = get_fold_dataloaders( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _SCREAMING_SNAKE_CASE : Any = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__SCREAMING_SNAKE_CASE ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _SCREAMING_SNAKE_CASE : Tuple = model.to(accelerator.device ) # Instantiate optimizer _SCREAMING_SNAKE_CASE : int = AdamW(params=model.parameters() , lr=__SCREAMING_SNAKE_CASE ) # Instantiate scheduler _SCREAMING_SNAKE_CASE : int = get_linear_schedule_with_warmup( optimizer=__SCREAMING_SNAKE_CASE , num_warmup_steps=100 , num_training_steps=(len(__SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = accelerator.prepare( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Now we train the model for epoch in range(__SCREAMING_SNAKE_CASE ): model.train() for step, batch in enumerate(__SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _SCREAMING_SNAKE_CASE : Optional[Any] = model(**__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = outputs.loss _SCREAMING_SNAKE_CASE : List[Any] = loss / gradient_accumulation_steps accelerator.backward(__SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[str] = model(**__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : str = outputs.logits.argmax(dim=-1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__SCREAMING_SNAKE_CASE , references=__SCREAMING_SNAKE_CASE , ) _SCREAMING_SNAKE_CASE : Optional[int] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , __SCREAMING_SNAKE_CASE ) # New Code # # We also run predictions on the test set at the very end _SCREAMING_SNAKE_CASE : str = [] for step, batch in enumerate(__SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[str] = model(**__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[Any] = outputs.logits _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(__SCREAMING_SNAKE_CASE , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: _SCREAMING_SNAKE_CASE : Optional[int] = torch.cat(__SCREAMING_SNAKE_CASE , dim=0 ) _SCREAMING_SNAKE_CASE : List[str] = torch.stack(__SCREAMING_SNAKE_CASE , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) _SCREAMING_SNAKE_CASE : int = metric.compute(predictions=__SCREAMING_SNAKE_CASE , references=__SCREAMING_SNAKE_CASE ) accelerator.print("""Average test metrics from all folds:""" , __SCREAMING_SNAKE_CASE ) def lowerCamelCase_()-> Optional[Any]: _SCREAMING_SNAKE_CASE : Any = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) # New Code # parser.add_argument("""--num_folds""" , type=__SCREAMING_SNAKE_CASE , default=3 , help="""The number of splits to perform across the dataset""" ) _SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args() _SCREAMING_SNAKE_CASE : Optional[int] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
635
1
"""simple docstring""" import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class _snake_case ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = AutoImageProcessor.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""") _SCREAMING_SNAKE_CASE : str = AutoModelForImageClassification.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""") model.to(_A) from datasets import load_dataset _SCREAMING_SNAKE_CASE : Any = load_dataset("""nielsr/rvlcdip-demo""") _SCREAMING_SNAKE_CASE : Any = dataset["""train"""][0]["""image"""].convert("""RGB""") _SCREAMING_SNAKE_CASE : str = image_processor(_A , return_tensors="""pt""").to(_A) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE : Any = model(**_A) _SCREAMING_SNAKE_CASE : List[Any] = outputs.logits _SCREAMING_SNAKE_CASE : List[str] = torch.Size((1, 1_6)) self.assertEqual(logits.shape , _A) _SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [-0.4_158, -0.4_092, -0.4_347] , device=_A , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , _A , atol=1e-4))
635
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { '''configuration_clipseg''': [ '''CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPSegConfig''', '''CLIPSegTextConfig''', '''CLIPSegVisionConfig''', ], '''processing_clipseg''': ['''CLIPSegProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPSegModel''', '''CLIPSegPreTrainedModel''', '''CLIPSegTextModel''', '''CLIPSegVisionModel''', '''CLIPSegForImageSegmentation''', ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase_ = { '''configuration_roformer''': ['''ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoFormerConfig''', '''RoFormerOnnxConfig'''], '''tokenization_roformer''': ['''RoFormerTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''RoFormerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RoFormerForCausalLM''', '''RoFormerForMaskedLM''', '''RoFormerForMultipleChoice''', '''RoFormerForQuestionAnswering''', '''RoFormerForSequenceClassification''', '''RoFormerForTokenClassification''', '''RoFormerLayer''', '''RoFormerModel''', '''RoFormerPreTrainedModel''', '''load_tf_weights_in_roformer''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRoFormerForCausalLM''', '''TFRoFormerForMaskedLM''', '''TFRoFormerForMultipleChoice''', '''TFRoFormerForQuestionAnswering''', '''TFRoFormerForSequenceClassification''', '''TFRoFormerForTokenClassification''', '''TFRoFormerLayer''', '''TFRoFormerModel''', '''TFRoFormerPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxRoFormerForMaskedLM''', '''FlaxRoFormerForMultipleChoice''', '''FlaxRoFormerForQuestionAnswering''', '''FlaxRoFormerForSequenceClassification''', '''FlaxRoFormerForTokenClassification''', '''FlaxRoFormerModel''', '''FlaxRoFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
"""simple docstring""" import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class _snake_case : """simple docstring""" def __init__( self : int , _A : List[Any] , _A : int , _A : int): """simple docstring""" if dst_width < 0 or dst_height < 0: raise ValueError("""Destination width/height should be > 0""") _SCREAMING_SNAKE_CASE : str = img _SCREAMING_SNAKE_CASE : Optional[Any] = img.shape[1] _SCREAMING_SNAKE_CASE : Tuple = img.shape[0] _SCREAMING_SNAKE_CASE : Any = dst_width _SCREAMING_SNAKE_CASE : Any = dst_height _SCREAMING_SNAKE_CASE : Any = self.src_w / self.dst_w _SCREAMING_SNAKE_CASE : Dict = self.src_h / self.dst_h _SCREAMING_SNAKE_CASE : Optional[Any] = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta) * 2_5_5 ) def _lowerCAmelCase ( self : Tuple): """simple docstring""" for i in range(self.dst_h): for j in range(self.dst_w): _SCREAMING_SNAKE_CASE : Any = self.img[self.get_y(_A)][self.get_x(_A)] def _lowerCAmelCase ( self : int , _A : int): """simple docstring""" return int(self.ratio_x * x) def _lowerCAmelCase ( self : str , _A : int): """simple docstring""" return int(self.ratio_y * y) if __name__ == "__main__": lowerCAmelCase_ , lowerCAmelCase_ = 800, 600 lowerCAmelCase_ = imread('''image_data/lena.jpg''', 1) lowerCAmelCase_ = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}", n.output ) waitKey(0) destroyAllWindows()
635
1
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''speechbrain/m-ctc-t-large''': '''https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json''', # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class _snake_case ( __snake_case ): """simple docstring""" a = "mctct" def __init__( self : int , _A : List[Any]=8_0_6_5 , _A : Dict=1_5_3_6 , _A : Dict=3_6 , _A : Union[str, Any]=6_1_4_4 , _A : List[Any]=4 , _A : Optional[Any]=3_8_4 , _A : List[Any]=9_2_0 , _A : Union[str, Any]=1e-5 , _A : int=0.3 , _A : List[str]="relu" , _A : str=0.02 , _A : List[Any]=0.3 , _A : Tuple=0.3 , _A : List[str]=1 , _A : Any=0 , _A : Dict=2 , _A : Optional[int]=1 , _A : Optional[Any]=0.3 , _A : Union[str, Any]=1 , _A : Dict=(7,) , _A : Optional[int]=(3,) , _A : Optional[int]=8_0 , _A : Tuple=1 , _A : Optional[Any]=None , _A : Optional[Any]="sum" , _A : Optional[Any]=False , **_A : List[str] , ): """simple docstring""" super().__init__(**_A , pad_token_id=_A , bos_token_id=_A , eos_token_id=_A) _SCREAMING_SNAKE_CASE : List[Any] = vocab_size _SCREAMING_SNAKE_CASE : List[str] = hidden_size _SCREAMING_SNAKE_CASE : Optional[int] = num_hidden_layers _SCREAMING_SNAKE_CASE : Union[str, Any] = intermediate_size _SCREAMING_SNAKE_CASE : Any = num_attention_heads _SCREAMING_SNAKE_CASE : Optional[Any] = attention_head_dim _SCREAMING_SNAKE_CASE : str = max_position_embeddings _SCREAMING_SNAKE_CASE : Union[str, Any] = layer_norm_eps _SCREAMING_SNAKE_CASE : List[str] = layerdrop _SCREAMING_SNAKE_CASE : str = hidden_act _SCREAMING_SNAKE_CASE : List[Any] = initializer_range _SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob _SCREAMING_SNAKE_CASE : Any = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : Dict = pad_token_id _SCREAMING_SNAKE_CASE : Union[str, Any] = bos_token_id _SCREAMING_SNAKE_CASE : int = eos_token_id _SCREAMING_SNAKE_CASE : Tuple = conv_glu_dim _SCREAMING_SNAKE_CASE : List[str] = conv_dropout _SCREAMING_SNAKE_CASE : List[str] = num_conv_layers _SCREAMING_SNAKE_CASE : Optional[int] = input_feat_per_channel _SCREAMING_SNAKE_CASE : int = input_channels _SCREAMING_SNAKE_CASE : Tuple = conv_channels _SCREAMING_SNAKE_CASE : Dict = ctc_loss_reduction _SCREAMING_SNAKE_CASE : List[str] = ctc_zero_infinity # prevents config testing fail with exporting to json _SCREAMING_SNAKE_CASE : Union[str, Any] = list(_A) _SCREAMING_SNAKE_CASE : Any = list(_A) if len(self.conv_kernel) != self.num_conv_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.conv_kernel)` == `config.num_conv_layers` """ f"""but is `len(config.conv_kernel) = {len(self.conv_kernel)}`, """ f"""`config.num_conv_layers = {self.num_conv_layers}`.""")
635
"""simple docstring""" import argparse from collections import defaultdict def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> int: _SCREAMING_SNAKE_CASE : str = F"""{file}_{class_name}_{test_name}""" done_test[_id] += 1 with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: _SCREAMING_SNAKE_CASE : Union[str, Any] = f.readlines() _SCREAMING_SNAKE_CASE : Optional[Any] = F"""class {class_name}(""" _SCREAMING_SNAKE_CASE : List[Any] = F"""{4 * " "}def {test_name}(""" _SCREAMING_SNAKE_CASE : Tuple = F"""{8 * " "}{correct_line.split()[0]}""" _SCREAMING_SNAKE_CASE : List[Any] = F"""{16 * " "}{correct_line.split()[0]}""" _SCREAMING_SNAKE_CASE : List[str] = False _SCREAMING_SNAKE_CASE : Tuple = False _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[int] = False _SCREAMING_SNAKE_CASE : Any = 0 _SCREAMING_SNAKE_CASE : Optional[Any] = 0 _SCREAMING_SNAKE_CASE : Dict = [] for line in lines: if line.startswith(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = True elif in_class and line.startswith(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = True elif in_class and in_func and (line.startswith(__SCREAMING_SNAKE_CASE ) or line.startswith(__SCREAMING_SNAKE_CASE )): _SCREAMING_SNAKE_CASE : Dict = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: _SCREAMING_SNAKE_CASE : int = True if in_class and in_func and in_line: if ")" not in line: continue else: _SCREAMING_SNAKE_CASE : Any = True if in_class and in_func and in_line and insert_line: new_lines.append(F"""{spaces * " "}{correct_line}""" ) _SCREAMING_SNAKE_CASE : Optional[int] = False else: new_lines.append(__SCREAMING_SNAKE_CASE ) with open(__SCREAMING_SNAKE_CASE , """w""" ) as f: for line in new_lines: f.write(__SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None )-> Optional[Any]: if fail is not None: with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: _SCREAMING_SNAKE_CASE : Union[str, Any] = {l.strip() for l in f.readlines()} else: _SCREAMING_SNAKE_CASE : str = None with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: _SCREAMING_SNAKE_CASE : str = f.readlines() _SCREAMING_SNAKE_CASE : str = defaultdict(__SCREAMING_SNAKE_CASE ) for line in correct_lines: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = line.split(""";""" ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument('''--correct_filename''', help='''filename of tests with expected result''') parser.add_argument('''--fail_filename''', help='''filename of test failures''', type=str, default=None) lowerCAmelCase_ = parser.parse_args() main(args.correct_filename, args.fail_filename)
635
1
"""simple docstring""" import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process lowerCAmelCase_ = logging.getLogger(__name__) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> str: return (preds == labels).mean() @dataclass class _snake_case : """simple docstring""" a = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) a = field( default=__snake_case , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) a = field( default=__snake_case , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) a = field( default=__snake_case , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class _snake_case : """simple docstring""" a = field(metadata={"help": "The name of the task to train on: " + ", ".join(processors.keys() )} ) a = field(metadata={"help": "Should contain the data files for the task."} ) a = field( default=1_28 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) a = field( default=__snake_case , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def lowerCamelCase_()-> int: # 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. _SCREAMING_SNAKE_CASE : Optional[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" """ --overwrite_output_dir to overcome.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s""" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , 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""" , __SCREAMING_SNAKE_CASE ) # Set seed set_seed(training_args.seed ) try: _SCREAMING_SNAKE_CASE : Any = processors[data_args.task_name]() _SCREAMING_SNAKE_CASE : int = processor.get_labels() _SCREAMING_SNAKE_CASE : str = len(__SCREAMING_SNAKE_CASE ) except KeyError: raise ValueError("""Task not found: %s""" % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__SCREAMING_SNAKE_CASE , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) _SCREAMING_SNAKE_CASE : List[Any] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) _SCREAMING_SNAKE_CASE : List[str] = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , ) # Get datasets _SCREAMING_SNAKE_CASE : List[str] = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=__SCREAMING_SNAKE_CASE , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) _SCREAMING_SNAKE_CASE : Union[str, Any] = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=__SCREAMING_SNAKE_CASE , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def compute_metrics(__SCREAMING_SNAKE_CASE ) -> Dict: _SCREAMING_SNAKE_CASE : Optional[Any] = np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(__SCREAMING_SNAKE_CASE , p.label_ids )} # Data collator _SCREAMING_SNAKE_CASE : Optional[int] = DataCollatorWithPadding(__SCREAMING_SNAKE_CASE , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer _SCREAMING_SNAKE_CASE : Dict = Trainer( model=__SCREAMING_SNAKE_CASE , args=__SCREAMING_SNAKE_CASE , train_dataset=__SCREAMING_SNAKE_CASE , eval_dataset=__SCREAMING_SNAKE_CASE , compute_metrics=__SCREAMING_SNAKE_CASE , data_collator=__SCREAMING_SNAKE_CASE , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation _SCREAMING_SNAKE_CASE : str = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = trainer.evaluate() _SCREAMING_SNAKE_CASE : Dict = os.path.join(training_args.output_dir , """eval_results.txt""" ) if trainer.is_world_master(): with open(__SCREAMING_SNAKE_CASE , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in result.items(): logger.info(""" %s = %s""" , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) writer.write("""%s = %s\n""" % (key, value) ) results.update(__SCREAMING_SNAKE_CASE ) return results def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
635
"""simple docstring""" import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel lowerCAmelCase_ = { '''text_branch''': '''text_model''', '''audio_branch''': '''audio_model.audio_encoder''', '''attn''': '''attention.self''', '''self.proj''': '''output.dense''', '''attention.self_mask''': '''attn_mask''', '''mlp.fc1''': '''intermediate.dense''', '''mlp.fc2''': '''output.dense''', '''norm1''': '''layernorm_before''', '''norm2''': '''layernorm_after''', '''bn0''': '''batch_norm''', } lowerCAmelCase_ = AutoFeatureExtractor.from_pretrained('''laion/clap-htsat-unfused''', truncation='''rand_trunc''') def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False )-> str: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = create_model( """HTSAT-tiny""" , """roberta""" , __SCREAMING_SNAKE_CASE , precision="""fp32""" , device="""cuda:0""" if torch.cuda.is_available() else """cpu""" , enable_fusion=__SCREAMING_SNAKE_CASE , fusion_type="""aff_2d""" if enable_fusion else None , ) return model, model_cfg def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = {} _SCREAMING_SNAKE_CASE : Optional[Any] = R""".*sequential.(\d+).*""" _SCREAMING_SNAKE_CASE : Any = R""".*_projection.(\d+).*""" for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: _SCREAMING_SNAKE_CASE : Optional[Any] = key.replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # replace sequential layers with list _SCREAMING_SNAKE_CASE : List[Any] = re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).group(1 ) _SCREAMING_SNAKE_CASE : Dict = key.replace(F"""sequential.{sequential_layer}.""" , F"""layers.{int(__SCREAMING_SNAKE_CASE )//3}.linear.""" ) elif re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = int(re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... _SCREAMING_SNAKE_CASE : Dict = 1 if projecton_layer == 0 else 2 _SCREAMING_SNAKE_CASE : Union[str, Any] = key.replace(F"""_projection.{projecton_layer}.""" , F"""_projection.linear{transformers_projection_layer}.""" ) if "audio" and "qkv" in key: # split qkv into query key and value _SCREAMING_SNAKE_CASE : Dict = value _SCREAMING_SNAKE_CASE : List[Any] = mixed_qkv.size(0 ) // 3 _SCREAMING_SNAKE_CASE : Optional[Any] = mixed_qkv[:qkv_dim] _SCREAMING_SNAKE_CASE : str = mixed_qkv[qkv_dim : qkv_dim * 2] _SCREAMING_SNAKE_CASE : Any = mixed_qkv[qkv_dim * 2 :] _SCREAMING_SNAKE_CASE : Dict = query_layer _SCREAMING_SNAKE_CASE : List[Any] = key_layer _SCREAMING_SNAKE_CASE : Dict = value_layer else: _SCREAMING_SNAKE_CASE : Optional[Any] = value return model_state_dict def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False )-> List[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = init_clap(__SCREAMING_SNAKE_CASE , enable_fusion=__SCREAMING_SNAKE_CASE ) clap_model.eval() _SCREAMING_SNAKE_CASE : Dict = clap_model.state_dict() _SCREAMING_SNAKE_CASE : Tuple = rename_state_dict(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : int = ClapConfig() _SCREAMING_SNAKE_CASE : Tuple = enable_fusion _SCREAMING_SNAKE_CASE : Dict = ClapModel(__SCREAMING_SNAKE_CASE ) # ignore the spectrogram embedding layer model.load_state_dict(__SCREAMING_SNAKE_CASE , strict=__SCREAMING_SNAKE_CASE ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) transformers_config.save_pretrained(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = 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('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument('''--enable_fusion''', action='''store_true''', help='''Whether to enable fusion or not''') lowerCAmelCase_ = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
635
1
"""simple docstring""" import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ = get_tests_dir('''fixtures/test_sentencepiece_with_bytefallback.model''') @require_sentencepiece @require_tokenizers class _snake_case ( __snake_case , unittest.TestCase ): """simple docstring""" a = GPTSwaTokenizer a = False a = True a = False def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing _SCREAMING_SNAKE_CASE : Optional[int] = GPTSwaTokenizer(_A , eos_token="""<unk>""" , bos_token="""<unk>""" , pad_token="""<unk>""") tokenizer.save_pretrained(self.tmpdirname) def _lowerCAmelCase ( self : Any , _A : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = """This is a test""" _SCREAMING_SNAKE_CASE : Any = """This is a test""" return input_text, output_text def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = """<s>""" _SCREAMING_SNAKE_CASE : Dict = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A) , _A) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A) , _A) def _lowerCAmelCase ( self : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : str = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , """<unk>""") self.assertEqual(vocab_keys[1] , """<s>""") self.assertEqual(vocab_keys[-1] , """j""") self.assertEqual(len(_A) , 2_0_0_0) def _lowerCAmelCase ( self : Dict): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 2_0_0_0) def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = GPTSwaTokenizer(_A) _SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.tokenize("""This is a test""") self.assertListEqual(_A , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""]) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A) , [4_6_5, 2_8_7, 2_6_5, 6_3_1, 8_4_2]) _SCREAMING_SNAKE_CASE : List[Any] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""") # fmt: off self.assertListEqual( _A , ["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""] , ) # fmt: on _SCREAMING_SNAKE_CASE : Any = tokenizer.convert_tokens_to_ids(_A) self.assertListEqual( _A , [2_6_2, 2_7_2, 1_5_2_5, 2_8_6, 2_7_1, 2_6_8, 6_0, 9_1_6, 6_3_3, 6_3_3, 6_3_3, 2_5_9, 2_6_6, 3_0_1, 2_8_7, 3_8_4, 3_6_7, 2_6_3, 1_9_8, 1_7_2, 2_6_0] , ) _SCREAMING_SNAKE_CASE : str = tokenizer.convert_ids_to_tokens(_A) # fmt: off self.assertListEqual( _A , ["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""]) # fmt: on def _lowerCAmelCase ( self : int): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = GPTSwaTokenizer(_A) _SCREAMING_SNAKE_CASE : int = ["""This is a test""", """I was born in 92000, and this is falsé."""] _SCREAMING_SNAKE_CASE : Tuple = [ [4_6_5, 2_8_7, 2_6_5, 6_3_1, 8_4_2], [2_6_2, 2_7_2, 1_5_2_5, 2_8_6, 2_7_1, 2_6_8, 6_0, 9_1_6, 6_3_3, 6_3_3, 6_3_3, 2_5_9, 2_6_6, 3_0_1, 2_8_7, 3_8_4, 3_6_7, 2_6_3, 1_9_8, 1_7_2, 2_6_0], ] # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids for text, expected_ids in zip(_A , _A): self.assertListEqual(tokenizer.encode_fast(_A) , _A) # Test that decode_fast returns the input text for text, token_ids in zip(_A , _A): self.assertEqual(tokenizer.decode_fast(_A) , _A) @slow def _lowerCAmelCase ( self : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = [ """<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')""", """Hey there, how are you doing this fine day?""", """This is a text with a trailing spaces followed by a dot .""", """Häj sväjs lillebrör! =)""", """Det är inget fel på Mr. Cool""", ] # fmt: off _SCREAMING_SNAKE_CASE : Optional[int] = {"""input_ids""": [[6_3_4_2_3, 5, 6_8_1_1, 1_4_9_5_4, 2_8_2, 8_1_6, 3_8_2_1, 6_3_4_6_6, 6_3_4_2_5, 6_3_4_6_2, 1_8, 6_3_9_7_8, 6_7_8, 3_0_1, 1_3_2_0, 6_3_4_2_3, 6_3_4_5_5, 6_3_4_5_8, 1_8, 6_3_9_8_2, 4_2_4_6, 3_9_4_0, 1_9_0_1, 4_7_7_8_9, 5_5_4_7, 1_8_9_9_4], [1_9_6_3_0, 1_1_0_0, 6_3_4_4_6, 1_3_4_2, 6_3_3, 5_4_4, 4_4_8_8, 5_9_3, 5_1_0_2, 2_4_1_6, 6_3_4_9_5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_6_5_2, 4_2_8, 2_6_8, 1_9_3_6, 5_1_5, 2_6_8, 5_8_5_9_3, 2_2_4_1_3, 9_1_0_6, 5_4_6, 2_6_8, 3_3_2_1_3, 6_3_9_7_9, 6_9_8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5_5_1_3_0, 6_3_4_5_0, 9_2_4, 6_3_4_4_9, 2_2_4_9, 4_0_6_2, 1_5_5_8, 3_1_8, 6_3_5_0_4, 2_1_4_9_8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5_0_9, 3_7_7, 2_8_2_7, 2_5_5_9, 3_3_2, 6_5_7_5, 6_3_4_4_3, 2_6_8_0_1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """token_type_ids""": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [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], [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]]} # fmt: on self.tokenizer_integration_test_util( expected_encoding=_A , model_name="""AI-Sweden/gpt-sw3-126m""" , sequences=_A , )
635
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import 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.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.g4dn.xlarge", "results": {"train_runtime": 6_50, "eval_accuracy": 0.6, "eval_loss": 0.9}, }, { "framework": "tensorflow", "script": "run_tf.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.g4dn.xlarge", "results": {"train_runtime": 6_00, "eval_accuracy": 0.3, "eval_loss": 0.9}, }, ] ) class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" 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=_A , ) assert hasattr(self , """env""") def _lowerCAmelCase ( self : Union[str, Any] , _A : str=1): """simple docstring""" 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}-single""" , instance_count=_A , instance_type=self.instance_type , debugger_hook_config=_A , hyperparameters={**self.env.hyperparameters, """model_name_or_path""": self.model_name_or_path} , metric_definitions=self.env.metric_definitions , py_version="""py36""" , ) def _lowerCAmelCase ( self : Union[str, Any] , _A : Union[str, Any]): """simple docstring""" TrainingJobAnalytics(_A).export_csv(f"""{self.env.test_path}/{job_name}_metrics.csv""") def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : str = self.create_estimator() # run training estimator.fit() # result dataframe _SCREAMING_SNAKE_CASE : Any = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis _SCREAMING_SNAKE_CASE : Any = list(result_metrics_df[result_metrics_df.metric_name == """eval_accuracy"""]["""value"""]) _SCREAMING_SNAKE_CASE : Tuple = list(result_metrics_df[result_metrics_df.metric_name == """eval_loss"""]["""value"""]) # get train time from SageMaker job, this includes starting, preprocessing, stopping _SCREAMING_SNAKE_CASE : int = ( 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} , _A)
635
1
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process lowerCAmelCase_ = logging.getLogger(__name__) @dataclass class _snake_case : """simple docstring""" a = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) a = field( default=__snake_case , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) a = field( default="NER" , metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) a = field( default=__snake_case , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) a = field(default=__snake_case , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. a = field( default=__snake_case , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class _snake_case : """simple docstring""" a = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) a = field( default=__snake_case , metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} , ) a = field( default=1_28 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) a = field( default=__snake_case , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def lowerCamelCase_()-> int: # 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. _SCREAMING_SNAKE_CASE : Tuple = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" """ --overwrite_output_dir to overcome.""" ) _SCREAMING_SNAKE_CASE : Optional[int] = import_module("""tasks""" ) try: _SCREAMING_SNAKE_CASE : List[Any] = getattr(__SCREAMING_SNAKE_CASE , model_args.task_type ) _SCREAMING_SNAKE_CASE : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( F"""Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. """ F"""Available tasks classes are: {TokenClassificationTask.__subclasses__()}""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s""" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , 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""" , __SCREAMING_SNAKE_CASE ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task _SCREAMING_SNAKE_CASE : Dict = token_classification_task.get_labels(data_args.labels ) _SCREAMING_SNAKE_CASE : Dict[int, str] = dict(enumerate(__SCREAMING_SNAKE_CASE ) ) _SCREAMING_SNAKE_CASE : Optional[int] = len(__SCREAMING_SNAKE_CASE ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _SCREAMING_SNAKE_CASE : int = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__SCREAMING_SNAKE_CASE , idalabel=__SCREAMING_SNAKE_CASE , labelaid={label: i for i, label in enumerate(__SCREAMING_SNAKE_CASE )} , cache_dir=model_args.cache_dir , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) _SCREAMING_SNAKE_CASE : Dict = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , ) # Get datasets _SCREAMING_SNAKE_CASE : List[str] = ( TokenClassificationDataset( token_classification_task=__SCREAMING_SNAKE_CASE , data_dir=data_args.data_dir , tokenizer=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) _SCREAMING_SNAKE_CASE : List[str] = ( TokenClassificationDataset( token_classification_task=__SCREAMING_SNAKE_CASE , data_dir=data_args.data_dir , tokenizer=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Tuple[List[int], List[int]]: _SCREAMING_SNAKE_CASE : int = np.argmax(__SCREAMING_SNAKE_CASE , axis=2 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = preds.shape _SCREAMING_SNAKE_CASE : Optional[Any] = [[] for _ in range(__SCREAMING_SNAKE_CASE )] _SCREAMING_SNAKE_CASE : Dict = [[] for _ in range(__SCREAMING_SNAKE_CASE )] for i in range(__SCREAMING_SNAKE_CASE ): for j in range(__SCREAMING_SNAKE_CASE ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(__SCREAMING_SNAKE_CASE ) -> Dict: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ), "precision": precision_score(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ), "recall": recall_score(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ), "f1": fa_score(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ), } # Data collator _SCREAMING_SNAKE_CASE : Tuple = DataCollatorWithPadding(__SCREAMING_SNAKE_CASE , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer _SCREAMING_SNAKE_CASE : Tuple = Trainer( model=__SCREAMING_SNAKE_CASE , args=__SCREAMING_SNAKE_CASE , train_dataset=__SCREAMING_SNAKE_CASE , eval_dataset=__SCREAMING_SNAKE_CASE , compute_metrics=__SCREAMING_SNAKE_CASE , data_collator=__SCREAMING_SNAKE_CASE , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation _SCREAMING_SNAKE_CASE : Union[str, Any] = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) _SCREAMING_SNAKE_CASE : str = trainer.evaluate() _SCREAMING_SNAKE_CASE : Dict = os.path.join(training_args.output_dir , """eval_results.txt""" ) if trainer.is_world_process_zero(): with open(__SCREAMING_SNAKE_CASE , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in result.items(): logger.info(""" %s = %s""" , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) writer.write("""%s = %s\n""" % (key, value) ) results.update(__SCREAMING_SNAKE_CASE ) # Predict if training_args.do_predict: _SCREAMING_SNAKE_CASE : List[str] = TokenClassificationDataset( token_classification_task=__SCREAMING_SNAKE_CASE , data_dir=data_args.data_dir , tokenizer=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = trainer.predict(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = align_predictions(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Any = os.path.join(training_args.output_dir , """test_results.txt""" ) if trainer.is_world_process_zero(): with open(__SCREAMING_SNAKE_CASE , """w""" ) as writer: for key, value in metrics.items(): logger.info(""" %s = %s""" , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) writer.write("""%s = %s\n""" % (key, value) ) # Save predictions _SCREAMING_SNAKE_CASE : str = os.path.join(training_args.output_dir , """test_predictions.txt""" ) if trainer.is_world_process_zero(): with open(__SCREAMING_SNAKE_CASE , """w""" ) as writer: with open(os.path.join(data_args.data_dir , """test.txt""" ) , """r""" ) as f: token_classification_task.write_predictions_to_file(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return results def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> List[Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
635
"""simple docstring""" import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip lowerCAmelCase_ = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> List[str]: if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Any: return max(metric_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for gt in ground_truths ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[str]: _SCREAMING_SNAKE_CASE : List[str] = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Dict = [] if args.gold_data_mode == "qa": _SCREAMING_SNAKE_CASE : int = pd.read_csv(__SCREAMING_SNAKE_CASE , sep="""\t""" , header=__SCREAMING_SNAKE_CASE ) for answer_list in data[1]: _SCREAMING_SNAKE_CASE : Union[str, Any] = ast.literal_eval(__SCREAMING_SNAKE_CASE ) answers.append(__SCREAMING_SNAKE_CASE ) else: _SCREAMING_SNAKE_CASE : Optional[Any] = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Optional[int] = [[reference] for reference in references] _SCREAMING_SNAKE_CASE : Optional[int] = 0 for prediction, ground_truths in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): total += 1 em += metric_max_over_ground_truths(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) fa += metric_max_over_ground_truths(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = 1_00.0 * em / total _SCREAMING_SNAKE_CASE : Optional[Any] = 1_00.0 * fa / total logger.info(F"""F1: {fa:.2f}""" ) logger.info(F"""EM: {em:.2f}""" ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Tuple = args.k _SCREAMING_SNAKE_CASE : int = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Any = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Optional[Any] = 0 for hypo, reference in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = set(hypo.split("""\t""" )[:k] ) _SCREAMING_SNAKE_CASE : Union[str, Any] = set(reference.split("""\t""" ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k _SCREAMING_SNAKE_CASE : int = 1_00.0 * em / total logger.info(F"""Precision@{k}: {em: .2f}""" ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: def strip_title(__SCREAMING_SNAKE_CASE ): if title.startswith("""\"""" ): _SCREAMING_SNAKE_CASE : Optional[int] = title[1:] if title.endswith("""\"""" ): _SCREAMING_SNAKE_CASE : str = title[:-1] return title _SCREAMING_SNAKE_CASE : Dict = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( __SCREAMING_SNAKE_CASE , return_tensors="""pt""" , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , )["""input_ids"""].to(args.device ) _SCREAMING_SNAKE_CASE : List[str] = rag_model.rag.question_encoder(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Any = question_enc_outputs[0] _SCREAMING_SNAKE_CASE : List[Any] = rag_model.retriever( __SCREAMING_SNAKE_CASE , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors="""pt""" , ) _SCREAMING_SNAKE_CASE : Optional[int] = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [] for docs in all_docs: _SCREAMING_SNAKE_CASE : str = [strip_title(__SCREAMING_SNAKE_CASE ) for title in docs["""title"""]] provenance_strings.append("""\t""".join(__SCREAMING_SNAKE_CASE ) ) return provenance_strings def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[Any]: with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[Any] = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( __SCREAMING_SNAKE_CASE , return_tensors="""pt""" , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Union[str, Any] = inputs_dict.input_ids.to(args.device ) _SCREAMING_SNAKE_CASE : Union[str, Any] = inputs_dict.attention_mask.to(args.device ) _SCREAMING_SNAKE_CASE : Optional[Any] = rag_model.generate( # rag_model overwrites generate __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=__SCREAMING_SNAKE_CASE , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) _SCREAMING_SNAKE_CASE : Tuple = rag_model.retriever.generator_tokenizer.batch_decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) if args.print_predictions: for q, a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): logger.info("""Q: {} - A: {}""".format(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) return answers def lowerCamelCase_()-> List[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser() parser.add_argument( """--model_type""" , choices=["""rag_sequence""", """rag_token""", """bart"""] , type=__SCREAMING_SNAKE_CASE , help=( """RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the""" """ model_name_or_path""" ) , ) parser.add_argument( """--index_name""" , default=__SCREAMING_SNAKE_CASE , choices=["""exact""", """compressed""", """legacy"""] , type=__SCREAMING_SNAKE_CASE , help="""RAG model retriever type""" , ) parser.add_argument( """--index_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Path to the retrieval index""" , ) parser.add_argument("""--n_docs""" , default=5 , type=__SCREAMING_SNAKE_CASE , help="""Number of retrieved docs""" ) parser.add_argument( """--model_name_or_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to pretrained checkpoints or model identifier from huggingface.co/models""" , ) parser.add_argument( """--eval_mode""" , choices=["""e2e""", """retrieval"""] , default="""e2e""" , type=__SCREAMING_SNAKE_CASE , help=( """Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates""" """ precision@k.""" ) , ) parser.add_argument("""--k""" , default=1 , type=__SCREAMING_SNAKE_CASE , help="""k for the precision@k calculation""" ) parser.add_argument( """--evaluation_set""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to a file containing evaluation samples""" , ) parser.add_argument( """--gold_data_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to a tab-separated file with gold samples""" , ) parser.add_argument( """--gold_data_mode""" , default="""qa""" , type=__SCREAMING_SNAKE_CASE , choices=["""qa""", """ans"""] , help=( """Format of the gold data file""" """qa - a single line in the following format: question [tab] answer_list""" """ans - a single line of the gold file contains the expected answer string""" ) , ) parser.add_argument( """--predictions_path""" , type=__SCREAMING_SNAKE_CASE , default="""predictions.txt""" , help="""Name of the predictions file, to be stored in the checkpoints directory""" , ) parser.add_argument( """--eval_all_checkpoints""" , action="""store_true""" , help="""Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number""" , ) parser.add_argument( """--eval_batch_size""" , default=8 , type=__SCREAMING_SNAKE_CASE , help="""Batch size per GPU/CPU for evaluation.""" , ) parser.add_argument( """--recalculate""" , help="""Recalculate predictions even if the prediction file exists""" , action="""store_true""" , ) parser.add_argument( """--num_beams""" , default=4 , type=__SCREAMING_SNAKE_CASE , help="""Number of beams to be used when generating answers""" , ) parser.add_argument("""--min_length""" , default=1 , type=__SCREAMING_SNAKE_CASE , help="""Min length of the generated answers""" ) parser.add_argument("""--max_length""" , default=50 , type=__SCREAMING_SNAKE_CASE , help="""Max length of the generated answers""" ) parser.add_argument( """--print_predictions""" , action="""store_true""" , help="""If True, prints predictions while evaluating.""" , ) parser.add_argument( """--print_docs""" , action="""store_true""" , help="""If True, prints docs retried while generating.""" , ) _SCREAMING_SNAKE_CASE : Dict = parser.parse_args() _SCREAMING_SNAKE_CASE : Any = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) return args def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: _SCREAMING_SNAKE_CASE : Union[str, Any] = {} if args.model_type is None: _SCREAMING_SNAKE_CASE : Optional[int] = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith("""rag""" ): _SCREAMING_SNAKE_CASE : List[Any] = RagTokenForGeneration if args.model_type == """rag_token""" else RagSequenceForGeneration _SCREAMING_SNAKE_CASE : Optional[Any] = args.n_docs if args.index_name is not None: _SCREAMING_SNAKE_CASE : Optional[Any] = args.index_name if args.index_path is not None: _SCREAMING_SNAKE_CASE : Any = args.index_path else: _SCREAMING_SNAKE_CASE : Any = BartForConditionalGeneration _SCREAMING_SNAKE_CASE : int = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info("""Evaluate the following checkpoints: %s""" , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = get_scores if args.eval_mode == """e2e""" else get_precision_at_k _SCREAMING_SNAKE_CASE : Tuple = evaluate_batch_eae if args.eval_mode == """e2e""" else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info("""Calculating metrics based on an existing predictions file: {}""".format(args.predictions_path ) ) score_fn(__SCREAMING_SNAKE_CASE , args.predictions_path , args.gold_data_path ) continue logger.info("""***** Running evaluation for {} *****""".format(__SCREAMING_SNAKE_CASE ) ) logger.info(""" Batch size = %d""" , args.eval_batch_size ) logger.info(""" Predictions will be stored under {}""".format(args.predictions_path ) ) if args.model_type.startswith("""rag""" ): _SCREAMING_SNAKE_CASE : str = RagRetriever.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = model_class.from_pretrained(__SCREAMING_SNAKE_CASE , retriever=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) model.retriever.init_retrieval() else: _SCREAMING_SNAKE_CASE : str = model_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) model.to(args.device ) with open(args.evaluation_set , """r""" ) as eval_file, open(args.predictions_path , """w""" ) as preds_file: _SCREAMING_SNAKE_CASE : str = [] for line in tqdm(__SCREAMING_SNAKE_CASE ): questions.append(line.strip() ) if len(__SCREAMING_SNAKE_CASE ) == args.eval_batch_size: _SCREAMING_SNAKE_CASE : str = evaluate_batch_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) preds_file.write("""\n""".join(__SCREAMING_SNAKE_CASE ) + """\n""" ) preds_file.flush() _SCREAMING_SNAKE_CASE : Any = [] if len(__SCREAMING_SNAKE_CASE ) > 0: _SCREAMING_SNAKE_CASE : List[str] = evaluate_batch_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) preds_file.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) preds_file.flush() score_fn(__SCREAMING_SNAKE_CASE , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": lowerCAmelCase_ = get_args() main(args)
635
1
"""simple docstring""" import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class _snake_case ( nn.Module ): """simple docstring""" def __init__( self : Dict): """simple docstring""" super().__init__() _SCREAMING_SNAKE_CASE : Dict = nn.Linear(3 , 4) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.BatchNormad(4) _SCREAMING_SNAKE_CASE : List[str] = nn.Linear(4 , 5) def _lowerCAmelCase ( self : int , _A : Optional[Any]): """simple docstring""" return self.lineara(self.batchnorm(self.lineara(_A))) class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , model.state_dict()) _SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_A , """index.json""") self.assertTrue(os.path.isfile(_A)) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: _SCREAMING_SNAKE_CASE : int = os.path.join(_A , f"""{key}.dat""") self.assertTrue(os.path.isfile(_A)) # TODO: add tests on the fact weights are properly loaded def _lowerCAmelCase ( self : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.randn(2 , 3 , dtype=_A) with TemporaryDirectory() as tmp_dir: _SCREAMING_SNAKE_CASE : Tuple = offload_weight(_A , """weight""" , _A , {}) _SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_A , """weight.dat""") self.assertTrue(os.path.isfile(_A)) self.assertDictEqual(_A , {"""weight""": {"""shape""": [2, 3], """dtype""": str(_A).split(""".""")[1]}}) _SCREAMING_SNAKE_CASE : Optional[Any] = load_offloaded_weight(_A , index["""weight"""]) self.assertTrue(torch.equal(_A , _A)) def _lowerCAmelCase ( self : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : List[str] = ModelForTest() _SCREAMING_SNAKE_CASE : Optional[Any] = model.state_dict() _SCREAMING_SNAKE_CASE : Any = {k: v for k, v in state_dict.items() if """linear2""" not in k} _SCREAMING_SNAKE_CASE : Dict = {k: v for k, v in state_dict.items() if """linear2""" in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A) _SCREAMING_SNAKE_CASE : Dict = OffloadedWeightsLoader(state_dict=_A , save_folder=_A) # Every key is there with the right value self.assertEqual(sorted(_A) , sorted(state_dict.keys())) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key])) _SCREAMING_SNAKE_CASE : Dict = {k: v for k, v in state_dict.items() if """weight""" in k} _SCREAMING_SNAKE_CASE : Optional[Any] = {k: v for k, v in state_dict.items() if """weight""" not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A) _SCREAMING_SNAKE_CASE : Tuple = OffloadedWeightsLoader(state_dict=_A , save_folder=_A) # Every key is there with the right value self.assertEqual(sorted(_A) , sorted(state_dict.keys())) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key])) with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A) # Duplicates are removed _SCREAMING_SNAKE_CASE : List[str] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A) # Every key is there with the right value self.assertEqual(sorted(_A) , sorted(state_dict.keys())) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key])) def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = {"""a.1""": 0, """a.10""": 1, """a.2""": 2} _SCREAMING_SNAKE_CASE : List[Any] = extract_submodules_state_dict(_A , ["""a.1""", """a.2"""]) self.assertDictEqual(_A , {"""a.1""": 0, """a.2""": 2}) _SCREAMING_SNAKE_CASE : int = {"""a.1.a""": 0, """a.10.a""": 1, """a.2.a""": 2} _SCREAMING_SNAKE_CASE : str = extract_submodules_state_dict(_A , ["""a.1""", """a.2"""]) self.assertDictEqual(_A , {"""a.1.a""": 0, """a.2.a""": 2})
635
"""simple docstring""" import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def lowerCamelCase_(__SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=10 , __SCREAMING_SNAKE_CASE=100 , __SCREAMING_SNAKE_CASE=1_026 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE="data/tokenized_stories_train_wikitext103.jbl" , __SCREAMING_SNAKE_CASE="igf_context_pairs.jbl" , )-> Union[str, Any]: set_seed(3 ) # generate train_data and objective_set _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = generate_datasets( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , number=__SCREAMING_SNAKE_CASE , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? _SCREAMING_SNAKE_CASE : Dict = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) # load pretrained model _SCREAMING_SNAKE_CASE : Any = load_gpta("""gpt2""" ).to(__SCREAMING_SNAKE_CASE ) print("""computing perplexity on objective set""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).item() print("""perplexity on objective set:""" , __SCREAMING_SNAKE_CASE ) # collect igf pairs and save to file demo.jbl collect_objective_set(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=15 , __SCREAMING_SNAKE_CASE=128 , __SCREAMING_SNAKE_CASE=100 , __SCREAMING_SNAKE_CASE="igf_model.pt" , )-> Optional[int]: set_seed(42 ) # Load pre-trained model _SCREAMING_SNAKE_CASE : Any = GPTaLMHeadModel.from_pretrained("""gpt2""" ) # Initialize secondary learner to use embedding weights of model _SCREAMING_SNAKE_CASE : Union[str, Any] = SecondaryLearner(__SCREAMING_SNAKE_CASE ) # Train secondary learner _SCREAMING_SNAKE_CASE : Any = train_secondary_learner( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , max_epochs=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , eval_freq=100 , igf_model_path=__SCREAMING_SNAKE_CASE , ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_000 , __SCREAMING_SNAKE_CASE=16 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=recopy_gpta , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=10 , __SCREAMING_SNAKE_CASE="gpt2_finetuned.pt" , )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Tuple = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = RandomSampler(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = DataLoader(__SCREAMING_SNAKE_CASE , sampler=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = max_steps // (len(__SCREAMING_SNAKE_CASE )) + 1 _SCREAMING_SNAKE_CASE : List[Any] = 0 _SCREAMING_SNAKE_CASE : Any = torch.zeros((1, context_len) , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = recopy_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) model.train() if secondary_learner is not None: secondary_learner.to(__SCREAMING_SNAKE_CASE ) secondary_learner.eval() _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : Optional[int] = 0 _SCREAMING_SNAKE_CASE : Optional[Any] = [] _SCREAMING_SNAKE_CASE : int = [] # Compute the performance of the transformer model at the beginning _SCREAMING_SNAKE_CASE : Tuple = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) test_perps.append(__SCREAMING_SNAKE_CASE ) print("""Test perplexity, step""" , __SCREAMING_SNAKE_CASE , """:""" , __SCREAMING_SNAKE_CASE ) for epoch in range(int(__SCREAMING_SNAKE_CASE ) ): for step, example in enumerate(__SCREAMING_SNAKE_CASE ): torch.cuda.empty_cache() _SCREAMING_SNAKE_CASE : Any = random.randint(0 , example.size(2 ) - context_len - 1 ) _SCREAMING_SNAKE_CASE : int = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() _SCREAMING_SNAKE_CASE : Union[str, Any] = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[str] = True if secondary_learner is not None: _SCREAMING_SNAKE_CASE : List[Any] = secondary_learner.forward( torch.tensor(__SCREAMING_SNAKE_CASE , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ).unsqueeze(0 ) )[0].item() observed_qs.append(float(__SCREAMING_SNAKE_CASE ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: _SCREAMING_SNAKE_CASE : Dict = -1 if predicted_q < threshold: _SCREAMING_SNAKE_CASE : List[str] = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() _SCREAMING_SNAKE_CASE : Any = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: _SCREAMING_SNAKE_CASE : Tuple = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) test_perps.append(__SCREAMING_SNAKE_CASE ) print("""Test perplexity, step""" , __SCREAMING_SNAKE_CASE , """:""" , __SCREAMING_SNAKE_CASE ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() , __SCREAMING_SNAKE_CASE ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def lowerCamelCase_()-> Tuple: _SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser(description="""Fine-tune a transformer model with IGF on a language modeling task""" ) # Required parameters parser.add_argument( """--data_dir""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The input data dir. Should contain data files for WikiText.""" , ) parser.add_argument( """--model_name_or_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to pretrained model or model identifier from huggingface.co/models""" , ) parser.add_argument( """--data_file""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help=( """A jbl file containing tokenized data which can be split as objective dataset, """ """train_dataset and test_dataset.""" ) , ) parser.add_argument( """--igf_data_file""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help="""A jbl file containing the context and information gain pairs to train secondary learner.""" , ) parser.add_argument( """--output_dir""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The output directory where the final fine-tuned model is stored.""" , ) parser.add_argument( """--tokenizer_name""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Pretrained tokenizer name or path if not the same as model_name""" , ) parser.add_argument("""--seed""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help="""A seed for reproducible training.""" ) parser.add_argument( """--context_len""" , default=32 , type=__SCREAMING_SNAKE_CASE , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--size_objective_set""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""number of articles that are long enough to be used as our objective set""" , ) parser.add_argument( """--eval_freq""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""secondary model evaluation is triggered at eval_freq""" ) parser.add_argument("""--max_steps""" , default=1_000 , type=__SCREAMING_SNAKE_CASE , help="""To calculate training epochs""" ) parser.add_argument( """--secondary_learner_batch_size""" , default=128 , type=__SCREAMING_SNAKE_CASE , help="""batch size of training data for secondary learner""" , ) parser.add_argument( """--batch_size""" , default=16 , type=__SCREAMING_SNAKE_CASE , help="""batch size of training data of language model(gpt2) """ ) parser.add_argument( """--eval_interval""" , default=10 , type=__SCREAMING_SNAKE_CASE , help=( """decay the selectivity of our secondary learner filter from""" """1 standard deviation above average to 1 below average after 10 batches""" ) , ) parser.add_argument( """--number""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""The number of examples split to be used as objective_set/test_data""" ) parser.add_argument( """--min_len""" , default=1_026 , type=__SCREAMING_SNAKE_CASE , help="""The minimum length of the article to be used as objective set""" ) parser.add_argument( """--secondary_learner_max_epochs""" , default=15 , type=__SCREAMING_SNAKE_CASE , help="""number of epochs to train secondary learner""" ) parser.add_argument("""--trim""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""truncate the example if it exceeds context length""" ) parser.add_argument( """--threshold""" , default=1.0 , type=__SCREAMING_SNAKE_CASE , help=( """The threshold value used by secondary learner to filter the train_data and allow only""" """ informative data as input to the model""" ) , ) parser.add_argument("""--finetuned_model_name""" , default="""gpt2_finetuned.pt""" , type=__SCREAMING_SNAKE_CASE , help="""finetuned_model_name""" ) parser.add_argument( """--recopy_model""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Reset the model to the original pretrained GPT-2 weights after each iteration""" , ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 , max_steps=10 , size_objective_set=100 , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE , data_file="""data/tokenized_stories_train_wikitext103.jbl""" , igf_data_file="""igf_context_pairs.jbl""" , ) # Load train data for secondary learner _SCREAMING_SNAKE_CASE : Optional[int] = joblib.load("""data/IGF_values.jbl""" ) # Train secondary learner _SCREAMING_SNAKE_CASE : int = training_secondary_learner( __SCREAMING_SNAKE_CASE , secondary_learner_max_epochs=15 , secondary_learner_batch_size=128 , eval_freq=100 , igf_model_path="""igf_model.pt""" , ) # load pretrained gpt2 model _SCREAMING_SNAKE_CASE : List[Any] = GPTaLMHeadModel.from_pretrained("""gpt2""" ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = generate_datasets( context_len=32 , file="""data/tokenized_stories_train_wikitext103.jbl""" , number=100 , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , context_len=32 , max_steps=1_000 , batch_size=16 , threshold=1.0 , recopy_model=__SCREAMING_SNAKE_CASE , secondary_learner=__SCREAMING_SNAKE_CASE , eval_interval=10 , finetuned_model_name="""gpt2_finetuned.pt""" , ) if __name__ == "__main__": main()
635
1
"""simple docstring""" from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. lowerCAmelCase_ = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. lowerCAmelCase_ = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. lowerCAmelCase_ = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> tuple[str, float]: _SCREAMING_SNAKE_CASE : Tuple = len([g for position, g in enumerate(__SCREAMING_SNAKE_CASE ) if g == main_target[position]] ) return (item, float(__SCREAMING_SNAKE_CASE )) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> tuple[str, str]: _SCREAMING_SNAKE_CASE : Union[str, Any] = random.randint(0 , len(__SCREAMING_SNAKE_CASE ) - 1 ) _SCREAMING_SNAKE_CASE : Any = parent_a[:random_slice] + parent_a[random_slice:] _SCREAMING_SNAKE_CASE : Dict = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> str: _SCREAMING_SNAKE_CASE : Any = list(__SCREAMING_SNAKE_CASE ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: _SCREAMING_SNAKE_CASE : Optional[int] = random.choice(__SCREAMING_SNAKE_CASE ) return "".join(__SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , )-> list[str]: _SCREAMING_SNAKE_CASE : Dict = [] # Generate more children proportionally to the fitness score. _SCREAMING_SNAKE_CASE : Any = int(parent_a[1] * 100 ) + 1 _SCREAMING_SNAKE_CASE : str = 10 if child_n >= 10 else child_n for _ in range(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = population_score[random.randint(0 , __SCREAMING_SNAKE_CASE )][0] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = crossover(parent_a[0] , __SCREAMING_SNAKE_CASE ) # Append new string to the population list. pop.append(mutate(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) pop.append(mutate(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) return pop def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = True )-> tuple[int, int, str]: # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: _SCREAMING_SNAKE_CASE : int = F"""{N_POPULATION} must be bigger than {N_SELECTED}""" raise ValueError(__SCREAMING_SNAKE_CASE ) # Verify that the target contains no genes besides the ones inside genes variable. _SCREAMING_SNAKE_CASE : List[str] = sorted({c for c in target if c not in genes} ) if not_in_genes_list: _SCREAMING_SNAKE_CASE : int = F"""{not_in_genes_list} is not in genes list, evolution cannot converge""" raise ValueError(__SCREAMING_SNAKE_CASE ) # Generate random starting population. _SCREAMING_SNAKE_CASE : List[Any] = [] for _ in range(__SCREAMING_SNAKE_CASE ): population.append("""""".join([random.choice(__SCREAMING_SNAKE_CASE ) for i in range(len(__SCREAMING_SNAKE_CASE ) )] ) ) # Just some logs to know what the algorithms is doing. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(__SCREAMING_SNAKE_CASE ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. _SCREAMING_SNAKE_CASE : Union[str, Any] = [evaluate(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for item in population] # Check if there is a matching evolution. _SCREAMING_SNAKE_CASE : Any = sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : x[1] , reverse=__SCREAMING_SNAKE_CASE ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F"""\nGeneration: {generation}""" F"""\nTotal Population:{total_population}""" F"""\nBest score: {population_score[0][1]}""" F"""\nBest string: {population_score[0][0]}""" ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. _SCREAMING_SNAKE_CASE : Dict = population[: int(N_POPULATION / 3 )] population.clear() population.extend(__SCREAMING_SNAKE_CASE ) # Normalize population score to be between 0 and 1. _SCREAMING_SNAKE_CASE : List[str] = [ (item, score / len(__SCREAMING_SNAKE_CASE )) for item, score in population_score ] # This is selection for i in range(__SCREAMING_SNAKE_CASE ): population.extend(select(population_score[int(__SCREAMING_SNAKE_CASE )] , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(__SCREAMING_SNAKE_CASE ) > N_POPULATION: break if __name__ == "__main__": lowerCAmelCase_ = ( '''This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!''' ) lowerCAmelCase_ = list( ''' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm''' '''nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\''' ) lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = basic(target_str, genes_list) print( F"\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}" )
635
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _snake_case ( __snake_case ): """simple docstring""" a = ["image_processor", "tokenizer"] a = "ChineseCLIPImageProcessor" a = ("BertTokenizer", "BertTokenizerFast") def __init__( self : Dict , _A : Tuple=None , _A : List[Any]=None , **_A : int): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , _A , ) _SCREAMING_SNAKE_CASE : str = kwargs.pop("""feature_extractor""") _SCREAMING_SNAKE_CASE : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""") if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""") super().__init__(_A , _A) _SCREAMING_SNAKE_CASE : Dict = self.image_processor def __call__( self : Optional[int] , _A : Optional[Any]=None , _A : Any=None , _A : Tuple=None , **_A : int): """simple docstring""" if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""") if text is not None: _SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer(_A , return_tensors=_A , **_A) if images is not None: _SCREAMING_SNAKE_CASE : List[Any] = self.image_processor(_A , return_tensors=_A , **_A) if text is not None and images is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_A) , tensor_type=_A) def _lowerCAmelCase ( self : str , *_A : Any , **_A : Any): """simple docstring""" return self.tokenizer.batch_decode(*_A , **_A) def _lowerCAmelCase ( self : Union[str, Any] , *_A : List[Any] , **_A : Any): """simple docstring""" return self.tokenizer.decode(*_A , **_A) @property def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.model_input_names _SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def _lowerCAmelCase ( self : List[str]): """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , _A , ) return self.image_processor_class
635
1
"""simple docstring""" from manim import * class _snake_case ( __snake_case ): """simple docstring""" def _lowerCAmelCase ( self : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = Rectangle(height=0.5 , width=0.5) _SCREAMING_SNAKE_CASE : List[Any] = Rectangle(height=0.46 , width=0.46).set_stroke(width=0) _SCREAMING_SNAKE_CASE : Tuple = [mem.copy() for i in range(6)] _SCREAMING_SNAKE_CASE : List[str] = [mem.copy() for i in range(6)] _SCREAMING_SNAKE_CASE : Optional[Any] = VGroup(*_A).arrange(_A , buff=0) _SCREAMING_SNAKE_CASE : str = VGroup(*_A).arrange(_A , buff=0) _SCREAMING_SNAKE_CASE : List[str] = VGroup(_A , _A).arrange(_A , buff=0) _SCREAMING_SNAKE_CASE : Any = Text("""CPU""" , font_size=2_4) _SCREAMING_SNAKE_CASE : Dict = Group(_A , _A).arrange(_A , buff=0.5 , aligned_edge=_A) cpu.move_to([-2.5, -0.5, 0]) self.add(_A) _SCREAMING_SNAKE_CASE : Dict = [mem.copy() for i in range(4)] _SCREAMING_SNAKE_CASE : int = VGroup(*_A).arrange(_A , buff=0) _SCREAMING_SNAKE_CASE : str = Text("""GPU""" , font_size=2_4) _SCREAMING_SNAKE_CASE : Tuple = Group(_A , _A).arrange(_A , buff=0.5 , aligned_edge=_A) gpu.move_to([-1, -1, 0]) self.add(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = [mem.copy() for i in range(6)] _SCREAMING_SNAKE_CASE : Optional[Any] = VGroup(*_A).arrange(_A , buff=0) _SCREAMING_SNAKE_CASE : Optional[int] = Text("""Model""" , font_size=2_4) _SCREAMING_SNAKE_CASE : Optional[Any] = Group(_A , _A).arrange(_A , buff=0.5 , aligned_edge=_A) model.move_to([3, -1.0, 0]) self.add(_A) _SCREAMING_SNAKE_CASE : List[str] = [] for i, rect in enumerate(_A): rect.set_stroke(_A) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) _SCREAMING_SNAKE_CASE : Optional[int] = Rectangle(height=0.46 / 4 , width=0.46 / 3).set_stroke(width=0.0).set_fill(_A , opacity=0.7) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT) , buff=0.02 , direction=_A) cpu_target.set_x(cpu_target.get_x() + 0.1) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=_A , buff=0.0) else: cpu_target.next_to(cpu_targs[i - 1] , direction=_A , buff=0.0) self.add(_A) cpu_targs.append(_A) _SCREAMING_SNAKE_CASE : List[str] = [mem.copy() for i in range(6)] _SCREAMING_SNAKE_CASE : int = VGroup(*_A).arrange(_A , buff=0) _SCREAMING_SNAKE_CASE : Union[str, Any] = Text("""Loaded Checkpoint""" , font_size=2_4) _SCREAMING_SNAKE_CASE : Dict = Group(_A , _A).arrange(_A , aligned_edge=_A , buff=0.4) checkpoint.move_to([3, 0.5, 0]) _SCREAMING_SNAKE_CASE : Optional[Any] = Square(side_length=2.2) key.move_to([-5, 2, 0]) _SCREAMING_SNAKE_CASE : str = MarkupText( f"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" , font_size=1_8 , ) key_text.move_to([-5, 2.4, 0]) self.add(_A , _A) _SCREAMING_SNAKE_CASE : List[str] = MarkupText( f"""<span fgcolor='{BLUE}'>●</span> Checkpoint""" , font_size=1_8 , ) blue_text.next_to(_A , DOWN * 2.4 , aligned_edge=key_text.get_left()) _SCREAMING_SNAKE_CASE : List[str] = MarkupText( f"""Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>.""" , font_size=2_4 , ) step_a.move_to([2, 2, 0]) self.play(Write(_A) , Write(_A)) self.play(Write(_A , run_time=1) , Create(_A , run_time=1)) _SCREAMING_SNAKE_CASE : List[str] = [] _SCREAMING_SNAKE_CASE : Union[str, Any] = [] for i, rect in enumerate(_A): _SCREAMING_SNAKE_CASE : str = fill.copy().set_fill(_A , opacity=0.7) target.move_to(_A) first_animations.append(GrowFromCenter(_A , run_time=1)) _SCREAMING_SNAKE_CASE : List[Any] = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1]) else: cpu_target.target.move_to(cpu_right_col_base[i - 5]) second_animations.append(MoveToTarget(_A , run_time=1.5)) self.play(*_A) self.play(*_A) self.wait()
635
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = ['''model.decoder.embed_positions.weights'''] def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[int]: if "emb" in name: _SCREAMING_SNAKE_CASE : List[Any] = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: _SCREAMING_SNAKE_CASE : List[str] = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: _SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: _SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: _SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: _SCREAMING_SNAKE_CASE : int = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: _SCREAMING_SNAKE_CASE : Dict = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: _SCREAMING_SNAKE_CASE : Dict = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: _SCREAMING_SNAKE_CASE : Tuple = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: _SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: _SCREAMING_SNAKE_CASE : str = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple[Dict, Dict]: _SCREAMING_SNAKE_CASE : str = list(state_dict.keys() ) _SCREAMING_SNAKE_CASE : Tuple = {} for key in keys: _SCREAMING_SNAKE_CASE : Dict = state_dict.pop(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : int = rename_keys(__SCREAMING_SNAKE_CASE ) if "in_proj_weight" in key: # split fused qkv proj _SCREAMING_SNAKE_CASE : str = val[:hidden_size, :] _SCREAMING_SNAKE_CASE : Any = val[hidden_size : 2 * hidden_size, :] _SCREAMING_SNAKE_CASE : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: _SCREAMING_SNAKE_CASE : int = val else: _SCREAMING_SNAKE_CASE : Dict = val return state_dict, enc_dec_proj_state_dict def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> MusicgenDecoderConfig: if checkpoint == "small": # default config values _SCREAMING_SNAKE_CASE : Optional[Any] = 1_024 _SCREAMING_SNAKE_CASE : str = 24 _SCREAMING_SNAKE_CASE : Any = 16 elif checkpoint == "medium": _SCREAMING_SNAKE_CASE : Dict = 1_536 _SCREAMING_SNAKE_CASE : Union[str, Any] = 48 _SCREAMING_SNAKE_CASE : Optional[Any] = 24 elif checkpoint == "large": _SCREAMING_SNAKE_CASE : List[Any] = 2_048 _SCREAMING_SNAKE_CASE : Optional[int] = 48 _SCREAMING_SNAKE_CASE : str = 32 else: raise ValueError(F"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) _SCREAMING_SNAKE_CASE : Optional[Any] = MusicgenDecoderConfig( hidden_size=__SCREAMING_SNAKE_CASE , ffn_dim=hidden_size * 4 , num_hidden_layers=__SCREAMING_SNAKE_CASE , num_attention_heads=__SCREAMING_SNAKE_CASE , ) return config @torch.no_grad() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="cpu" )-> str: _SCREAMING_SNAKE_CASE : str = MusicGen.get_pretrained(__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[str] = decoder_config_from_checkpoint(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[Any] = fairseq_model.lm.state_dict() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = rename_state_dict( __SCREAMING_SNAKE_CASE , hidden_size=decoder_config.hidden_size ) _SCREAMING_SNAKE_CASE : Tuple = TaEncoderModel.from_pretrained("""t5-base""" ) _SCREAMING_SNAKE_CASE : List[Any] = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) _SCREAMING_SNAKE_CASE : str = MusicgenForCausalLM(__SCREAMING_SNAKE_CASE ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = decoder.load_state_dict(__SCREAMING_SNAKE_CASE , strict=__SCREAMING_SNAKE_CASE ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ValueError(F"""Missing key(s) in state_dict: {missing_keys}""" ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ValueError(F"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model _SCREAMING_SNAKE_CASE : Dict = MusicgenForConditionalGeneration(text_encoder=__SCREAMING_SNAKE_CASE , audio_encoder=__SCREAMING_SNAKE_CASE , decoder=__SCREAMING_SNAKE_CASE ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(__SCREAMING_SNAKE_CASE ) # check we can do a forward pass _SCREAMING_SNAKE_CASE : Optional[Any] = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) _SCREAMING_SNAKE_CASE : Dict = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[int] = model(input_ids=__SCREAMING_SNAKE_CASE , decoder_input_ids=__SCREAMING_SNAKE_CASE ).logits if logits.shape != (8, 1, 2_048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor _SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained("""t5-base""" ) _SCREAMING_SNAKE_CASE : List[str] = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) _SCREAMING_SNAKE_CASE : Optional[int] = MusicgenProcessor(feature_extractor=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE ) # set the appropriate bos/pad token ids _SCREAMING_SNAKE_CASE : Optional[Any] = 2_048 _SCREAMING_SNAKE_CASE : List[Any] = 2_048 # set other default generation config params _SCREAMING_SNAKE_CASE : Any = int(30 * audio_encoder.config.frame_rate ) _SCREAMING_SNAKE_CASE : Tuple = True _SCREAMING_SNAKE_CASE : int = 3.0 if pytorch_dump_folder is not None: Path(__SCREAMING_SNAKE_CASE ).mkdir(exist_ok=__SCREAMING_SNAKE_CASE ) logger.info(F"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) processor.save_pretrained(__SCREAMING_SNAKE_CASE ) if repo_id: logger.info(F"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(__SCREAMING_SNAKE_CASE ) processor.push_to_hub(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint''', default='''small''', type=str, help='''Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.''', ) parser.add_argument( '''--pytorch_dump_folder''', required=True, default=None, type=str, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) parser.add_argument( '''--device''', default='''cpu''', type=str, help='''Torch device to run the conversion, either cpu or cuda.''' ) lowerCAmelCase_ = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
635
1
"""simple docstring""" from __future__ import annotations lowerCAmelCase_ = list[list[int]] # assigning initial values to the grid lowerCAmelCase_ = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution lowerCAmelCase_ = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Matrix | None: if location := find_empty_location(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = digit if sudoku(__SCREAMING_SNAKE_CASE ) is not None: return grid _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 return None def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> None: for row in grid: for cell in row: print(__SCREAMING_SNAKE_CASE , end=""" """ ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 20) print_solution(example_grid) print('''\nExample grid solution:''') lowerCAmelCase_ = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
635
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''asapp/sew-tiny-100k''': '''https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json''', # See all SEW models at https://huggingface.co/models?filter=sew } class _snake_case ( __snake_case ): """simple docstring""" a = "sew" def __init__( self : List[Any] , _A : Tuple=3_2 , _A : str=7_6_8 , _A : Dict=1_2 , _A : Tuple=1_2 , _A : Optional[Any]=3_0_7_2 , _A : List[str]=2 , _A : Dict="gelu" , _A : Union[str, Any]=0.1 , _A : Optional[int]=0.1 , _A : Optional[int]=0.1 , _A : Optional[int]=0.0 , _A : str=0.1 , _A : Tuple=0.1 , _A : Optional[int]=0.02 , _A : Dict=1e-5 , _A : str="group" , _A : Tuple="gelu" , _A : Union[str, Any]=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , _A : Optional[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , _A : Any=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , _A : Tuple=False , _A : Tuple=1_2_8 , _A : int=1_6 , _A : Union[str, Any]=True , _A : Optional[Any]=0.05 , _A : List[Any]=1_0 , _A : Union[str, Any]=2 , _A : Tuple=0.0 , _A : Union[str, Any]=1_0 , _A : Optional[int]=0 , _A : Union[str, Any]="mean" , _A : Optional[int]=False , _A : List[Any]=False , _A : int=2_5_6 , _A : str=0 , _A : Optional[int]=1 , _A : List[Any]=2 , **_A : Dict , ): """simple docstring""" super().__init__(**_A , pad_token_id=_A , bos_token_id=_A , eos_token_id=_A) _SCREAMING_SNAKE_CASE : str = hidden_size _SCREAMING_SNAKE_CASE : Optional[int] = feat_extract_norm _SCREAMING_SNAKE_CASE : Optional[int] = feat_extract_activation _SCREAMING_SNAKE_CASE : Dict = list(_A) _SCREAMING_SNAKE_CASE : int = list(_A) _SCREAMING_SNAKE_CASE : int = list(_A) _SCREAMING_SNAKE_CASE : str = conv_bias _SCREAMING_SNAKE_CASE : Tuple = num_conv_pos_embeddings _SCREAMING_SNAKE_CASE : List[str] = num_conv_pos_embedding_groups _SCREAMING_SNAKE_CASE : Tuple = len(self.conv_dim) _SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers _SCREAMING_SNAKE_CASE : List[str] = intermediate_size _SCREAMING_SNAKE_CASE : str = squeeze_factor _SCREAMING_SNAKE_CASE : Dict = hidden_act _SCREAMING_SNAKE_CASE : str = num_attention_heads _SCREAMING_SNAKE_CASE : Dict = hidden_dropout _SCREAMING_SNAKE_CASE : Tuple = attention_dropout _SCREAMING_SNAKE_CASE : int = activation_dropout _SCREAMING_SNAKE_CASE : Any = feat_proj_dropout _SCREAMING_SNAKE_CASE : str = final_dropout _SCREAMING_SNAKE_CASE : Union[str, Any] = layerdrop _SCREAMING_SNAKE_CASE : Any = layer_norm_eps _SCREAMING_SNAKE_CASE : int = initializer_range _SCREAMING_SNAKE_CASE : List[Any] = vocab_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect.""" """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,""" f"""but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride)""" f"""= {len(self.conv_stride)}`, `len(config.conv_kernel) = {len(self.conv_kernel)}`.""") # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _SCREAMING_SNAKE_CASE : List[Any] = apply_spec_augment _SCREAMING_SNAKE_CASE : List[Any] = mask_time_prob _SCREAMING_SNAKE_CASE : List[str] = mask_time_length _SCREAMING_SNAKE_CASE : List[Any] = mask_time_min_masks _SCREAMING_SNAKE_CASE : List[Any] = mask_feature_prob _SCREAMING_SNAKE_CASE : int = mask_feature_length _SCREAMING_SNAKE_CASE : List[Any] = mask_feature_min_masks # ctc loss _SCREAMING_SNAKE_CASE : int = ctc_loss_reduction _SCREAMING_SNAKE_CASE : Optional[int] = ctc_zero_infinity # sequence classification _SCREAMING_SNAKE_CASE : Dict = use_weighted_layer_sum _SCREAMING_SNAKE_CASE : List[str] = classifier_proj_size @property def _lowerCAmelCase ( self : Any): """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1)
635
1
"""simple docstring""" from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent lowerCAmelCase_ = {'''UserAgent''': UserAgent().random} def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> dict: _SCREAMING_SNAKE_CASE : str = script.contents[0] _SCREAMING_SNAKE_CASE : int = json.loads(data[data.find("""{\"config\"""" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class _snake_case : """simple docstring""" def __init__( self : Any , _A : int): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = f"""https://www.instagram.com/{username}/""" _SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_json() def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : int = requests.get(self.url , headers=_A).text _SCREAMING_SNAKE_CASE : Optional[int] = BeautifulSoup(_A , """html.parser""").find_all("""script""") try: return extract_user_profile(scripts[4]) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3]) def __repr__( self : str): """simple docstring""" return f"""{self.__class__.__name__}('{self.username}')""" def __str__( self : List[str]): """simple docstring""" return f"""{self.fullname} ({self.username}) is {self.biography}""" @property def _lowerCAmelCase ( self : Union[str, Any]): """simple docstring""" return self.user_data["username"] @property def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" return self.user_data["full_name"] @property def _lowerCAmelCase ( self : List[Any]): """simple docstring""" return self.user_data["biography"] @property def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" return self.user_data["business_email"] @property def _lowerCAmelCase ( self : List[str]): """simple docstring""" return self.user_data["external_url"] @property def _lowerCAmelCase ( self : List[Any]): """simple docstring""" return self.user_data["edge_followed_by"]["count"] @property def _lowerCAmelCase ( self : int): """simple docstring""" return self.user_data["edge_follow"]["count"] @property def _lowerCAmelCase ( self : int): """simple docstring""" return self.user_data["edge_owner_to_timeline_media"]["count"] @property def _lowerCAmelCase ( self : Dict): """simple docstring""" return self.user_data["profile_pic_url_hd"] @property def _lowerCAmelCase ( self : List[Any]): """simple docstring""" return self.user_data["is_verified"] @property def _lowerCAmelCase ( self : Dict): """simple docstring""" return self.user_data["is_private"] def lowerCamelCase_(__SCREAMING_SNAKE_CASE = "github" )-> None: import os if os.environ.get("""CI""" ): return # test failing on GitHub Actions _SCREAMING_SNAKE_CASE : Optional[int] = InstagramUser(__SCREAMING_SNAKE_CASE ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __SCREAMING_SNAKE_CASE ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120_000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("""https://instagram.""" ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase_ = InstagramUser('''github''') print(instagram_user) print(F"{instagram_user.number_of_posts = }") print(F"{instagram_user.number_of_followers = }") print(F"{instagram_user.number_of_followings = }") print(F"{instagram_user.email = }") print(F"{instagram_user.website = }") print(F"{instagram_user.profile_picture_url = }") print(F"{instagram_user.is_verified = }") print(F"{instagram_user.is_private = }")
635
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCAmelCase_ = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mvp import MvpTokenizer lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} # See all MVP models at https://huggingface.co/models?filter=mvp lowerCAmelCase_ = { '''vocab_file''': { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json''', }, '''added_tokens.json''': { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json''', }, '''merges_file''': { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json''', }, } lowerCAmelCase_ = { '''RUCAIBox/mvp''': 1024, } class _snake_case ( __snake_case ): """simple docstring""" a = VOCAB_FILES_NAMES a = PRETRAINED_VOCAB_FILES_MAP a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a = ["input_ids", "attention_mask"] a = MvpTokenizer def __init__( self : Optional[Any] , _A : List[str]=None , _A : Optional[int]=None , _A : Optional[Any]=None , _A : Optional[int]="replace" , _A : Optional[Any]="<s>" , _A : Optional[Any]="</s>" , _A : str="</s>" , _A : Union[str, Any]="<s>" , _A : Union[str, Any]="<unk>" , _A : Any="<pad>" , _A : Optional[Any]="<mask>" , _A : int=False , _A : Optional[int]=True , **_A : Optional[Any] , ): """simple docstring""" super().__init__( _A , _A , tokenizer_file=_A , errors=_A , bos_token=_A , eos_token=_A , sep_token=_A , cls_token=_A , unk_token=_A , pad_token=_A , mask_token=_A , add_prefix_space=_A , trim_offsets=_A , **_A , ) _SCREAMING_SNAKE_CASE : str = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get("""add_prefix_space""" , _A) != add_prefix_space: _SCREAMING_SNAKE_CASE : List[Any] = getattr(_A , pre_tok_state.pop("""type""")) _SCREAMING_SNAKE_CASE : str = add_prefix_space _SCREAMING_SNAKE_CASE : int = pre_tok_class(**_A) _SCREAMING_SNAKE_CASE : str = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` _SCREAMING_SNAKE_CASE : Tuple = """post_processor""" _SCREAMING_SNAKE_CASE : Optional[Any] = getattr(self.backend_tokenizer , _A , _A) if tokenizer_component_instance: _SCREAMING_SNAKE_CASE : Dict = json.loads(tokenizer_component_instance.__getstate__()) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: _SCREAMING_SNAKE_CASE : Any = tuple(state["""sep"""]) if "cls" in state: _SCREAMING_SNAKE_CASE : str = tuple(state["""cls"""]) _SCREAMING_SNAKE_CASE : Any = False if state.get("""add_prefix_space""" , _A) != add_prefix_space: _SCREAMING_SNAKE_CASE : str = add_prefix_space _SCREAMING_SNAKE_CASE : Dict = True if state.get("""trim_offsets""" , _A) != trim_offsets: _SCREAMING_SNAKE_CASE : List[Any] = trim_offsets _SCREAMING_SNAKE_CASE : Tuple = True if changes_to_apply: _SCREAMING_SNAKE_CASE : str = getattr(_A , state.pop("""type""")) _SCREAMING_SNAKE_CASE : int = component_class(**_A) setattr(self.backend_tokenizer , _A , _A) @property def _lowerCAmelCase ( self : int): """simple docstring""" if self._mask_token is None: if self.verbose: logger.error("""Using mask_token, but it is not set yet.""") return None return str(self._mask_token) @mask_token.setter def _lowerCAmelCase ( self : Dict , _A : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : str = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else value _SCREAMING_SNAKE_CASE : Any = value def _lowerCAmelCase ( self : List[str] , *_A : Dict , **_A : int): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = kwargs.get("""is_split_into_words""" , _A) if is_split_into_words and not self.add_prefix_space: raise ValueError( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ """to use it with pretokenized inputs.""") return super()._batch_encode_plus(*_A , **_A) def _lowerCAmelCase ( self : str , *_A : Optional[Any] , **_A : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = kwargs.get("""is_split_into_words""" , _A) if is_split_into_words and not self.add_prefix_space: raise ValueError( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ """to use it with pretokenized inputs.""") return super()._encode_plus(*_A , **_A) def _lowerCAmelCase ( self : Optional[Any] , _A : str , _A : Optional[str] = None): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = self._tokenizer.model.save(_A , name=_A) return tuple(_A) def _lowerCAmelCase ( self : Any , _A : List[str] , _A : List[str]=None): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def _lowerCAmelCase ( self : Union[str, Any] , _A : List[int] , _A : Optional[List[int]] = None): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = [self.sep_token_id] _SCREAMING_SNAKE_CASE : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]
635
"""simple docstring""" import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: _SCREAMING_SNAKE_CASE : List[str] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Union[str, Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _SCREAMING_SNAKE_CASE : List[Any] = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: _SCREAMING_SNAKE_CASE : int = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : str = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : List[Any] = features.copy() if features else default_expected_features _SCREAMING_SNAKE_CASE : List[Any] = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) _SCREAMING_SNAKE_CASE : Optional[Any] = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: _SCREAMING_SNAKE_CASE : Tuple = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : int = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : Dict = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , split=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""" , [str, list] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> str: if issubclass(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = parquet_path elif issubclass(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = [parquet_path] _SCREAMING_SNAKE_CASE : Optional[Any] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Union[str, Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : str = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=("train",) )-> Union[str, Any]: assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for split in splits: _SCREAMING_SNAKE_CASE : int = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Optional[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _SCREAMING_SNAKE_CASE : Tuple = ParquetDatasetReader( {"""train""": parquet_path} , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: _SCREAMING_SNAKE_CASE : Optional[int] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Optional[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : List[str] = features.copy() if features else default_expected_features _SCREAMING_SNAKE_CASE : str = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) _SCREAMING_SNAKE_CASE : int = ParquetDatasetReader({"""train""": parquet_path} , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: if split: _SCREAMING_SNAKE_CASE : Union[str, Any] = {split: parquet_path} else: _SCREAMING_SNAKE_CASE : Optional[int] = """train""" _SCREAMING_SNAKE_CASE : Any = {"""train""": parquet_path, """test""": parquet_path} _SCREAMING_SNAKE_CASE : List[str] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : List[str] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : Union[str, Any] = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[Any]: _SCREAMING_SNAKE_CASE : List[str] = ParquetDatasetWriter(__SCREAMING_SNAKE_CASE , tmp_path / """foo.parquet""" ) assert writer.write() > 0 _SCREAMING_SNAKE_CASE : Tuple = pq.ParquetFile(tmp_path / """foo.parquet""" ) _SCREAMING_SNAKE_CASE : str = pf.read() assert dataset.data.table == output_table def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Dict = str(shared_datadir / """test_image_rgb.jpg""" ) _SCREAMING_SNAKE_CASE : Optional[Any] = {"""image""": [image_path]} _SCREAMING_SNAKE_CASE : Optional[Any] = Features({"""image""": Image()} ) _SCREAMING_SNAKE_CASE : Optional[int] = Dataset.from_dict(__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = ParquetDatasetWriter(__SCREAMING_SNAKE_CASE , tmp_path / """foo.parquet""" ) assert writer.write() > 0 _SCREAMING_SNAKE_CASE : List[str] = Dataset.from_parquet(str(tmp_path / """foo.parquet""" ) ) assert dataset.features == reloaded_dataset.features _SCREAMING_SNAKE_CASE : List[Any] = ParquetDatasetReader(str(tmp_path / """foo.parquet""" ) , streaming=__SCREAMING_SNAKE_CASE ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( """feature, expected""" , [ (Features({"""foo""": Value("""int32""" )} ), None), (Features({"""image""": Image(), """foo""": Value("""int32""" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"""nested""": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> int: assert get_writer_batch_size(__SCREAMING_SNAKE_CASE ) == expected
635
1
"""simple docstring""" from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class _snake_case : """simple docstring""" def __init__( self : Tuple , _A : Optional[Any] , _A : int=1_3 , _A : Any=3_0 , _A : Optional[Any]=2 , _A : int=3 , _A : List[str]=True , _A : Optional[int]=True , _A : List[str]=3_2 , _A : Optional[Any]=2 , _A : List[str]=4 , _A : int=3_7 , _A : Any="gelu" , _A : List[Any]=0.1 , _A : int=0.1 , _A : List[Any]=1_0 , _A : str=0.02 , _A : Union[str, Any]=3 , _A : Any=None , _A : List[str]=2 , ): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = parent _SCREAMING_SNAKE_CASE : Optional[int] = batch_size _SCREAMING_SNAKE_CASE : Tuple = image_size _SCREAMING_SNAKE_CASE : Union[str, Any] = patch_size _SCREAMING_SNAKE_CASE : List[Any] = num_channels _SCREAMING_SNAKE_CASE : Any = is_training _SCREAMING_SNAKE_CASE : Any = use_labels _SCREAMING_SNAKE_CASE : int = hidden_size _SCREAMING_SNAKE_CASE : List[str] = num_hidden_layers _SCREAMING_SNAKE_CASE : Any = num_attention_heads _SCREAMING_SNAKE_CASE : int = intermediate_size _SCREAMING_SNAKE_CASE : Tuple = hidden_act _SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob _SCREAMING_SNAKE_CASE : List[str] = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : Any = type_sequence_label_size _SCREAMING_SNAKE_CASE : Dict = initializer_range _SCREAMING_SNAKE_CASE : Optional[int] = scope _SCREAMING_SNAKE_CASE : List[str] = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) _SCREAMING_SNAKE_CASE : Any = (image_size // patch_size) ** 2 _SCREAMING_SNAKE_CASE : List[str] = num_patches + 2 def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) _SCREAMING_SNAKE_CASE : Dict = None if self.use_labels: _SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size) _SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, labels def _lowerCAmelCase ( self : Tuple): """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_A , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def _lowerCAmelCase ( self : Tuple , _A : Any , _A : Tuple , _A : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = TFDeiTModel(config=_A) _SCREAMING_SNAKE_CASE : Tuple = model(_A) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def _lowerCAmelCase ( self : List[Any] , _A : Optional[Any] , _A : Union[str, Any] , _A : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = TFDeiTForMaskedImageModeling(config=_A) _SCREAMING_SNAKE_CASE : Dict = model(_A) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size)) # test greyscale images _SCREAMING_SNAKE_CASE : Union[str, Any] = 1 _SCREAMING_SNAKE_CASE : str = TFDeiTForMaskedImageModeling(_A) _SCREAMING_SNAKE_CASE : Tuple = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) _SCREAMING_SNAKE_CASE : int = model(_A) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size)) def _lowerCAmelCase ( self : Optional[int] , _A : Optional[int] , _A : Union[str, Any] , _A : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : int = self.type_sequence_label_size _SCREAMING_SNAKE_CASE : Any = TFDeiTForImageClassification(_A) _SCREAMING_SNAKE_CASE : str = model(_A , labels=_A) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) # test greyscale images _SCREAMING_SNAKE_CASE : Dict = 1 _SCREAMING_SNAKE_CASE : str = TFDeiTForImageClassification(_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) _SCREAMING_SNAKE_CASE : Optional[Any] = model(_A , labels=_A) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" _SCREAMING_SNAKE_CASE : int = self.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = config_and_inputs _SCREAMING_SNAKE_CASE : Optional[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class _snake_case ( __snake_case , __snake_case , unittest.TestCase ): """simple docstring""" a = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) a = ( { "feature-extraction": TFDeiTModel, "image-classification": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) a = False a = False a = False a = False def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = TFDeiTModelTester(self) _SCREAMING_SNAKE_CASE : int = ConfigTester(self , config_class=_A , has_text_modality=_A , hidden_size=3_7) def _lowerCAmelCase ( self : Union[str, Any]): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""DeiT does not use inputs_embeds""") def _lowerCAmelCase ( self : int): """simple docstring""" pass def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : str = model_class(_A) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer)) _SCREAMING_SNAKE_CASE : List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_A , tf.keras.layers.Dense)) def _lowerCAmelCase ( self : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Any = model_class(_A) _SCREAMING_SNAKE_CASE : Any = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic _SCREAMING_SNAKE_CASE : Optional[Any] = [*signature.parameters.keys()] _SCREAMING_SNAKE_CASE : List[Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _A) def _lowerCAmelCase ( self : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A) def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_A) def _lowerCAmelCase ( self : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A) def _lowerCAmelCase ( self : Optional[int] , _A : List[str] , _A : Union[str, Any] , _A : Union[str, Any]=False): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = super()._prepare_for_class(_A , _A , return_labels=_A) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call).parameters: del inputs_dict["labels"] return inputs_dict @slow def _lowerCAmelCase ( self : Any): """simple docstring""" for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE : Optional[Any] = TFDeiTModel.from_pretrained(_A) self.assertIsNotNone(_A) def lowerCamelCase_()-> str: _SCREAMING_SNAKE_CASE : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class _snake_case ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : str): """simple docstring""" return ( DeiTImageProcessor.from_pretrained("""facebook/deit-base-distilled-patch16-224""") if is_vision_available() else None ) @slow def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : List[str] = TFDeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-patch16-224""") _SCREAMING_SNAKE_CASE : Dict = self.default_image_processor _SCREAMING_SNAKE_CASE : Any = prepare_img() _SCREAMING_SNAKE_CASE : List[str] = image_processor(images=_A , return_tensors="""tf""") # forward pass _SCREAMING_SNAKE_CASE : List[Any] = model(**_A) # verify the logits _SCREAMING_SNAKE_CASE : Optional[Any] = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape , _A) _SCREAMING_SNAKE_CASE : Optional[Any] = tf.constant([-1.0_266, 0.1_912, -1.2_861]) self.assertTrue(np.allclose(outputs.logits[0, :3] , _A , atol=1e-4))
635
"""simple docstring""" def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise TypeError("""only integers accepted as input""" ) else: _SCREAMING_SNAKE_CASE : List[Any] = str(abs(__SCREAMING_SNAKE_CASE ) ) _SCREAMING_SNAKE_CASE : List[str] = [list(__SCREAMING_SNAKE_CASE ) for char in range(len(__SCREAMING_SNAKE_CASE ) )] for index in range(len(__SCREAMING_SNAKE_CASE ) ): num_transpositions[index].pop(__SCREAMING_SNAKE_CASE ) return max( int("""""".join(list(__SCREAMING_SNAKE_CASE ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('''doctest''').testmod()
635
1
"""simple docstring""" def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> list: _SCREAMING_SNAKE_CASE : Union[str, Any] = len(__SCREAMING_SNAKE_CASE ) for _ in range(__SCREAMING_SNAKE_CASE ): for i in range(_ % 2 , arr_size - 1 , 2 ): if arr[i + 1] < arr[i]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = arr[i + 1], arr[i] return arr if __name__ == "__main__": lowerCAmelCase_ = list(range(10, 0, -1)) print(F"Original: {arr}. Sorted: {odd_even_transposition(arr)}")
635
"""simple docstring""" import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers import AutoModelForCausalLM @require_torch class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : Any = -1 _SCREAMING_SNAKE_CASE : List[str] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : Dict = model.generate(_A , max_new_tokens=1_0 , do_sample=_A) _SCREAMING_SNAKE_CASE : Dict = tokenizer.decode(greedy_ids[0]) with CaptureStdout() as cs: _SCREAMING_SNAKE_CASE : Any = TextStreamer(_A) model.generate(_A , max_new_tokens=1_0 , do_sample=_A , streamer=_A) # The greedy text should be printed to stdout, except for the final "\n" in the streamer _SCREAMING_SNAKE_CASE : str = cs.out[:-1] self.assertEqual(_A , _A) def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : Any = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : List[Any] = -1 _SCREAMING_SNAKE_CASE : str = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = model.generate(_A , max_new_tokens=1_0 , do_sample=_A) _SCREAMING_SNAKE_CASE : Any = tokenizer.decode(greedy_ids[0]) _SCREAMING_SNAKE_CASE : List[Any] = TextIteratorStreamer(_A) _SCREAMING_SNAKE_CASE : Any = {"""input_ids""": input_ids, """max_new_tokens""": 1_0, """do_sample""": False, """streamer""": streamer} _SCREAMING_SNAKE_CASE : List[Any] = Thread(target=model.generate , kwargs=_A) thread.start() _SCREAMING_SNAKE_CASE : Any = """""" for new_text in streamer: streamer_text += new_text self.assertEqual(_A , _A) def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : Any = -1 _SCREAMING_SNAKE_CASE : Any = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = model.generate(_A , max_new_tokens=1_0 , do_sample=_A) _SCREAMING_SNAKE_CASE : str = greedy_ids[:, input_ids.shape[1] :] _SCREAMING_SNAKE_CASE : Dict = tokenizer.decode(new_greedy_ids[0]) with CaptureStdout() as cs: _SCREAMING_SNAKE_CASE : Any = TextStreamer(_A , skip_prompt=_A) model.generate(_A , max_new_tokens=1_0 , do_sample=_A , streamer=_A) # The greedy text should be printed to stdout, except for the final "\n" in the streamer _SCREAMING_SNAKE_CASE : Optional[int] = cs.out[:-1] self.assertEqual(_A , _A) def _lowerCAmelCase ( self : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained("""distilgpt2""") _SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForCausalLM.from_pretrained("""distilgpt2""").to(_A) _SCREAMING_SNAKE_CASE : int = -1 _SCREAMING_SNAKE_CASE : List[str] = torch.ones((1, 5) , device=_A).long() * model.config.bos_token_id with CaptureStdout() as cs: _SCREAMING_SNAKE_CASE : Optional[int] = TextStreamer(_A , skip_special_tokens=_A) model.generate(_A , max_new_tokens=1 , do_sample=_A , streamer=_A) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token _SCREAMING_SNAKE_CASE : Optional[Any] = cs.out[:-1] # Remove the final "\n" _SCREAMING_SNAKE_CASE : Tuple = tokenizer(_A , return_tensors="""pt""") self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1)) def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : List[Any] = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : Tuple = -1 _SCREAMING_SNAKE_CASE : Dict = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : int = TextIteratorStreamer(_A , timeout=0.001) _SCREAMING_SNAKE_CASE : List[Any] = {"""input_ids""": input_ids, """max_new_tokens""": 1_0, """do_sample""": False, """streamer""": streamer} _SCREAMING_SNAKE_CASE : List[str] = Thread(target=model.generate , kwargs=_A) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(_A): _SCREAMING_SNAKE_CASE : str = """""" for new_text in streamer: streamer_text += new_text
635
1
"""simple docstring""" import importlib.metadata import operator import re import sys from typing import Optional from packaging import version lowerCAmelCase_ = { '''<''': operator.lt, '''<=''': operator.le, '''==''': operator.eq, '''!=''': operator.ne, '''>=''': operator.ge, '''>''': operator.gt, } def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: if got_ver is None or want_ver is None: raise ValueError( F"""Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider""" F""" reinstalling {pkg}.""" ) if not ops[op](version.parse(__SCREAMING_SNAKE_CASE ) , version.parse(__SCREAMING_SNAKE_CASE ) ): raise ImportError( F"""{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}""" ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None )-> None: _SCREAMING_SNAKE_CASE : int = F"""\n{hint}""" if hint is not None else """""" # non-versioned check if re.match(R"""^[\w_\-\d]+$""" , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = requirement, None, None else: _SCREAMING_SNAKE_CASE : Dict = re.findall(R"""^([^!=<>\s]+)([\s!=<>]{1,2}.+)""" , __SCREAMING_SNAKE_CASE ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but""" F""" got {requirement}""" ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = match[0] _SCREAMING_SNAKE_CASE : Tuple = want_full.split(""",""" ) # there could be multiple requirements _SCREAMING_SNAKE_CASE : Dict = {} for w in want_range: _SCREAMING_SNAKE_CASE : str = re.findall(R"""^([\s!=<>]{1,2})(.+)""" , __SCREAMING_SNAKE_CASE ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,""" F""" but got {requirement}""" ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = match[0] _SCREAMING_SNAKE_CASE : Dict = want_ver if op not in ops: raise ValueError(F"""{requirement}: need one of {list(ops.keys() )}, but got {op}""" ) # special case if pkg == "python": _SCREAMING_SNAKE_CASE : Dict = """.""".join([str(__SCREAMING_SNAKE_CASE ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return # check if any version is installed try: _SCREAMING_SNAKE_CASE : Tuple = importlib.metadata.version(__SCREAMING_SNAKE_CASE ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( F"""The '{requirement}' distribution was not found and is required by this application. {hint}""" ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : List[str] = """Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main""" return require_version(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
635
"""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 torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _snake_case ( __snake_case ): """simple docstring""" a = "facebook/bart-large-mnli" a = ( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) a = "text_classifier" a = AutoTokenizer a = AutoModelForSequenceClassification a = ["text", ["text"]] a = ["text"] def _lowerCAmelCase ( self : int): """simple docstring""" super().setup() _SCREAMING_SNAKE_CASE : Any = self.model.config _SCREAMING_SNAKE_CASE : Any = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail"""): _SCREAMING_SNAKE_CASE : List[Any] = int(_A) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""") def _lowerCAmelCase ( self : Optional[Any] , _A : Tuple , _A : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = labels return self.pre_processor( [text] * len(_A) , [f"""This example is {label}""" for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def _lowerCAmelCase ( self : Tuple , _A : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : str = outputs.logits _SCREAMING_SNAKE_CASE : List[Any] = torch.argmax(logits[:, 2]).item() return self._labels[label_id]
635
1
"""simple docstring""" lowerCAmelCase_ = 65521 def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: _SCREAMING_SNAKE_CASE : int = 1 _SCREAMING_SNAKE_CASE : Optional[int] = 0 for plain_chr in plain_text: _SCREAMING_SNAKE_CASE : Union[str, Any] = (a + ord(__SCREAMING_SNAKE_CASE )) % MOD_ADLER _SCREAMING_SNAKE_CASE : List[Any] = (b + a) % MOD_ADLER return (b << 16) | a
635
"""simple docstring""" import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class _snake_case ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = AutoImageProcessor.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""") _SCREAMING_SNAKE_CASE : str = AutoModelForImageClassification.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""") model.to(_A) from datasets import load_dataset _SCREAMING_SNAKE_CASE : Any = load_dataset("""nielsr/rvlcdip-demo""") _SCREAMING_SNAKE_CASE : Any = dataset["""train"""][0]["""image"""].convert("""RGB""") _SCREAMING_SNAKE_CASE : str = image_processor(_A , return_tensors="""pt""").to(_A) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE : Any = model(**_A) _SCREAMING_SNAKE_CASE : List[Any] = outputs.logits _SCREAMING_SNAKE_CASE : List[str] = torch.Size((1, 1_6)) self.assertEqual(logits.shape , _A) _SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [-0.4_158, -0.4_092, -0.4_347] , device=_A , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , _A , atol=1e-4))
635
1
"""simple docstring""" from math import pow, sqrt def lowerCamelCase_(*__SCREAMING_SNAKE_CASE )-> bool: _SCREAMING_SNAKE_CASE : str = len(__SCREAMING_SNAKE_CASE ) > 0 and all(value > 0.0 for value in values ) return result def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> float | ValueError: return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else ValueError("""Input Error: Molar mass values must greater than 0.""" ) ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> float | ValueError: return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> float | ValueError: return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> float | ValueError: return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> float | ValueError: return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) )
635
"""simple docstring""" import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class _snake_case ( __snake_case ): """simple docstring""" a = "M-CLIP" def __init__( self : Optional[Any] , _A : List[str]=1_0_2_4 , _A : Union[str, Any]=7_6_8 , **_A : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = transformerDimSize _SCREAMING_SNAKE_CASE : List[str] = imageDimSize super().__init__(**_A) class _snake_case ( __snake_case ): """simple docstring""" a = MCLIPConfig def __init__( self : Dict , _A : Optional[Any] , *_A : Any , **_A : Dict): """simple docstring""" super().__init__(_A , *_A , **_A) _SCREAMING_SNAKE_CASE : Tuple = XLMRobertaModel(_A) _SCREAMING_SNAKE_CASE : List[Any] = torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims) def _lowerCAmelCase ( self : Union[str, Any] , _A : str , _A : int): """simple docstring""" _SCREAMING_SNAKE_CASE : str = self.transformer(input_ids=_A , attention_mask=_A)[0] _SCREAMING_SNAKE_CASE : Optional[Any] = (embs * attention_mask.unsqueeze(2)).sum(dim=1) / attention_mask.sum(dim=1)[:, None] return self.LinearTransformation(_A), embs
635
1
"""simple docstring""" import enum import shutil import sys lowerCAmelCase_ , lowerCAmelCase_ = shutil.get_terminal_size() lowerCAmelCase_ = {'''UP''': '''A''', '''DOWN''': '''B''', '''RIGHT''': '''C''', '''LEFT''': '''D'''} class _snake_case ( enum.Enum ): """simple docstring""" a = 0 a = 1 def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="" )-> Any: sys.stdout.write(str(__SCREAMING_SNAKE_CASE ) + end ) sys.stdout.flush() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="" )-> str: forceWrite(F"""\u001b[{color}m{content}\u001b[0m""" , __SCREAMING_SNAKE_CASE ) def lowerCamelCase_()-> Optional[Any]: forceWrite("""\r""" ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Any: forceWrite(F"""\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}""" ) def lowerCamelCase_()-> Dict: forceWrite(""" """ * TERMINAL_WIDTH ) reset_cursor() def lowerCamelCase_()-> Any: reset_cursor() forceWrite("""-""" * TERMINAL_WIDTH )
635
"""simple docstring""" from decimal import Decimal, getcontext from math import ceil, factorial def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> str: if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise TypeError("""Undefined for non-integers""" ) elif precision < 1: raise ValueError("""Undefined for non-natural numbers""" ) _SCREAMING_SNAKE_CASE : int = precision _SCREAMING_SNAKE_CASE : Dict = ceil(precision / 14 ) _SCREAMING_SNAKE_CASE : int = 426_880 * Decimal(10_005 ).sqrt() _SCREAMING_SNAKE_CASE : Union[str, Any] = 1 _SCREAMING_SNAKE_CASE : str = 13_591_409 _SCREAMING_SNAKE_CASE : Tuple = Decimal(__SCREAMING_SNAKE_CASE ) for k in range(1 , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = factorial(6 * k ) // (factorial(3 * k ) * factorial(__SCREAMING_SNAKE_CASE ) ** 3) linear_term += 545_140_134 exponential_term *= -262_537_412_640_768_000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": lowerCAmelCase_ = 50 print(F"The first {n} digits of pi is: {pi(n)}")
635
1
"""simple docstring""" # DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class _snake_case ( __snake_case , __snake_case ): """simple docstring""" a = 1 @register_to_config def __init__( self : Union[str, Any] , _A : Optional[int]=2_0_0_0 , _A : Any=0.1 , _A : Optional[Any]=2_0 , _A : Optional[Any]=1e-3): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = None _SCREAMING_SNAKE_CASE : int = None _SCREAMING_SNAKE_CASE : Any = None def _lowerCAmelCase ( self : Tuple , _A : Optional[Any] , _A : Union[str, torch.device] = None): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = torch.linspace(1 , self.config.sampling_eps , _A , device=_A) def _lowerCAmelCase ( self : int , _A : List[str] , _A : List[Any] , _A : Union[str, Any] , _A : Any=None): """simple docstring""" if self.timesteps is None: raise ValueError( """`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler""") # TODO(Patrick) better comments + non-PyTorch # postprocess model score _SCREAMING_SNAKE_CASE : Optional[Any] = ( -0.25 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) _SCREAMING_SNAKE_CASE : List[Any] = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff)) _SCREAMING_SNAKE_CASE : List[str] = std.flatten() while len(std.shape) < len(score.shape): _SCREAMING_SNAKE_CASE : Tuple = std.unsqueeze(-1) _SCREAMING_SNAKE_CASE : int = -score / std # compute _SCREAMING_SNAKE_CASE : Optional[int] = -1.0 / len(self.timesteps) _SCREAMING_SNAKE_CASE : List[str] = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) _SCREAMING_SNAKE_CASE : int = beta_t.flatten() while len(beta_t.shape) < len(x.shape): _SCREAMING_SNAKE_CASE : Union[str, Any] = beta_t.unsqueeze(-1) _SCREAMING_SNAKE_CASE : List[Any] = -0.5 * beta_t * x _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.sqrt(_A) _SCREAMING_SNAKE_CASE : int = drift - diffusion**2 * score _SCREAMING_SNAKE_CASE : Any = x + drift * dt # add noise _SCREAMING_SNAKE_CASE : List[str] = randn_tensor(x.shape , layout=x.layout , generator=_A , device=x.device , dtype=x.dtype) _SCREAMING_SNAKE_CASE : Optional[Any] = x_mean + diffusion * math.sqrt(-dt) * noise return x, x_mean def __len__( self : int): """simple docstring""" return self.config.num_train_timesteps
635
"""simple docstring""" import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file _SCREAMING_SNAKE_CASE : Optional[int] = TapasConfig.from_json_file(__SCREAMING_SNAKE_CASE ) # set absolute/relative position embeddings parameter _SCREAMING_SNAKE_CASE : Dict = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": _SCREAMING_SNAKE_CASE : str = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "WTQ": # run_task_main.py hparams _SCREAMING_SNAKE_CASE : Optional[int] = 4 _SCREAMING_SNAKE_CASE : Any = True # hparam_utils.py hparams _SCREAMING_SNAKE_CASE : Any = 0.66_46_94 _SCREAMING_SNAKE_CASE : str = 0.20_79_51 _SCREAMING_SNAKE_CASE : str = 0.12_11_94 _SCREAMING_SNAKE_CASE : List[Any] = True _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = 0.0_35_25_13 _SCREAMING_SNAKE_CASE : Optional[Any] = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams _SCREAMING_SNAKE_CASE : int = 4 _SCREAMING_SNAKE_CASE : Tuple = False # hparam_utils.py hparams _SCREAMING_SNAKE_CASE : Any = 36.45_19 _SCREAMING_SNAKE_CASE : Union[str, Any] = 0.90_34_21 _SCREAMING_SNAKE_CASE : Optional[Any] = 2_22.0_88 _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Optional[int] = True _SCREAMING_SNAKE_CASE : Dict = 0.76_31_41 _SCREAMING_SNAKE_CASE : Union[str, Any] = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "TABFACT": _SCREAMING_SNAKE_CASE : int = TapasForSequenceClassification(config=__SCREAMING_SNAKE_CASE ) elif task == "MLM": _SCREAMING_SNAKE_CASE : int = TapasForMaskedLM(config=__SCREAMING_SNAKE_CASE ) elif task == "INTERMEDIATE_PRETRAINING": _SCREAMING_SNAKE_CASE : int = TapasModel(config=__SCREAMING_SNAKE_CASE ) else: raise ValueError(F"""Task {task} not supported.""" ) print(F"""Building PyTorch model from configuration: {config}""" ) # Load weights from tf checkpoint load_tf_weights_in_tapas(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Save pytorch-model (weights and configuration) print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) # Save tokenizer files print(F"""Save tokenizer files to {pytorch_dump_path}""" ) _SCREAMING_SNAKE_CASE : str = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + """vocab.txt""" , model_max_length=512 ) tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) print("""Used relative position embeddings:""" , model.config.reset_position_index_per_cell ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--task''', default='''SQA''', type=str, help='''Model task for which to convert a checkpoint. Defaults to SQA.''' ) parser.add_argument( '''--reset_position_index_per_cell''', default=False, action='''store_true''', help='''Whether to use relative position embeddings or not. Defaults to True.''', ) parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--tapas_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained TAPAS model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) lowerCAmelCase_ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
635
1
"""simple docstring""" def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise TypeError("""only integers accepted as input""" ) else: _SCREAMING_SNAKE_CASE : List[Any] = str(abs(__SCREAMING_SNAKE_CASE ) ) _SCREAMING_SNAKE_CASE : List[str] = [list(__SCREAMING_SNAKE_CASE ) for char in range(len(__SCREAMING_SNAKE_CASE ) )] for index in range(len(__SCREAMING_SNAKE_CASE ) ): num_transpositions[index].pop(__SCREAMING_SNAKE_CASE ) return max( int("""""".join(list(__SCREAMING_SNAKE_CASE ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('''doctest''').testmod()
635
"""simple docstring""" from typing import Any import numpy as np def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> bool: return np.array_equal(__SCREAMING_SNAKE_CASE , matrix.conjugate().T ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Any: _SCREAMING_SNAKE_CASE : Optional[int] = v.conjugate().T _SCREAMING_SNAKE_CASE : Optional[int] = v_star.dot(__SCREAMING_SNAKE_CASE ) assert isinstance(__SCREAMING_SNAKE_CASE , np.ndarray ) return (v_star_dot.dot(__SCREAMING_SNAKE_CASE )) / (v_star.dot(__SCREAMING_SNAKE_CASE )) def lowerCamelCase_()-> None: _SCREAMING_SNAKE_CASE : Optional[Any] = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) _SCREAMING_SNAKE_CASE : int = np.array([[1], [2], [3]] ) assert is_hermitian(__SCREAMING_SNAKE_CASE ), F"""{a} is not hermitian.""" print(rayleigh_quotient(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) _SCREAMING_SNAKE_CASE : int = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(__SCREAMING_SNAKE_CASE ), F"""{a} is not hermitian.""" assert rayleigh_quotient(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
635
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase_ = { '''configuration_tapas''': ['''TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TapasConfig'''], '''tokenization_tapas''': ['''TapasTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TapasForMaskedLM''', '''TapasForQuestionAnswering''', '''TapasForSequenceClassification''', '''TapasModel''', '''TapasPreTrainedModel''', '''load_tf_weights_in_tapas''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFTapasForMaskedLM''', '''TFTapasForQuestionAnswering''', '''TFTapasForSequenceClassification''', '''TFTapasModel''', '''TFTapasPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
"""simple docstring""" from __future__ import annotations def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , )-> tuple: if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError("""You cannot supply more or less than 2 values""" ) elif electron_conc < 0: raise ValueError("""Electron concentration cannot be negative in a semiconductor""" ) elif hole_conc < 0: raise ValueError("""Hole concentration cannot be negative in a semiconductor""" ) elif intrinsic_conc < 0: raise ValueError( """Intrinsic concentration cannot be negative in a semiconductor""" ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
635
1
"""simple docstring""" import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness lowerCAmelCase_ = '''\ @misc{chen2021evaluating, title={Evaluating Large Language Models Trained on Code}, author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \ and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \ and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \ and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \ and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \ and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \ and Mohammad Bavarian and Clemens Winter and Philippe Tillet \ and Felipe Petroski Such and Dave Cummings and Matthias Plappert \ and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \ and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \ and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \ and William Saunders and Christopher Hesse and Andrew N. Carr \ and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \ and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \ and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \ and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba}, year={2021}, eprint={2107.03374}, archivePrefix={arXiv}, primaryClass={cs.LG} } ''' lowerCAmelCase_ = '''\ This metric implements the evaluation harness for the HumanEval problem solving dataset described in the paper "Evaluating Large Language Models Trained on Code" (https://arxiv.org/abs/2107.03374). ''' lowerCAmelCase_ = ''' Calculates how good are predictions given some references, using certain scores Args: predictions: list of candidates to evaluate. Each candidates should be a list of strings with several code candidates to solve the problem. references: a list with a test for each prediction. Each test should evaluate the correctness of a code candidate. k: number of code candidates to consider in the evaluation (Default: [1, 10, 100]) num_workers: number of workers used to evaluate the canidate programs (Default: 4). timeout: Returns: pass_at_k: dict with pass rates for each k results: dict with granular results of each unittest Examples: >>> code_eval = datasets.load_metric("code_eval") >>> test_cases = ["assert add(2,3)==5"] >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]] >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2]) >>> print(pass_at_k) {\'pass@1\': 0.5, \'pass@2\': 1.0} ''' lowerCAmelCase_ = ''' ################################################################################ !!!WARNING!!! ################################################################################ The "code_eval" metric executes untrusted model-generated code in Python. Although it is highly unlikely that model-generated code will do something overtly malicious in response to this test suite, model-generated code may act destructively due to a lack of model capability or alignment. Users are strongly encouraged to sandbox this evaluation suite so that it does not perform destructive actions on their host or network. For more information on how OpenAI sandboxes its code, see the paper "Evaluating Large Language Models Trained on Code" (https://arxiv.org/abs/2107.03374). Once you have read this disclaimer and taken appropriate precautions, set the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this with: >>> import os >>> os.environ["HF_ALLOW_CODE_EVAL"] = "1" ################################################################################\ ''' lowerCAmelCase_ = '''The MIT License Copyright (c) OpenAI (https://openai.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""")), """references""": datasets.Value("""string"""), }) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def _lowerCAmelCase ( self : Optional[Any] , _A : Optional[int] , _A : List[Any] , _A : List[Any]=[1, 1_0, 1_0_0] , _A : Union[str, Any]=4 , _A : Optional[int]=3.0): """simple docstring""" if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0) != "1": raise ValueError(_WARNING) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""") with ThreadPoolExecutor(max_workers=_A) as executor: _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : Optional[Any] = Counter() _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 _SCREAMING_SNAKE_CASE : Tuple = defaultdict(_A) for task_id, (candidates, test_case) in enumerate(zip(_A , _A)): for candidate in candidates: _SCREAMING_SNAKE_CASE : List[str] = candidate + """\n""" + test_case _SCREAMING_SNAKE_CASE : Optional[int] = (test_program, timeout, task_id, completion_id[task_id]) _SCREAMING_SNAKE_CASE : List[str] = executor.submit(_A , *_A) futures.append(_A) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(_A): _SCREAMING_SNAKE_CASE : int = future.result() results[result["task_id"]].append((result["""completion_id"""], result)) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = [], [] for result in results.values(): result.sort() _SCREAMING_SNAKE_CASE : List[str] = [r[1]["""passed"""] for r in result] total.append(len(_A)) correct.append(sum(_A)) _SCREAMING_SNAKE_CASE : List[str] = np.array(_A) _SCREAMING_SNAKE_CASE : List[str] = np.array(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = k _SCREAMING_SNAKE_CASE : Optional[int] = {f"""pass@{k}""": estimate_pass_at_k(_A , _A , _A).mean() for k in ks if (total >= k).all()} return pass_at_k, results def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[str]: def estimator(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = itertools.repeat(__SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE ) ) else: assert len(__SCREAMING_SNAKE_CASE ) == len(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[Any] = iter(__SCREAMING_SNAKE_CASE ) return np.array([estimator(int(__SCREAMING_SNAKE_CASE ) , int(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) for n, c in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )] )
635
"""simple docstring""" import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCAmelCase_ = 16 lowerCAmelCase_ = 32 def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 16 )-> str: _SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetDict( { """train""": dataset["""train"""].select(__SCREAMING_SNAKE_CASE ), """validation""": dataset["""train"""].select(__SCREAMING_SNAKE_CASE ), """test""": dataset["""validation"""], } ) def tokenize_function(__SCREAMING_SNAKE_CASE ): # max_length=None => use the model max length (it's actually the default) _SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _SCREAMING_SNAKE_CASE : str = datasets.map( __SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _SCREAMING_SNAKE_CASE : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__SCREAMING_SNAKE_CASE ): # On TPU it's best to pad everything to the same length or training will be very slow. _SCREAMING_SNAKE_CASE : Any = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _SCREAMING_SNAKE_CASE : Optional[Any] = 16 elif accelerator.mixed_precision != "no": _SCREAMING_SNAKE_CASE : Any = 8 else: _SCREAMING_SNAKE_CASE : Optional[int] = None return tokenizer.pad( __SCREAMING_SNAKE_CASE , padding="""longest""" , max_length=__SCREAMING_SNAKE_CASE , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" , ) # Instantiate dataloaders. _SCREAMING_SNAKE_CASE : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__SCREAMING_SNAKE_CASE , collate_fn=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[int] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__SCREAMING_SNAKE_CASE , collate_fn=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = DataLoader( tokenized_datasets["""test"""] , shuffle=__SCREAMING_SNAKE_CASE , collate_fn=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE ) return train_dataloader, eval_dataloader, test_dataloader def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: # New Code # _SCREAMING_SNAKE_CASE : Union[str, Any] = [] # Download the dataset _SCREAMING_SNAKE_CASE : Union[str, Any] = load_dataset("""glue""" , """mrpc""" ) # Create our splits _SCREAMING_SNAKE_CASE : Dict = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator _SCREAMING_SNAKE_CASE : Any = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _SCREAMING_SNAKE_CASE : Tuple = config["""lr"""] _SCREAMING_SNAKE_CASE : Tuple = int(config["""num_epochs"""] ) _SCREAMING_SNAKE_CASE : int = int(config["""seed"""] ) _SCREAMING_SNAKE_CASE : int = int(config["""batch_size"""] ) _SCREAMING_SNAKE_CASE : List[str] = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation _SCREAMING_SNAKE_CASE : Any = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _SCREAMING_SNAKE_CASE : List[str] = batch_size // MAX_GPU_BATCH_SIZE _SCREAMING_SNAKE_CASE : List[str] = MAX_GPU_BATCH_SIZE set_seed(__SCREAMING_SNAKE_CASE ) # New Code # # Create our folds: _SCREAMING_SNAKE_CASE : List[str] = kfold.split(np.zeros(datasets["""train"""].num_rows ) , datasets["""train"""]["""label"""] ) _SCREAMING_SNAKE_CASE : Optional[Any] = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = get_fold_dataloaders( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _SCREAMING_SNAKE_CASE : Any = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__SCREAMING_SNAKE_CASE ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _SCREAMING_SNAKE_CASE : Tuple = model.to(accelerator.device ) # Instantiate optimizer _SCREAMING_SNAKE_CASE : int = AdamW(params=model.parameters() , lr=__SCREAMING_SNAKE_CASE ) # Instantiate scheduler _SCREAMING_SNAKE_CASE : int = get_linear_schedule_with_warmup( optimizer=__SCREAMING_SNAKE_CASE , num_warmup_steps=100 , num_training_steps=(len(__SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = accelerator.prepare( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Now we train the model for epoch in range(__SCREAMING_SNAKE_CASE ): model.train() for step, batch in enumerate(__SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _SCREAMING_SNAKE_CASE : Optional[Any] = model(**__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = outputs.loss _SCREAMING_SNAKE_CASE : List[Any] = loss / gradient_accumulation_steps accelerator.backward(__SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[str] = model(**__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : str = outputs.logits.argmax(dim=-1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__SCREAMING_SNAKE_CASE , references=__SCREAMING_SNAKE_CASE , ) _SCREAMING_SNAKE_CASE : Optional[int] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , __SCREAMING_SNAKE_CASE ) # New Code # # We also run predictions on the test set at the very end _SCREAMING_SNAKE_CASE : str = [] for step, batch in enumerate(__SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[str] = model(**__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[Any] = outputs.logits _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(__SCREAMING_SNAKE_CASE , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: _SCREAMING_SNAKE_CASE : Optional[int] = torch.cat(__SCREAMING_SNAKE_CASE , dim=0 ) _SCREAMING_SNAKE_CASE : List[str] = torch.stack(__SCREAMING_SNAKE_CASE , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) _SCREAMING_SNAKE_CASE : int = metric.compute(predictions=__SCREAMING_SNAKE_CASE , references=__SCREAMING_SNAKE_CASE ) accelerator.print("""Average test metrics from all folds:""" , __SCREAMING_SNAKE_CASE ) def lowerCamelCase_()-> Optional[Any]: _SCREAMING_SNAKE_CASE : Any = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) # New Code # parser.add_argument("""--num_folds""" , type=__SCREAMING_SNAKE_CASE , default=3 , help="""The number of splits to perform across the dataset""" ) _SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args() _SCREAMING_SNAKE_CASE : Optional[int] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
635
1
"""simple docstring""" import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params lowerCAmelCase_ = getLogger(__name__) lowerCAmelCase_ = '''cuda''' if torch.cuda.is_available() else '''cpu''' def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 8 , __SCREAMING_SNAKE_CASE = DEFAULT_DEVICE , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE="summarization" , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , )-> Dict: _SCREAMING_SNAKE_CASE : Tuple = Path(__SCREAMING_SNAKE_CASE ).open("""w""" , encoding="""utf-8""" ) _SCREAMING_SNAKE_CASE : Dict = str(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = AutoModelForSeqaSeqLM.from_pretrained(__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ) if fpaa: _SCREAMING_SNAKE_CASE : int = model.half() _SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) logger.info(F"""Inferred tokenizer type: {tokenizer.__class__}""" ) # if this is wrong, check config.model_type. _SCREAMING_SNAKE_CASE : Dict = time.time() # update config with task specific params use_task_specific_params(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if prefix is None: _SCREAMING_SNAKE_CASE : Optional[int] = prefix or getattr(model.config , """prefix""" , """""" ) or """""" for examples_chunk in tqdm(list(chunks(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) ): _SCREAMING_SNAKE_CASE : Tuple = [prefix + text for text in examples_chunk] _SCREAMING_SNAKE_CASE : Optional[int] = tokenizer(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" , truncation=__SCREAMING_SNAKE_CASE , padding="""longest""" ).to(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Any = model.generate( input_ids=batch.input_ids , attention_mask=batch.attention_mask , **__SCREAMING_SNAKE_CASE , ) _SCREAMING_SNAKE_CASE : int = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE ) for hypothesis in dec: fout.write(hypothesis + """\n""" ) fout.flush() fout.close() _SCREAMING_SNAKE_CASE : int = int(time.time() - start_time ) # seconds _SCREAMING_SNAKE_CASE : List[Any] = len(__SCREAMING_SNAKE_CASE ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs , 4 )} def lowerCamelCase_()-> List[Any]: return datetime.datetime.now().strftime("""%Y-%m-%d %H:%M:%S""" ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE=True )-> int: _SCREAMING_SNAKE_CASE : int = argparse.ArgumentParser() parser.add_argument("""model_name""" , type=__SCREAMING_SNAKE_CASE , help="""like facebook/bart-large-cnn,t5-base, etc.""" ) parser.add_argument("""input_path""" , type=__SCREAMING_SNAKE_CASE , help="""like cnn_dm/test.source""" ) parser.add_argument("""save_path""" , type=__SCREAMING_SNAKE_CASE , help="""where to save summaries""" ) parser.add_argument("""--reference_path""" , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""like cnn_dm/test.target""" ) parser.add_argument("""--score_path""" , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , default="""metrics.json""" , help="""where to save metrics""" ) parser.add_argument("""--device""" , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help="""cuda, cuda:1, cpu etc.""" ) parser.add_argument( """--prefix""" , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help="""will be added to the begininng of src examples""" ) parser.add_argument("""--task""" , type=__SCREAMING_SNAKE_CASE , default="""summarization""" , help="""used for task_specific_params + metrics""" ) parser.add_argument("""--bs""" , type=__SCREAMING_SNAKE_CASE , default=8 , required=__SCREAMING_SNAKE_CASE , help="""batch size""" ) parser.add_argument( """--n_obs""" , type=__SCREAMING_SNAKE_CASE , default=-1 , required=__SCREAMING_SNAKE_CASE , help="""How many observations. Defaults to all.""" ) parser.add_argument("""--fp16""" , action="""store_true""" ) parser.add_argument("""--dump-args""" , action="""store_true""" , help="""print the custom hparams with the results""" ) parser.add_argument( """--info""" , nargs="""?""" , type=__SCREAMING_SNAKE_CASE , const=datetime_now() , help=( """use in conjunction w/ --dump-args to print with the results whatever other info you'd like, e.g.""" """ lang=en-ru. If no value is passed, the current datetime string will be used.""" ) , ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = parser.parse_known_args() _SCREAMING_SNAKE_CASE : Dict = parse_numeric_n_bool_cl_kwargs(__SCREAMING_SNAKE_CASE ) if parsed_args and verbose: print(F"""parsed the following generate kwargs: {parsed_args}""" ) _SCREAMING_SNAKE_CASE : Any = [""" """ + x.rstrip() if """t5""" in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: _SCREAMING_SNAKE_CASE : List[str] = examples[: args.n_obs] Path(args.save_path ).parent.mkdir(exist_ok=__SCREAMING_SNAKE_CASE ) if args.reference_path is None and Path(args.score_path ).exists(): warnings.warn(F"""score_path {args.score_path} will be overwritten unless you type ctrl-c.""" ) if args.device == "cpu" and args.fpaa: # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half' raise ValueError("""Can't mix --fp16 and --device cpu""" ) _SCREAMING_SNAKE_CASE : List[str] = generate_summaries_or_translations( __SCREAMING_SNAKE_CASE , args.save_path , args.model_name , batch_size=args.bs , device=args.device , fpaa=args.fpaa , task=args.task , prefix=args.prefix , **__SCREAMING_SNAKE_CASE , ) if args.reference_path is None: return {} # Compute scores _SCREAMING_SNAKE_CASE : Optional[Any] = calculate_bleu if """translation""" in args.task else calculate_rouge _SCREAMING_SNAKE_CASE : str = [x.rstrip() for x in open(args.save_path ).readlines()] _SCREAMING_SNAKE_CASE : int = [x.rstrip() for x in open(args.reference_path ).readlines()][: len(__SCREAMING_SNAKE_CASE )] _SCREAMING_SNAKE_CASE : dict = score_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) scores.update(__SCREAMING_SNAKE_CASE ) if args.dump_args: scores.update(__SCREAMING_SNAKE_CASE ) if args.info: _SCREAMING_SNAKE_CASE : Any = args.info if verbose: print(__SCREAMING_SNAKE_CASE ) if args.score_path is not None: json.dump(__SCREAMING_SNAKE_CASE , open(args.score_path , """w""" ) ) return scores if __name__ == "__main__": # Usage for MT: # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json --task translation $@ run_generate(verbose=True)
635
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { '''configuration_clipseg''': [ '''CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPSegConfig''', '''CLIPSegTextConfig''', '''CLIPSegVisionConfig''', ], '''processing_clipseg''': ['''CLIPSegProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPSegModel''', '''CLIPSegPreTrainedModel''', '''CLIPSegTextModel''', '''CLIPSegVisionModel''', '''CLIPSegForImageSegmentation''', ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
1
"""simple docstring""" import gc import inspect import unittest import torch from parameterized import parameterized from diffusers import PriorTransformer from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin enable_full_determinism() class _snake_case ( __snake_case , unittest.TestCase ): """simple docstring""" a = PriorTransformer a = "hidden_states" @property def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = 4 _SCREAMING_SNAKE_CASE : Any = 8 _SCREAMING_SNAKE_CASE : Dict = 7 _SCREAMING_SNAKE_CASE : str = floats_tensor((batch_size, embedding_dim)).to(_A) _SCREAMING_SNAKE_CASE : Dict = floats_tensor((batch_size, embedding_dim)).to(_A) _SCREAMING_SNAKE_CASE : List[str] = floats_tensor((batch_size, num_embeddings, embedding_dim)).to(_A) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def _lowerCAmelCase ( self : str , _A : Optional[int]=0): """simple docstring""" torch.manual_seed(_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = 4 _SCREAMING_SNAKE_CASE : str = 8 _SCREAMING_SNAKE_CASE : Dict = 7 _SCREAMING_SNAKE_CASE : Any = torch.randn((batch_size, embedding_dim)).to(_A) _SCREAMING_SNAKE_CASE : List[str] = torch.randn((batch_size, embedding_dim)).to(_A) _SCREAMING_SNAKE_CASE : List[str] = torch.randn((batch_size, num_embeddings, embedding_dim)).to(_A) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } @property def _lowerCAmelCase ( self : Tuple): """simple docstring""" return (4, 8) @property def _lowerCAmelCase ( self : str): """simple docstring""" return (4, 8) def _lowerCAmelCase ( self : Union[str, Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : List[str] = { """num_attention_heads""": 2, """attention_head_dim""": 4, """num_layers""": 2, """embedding_dim""": 8, """num_embeddings""": 7, """additional_embeddings""": 4, } _SCREAMING_SNAKE_CASE : Tuple = self.dummy_input return init_dict, inputs_dict def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = PriorTransformer.from_pretrained( """hf-internal-testing/prior-dummy""" , output_loading_info=_A) self.assertIsNotNone(_A) self.assertEqual(len(loading_info["""missing_keys"""]) , 0) model.to(_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = model(**self.dummy_input)[0] assert hidden_states is not None, "Make sure output is not None" def _lowerCAmelCase ( self : Union[str, Any]): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self.prepare_init_args_and_inputs_for_common() _SCREAMING_SNAKE_CASE : Any = self.model_class(**_A) _SCREAMING_SNAKE_CASE : Tuple = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _SCREAMING_SNAKE_CASE : int = [*signature.parameters.keys()] _SCREAMING_SNAKE_CASE : Dict = ["""hidden_states""", """timestep"""] self.assertListEqual(arg_names[:2] , _A) def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = PriorTransformer.from_pretrained("""hf-internal-testing/prior-dummy""") _SCREAMING_SNAKE_CASE : str = model.to(_A) if hasattr(_A , """set_default_attn_processor"""): model.set_default_attn_processor() _SCREAMING_SNAKE_CASE : str = self.get_dummy_seed_input() with torch.no_grad(): _SCREAMING_SNAKE_CASE : str = model(**_A)[0] _SCREAMING_SNAKE_CASE : Tuple = output[0, :5].flatten().cpu() print(_A) # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. _SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([-1.3_436, -0.2_870, 0.7_538, 0.4_368, -0.0_239]) self.assertTrue(torch_all_close(_A , _A , rtol=1e-2)) @slow class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[str] , _A : Dict=1 , _A : List[str]=7_6_8 , _A : List[Any]=7_7 , _A : List[Any]=0): """simple docstring""" torch.manual_seed(_A) _SCREAMING_SNAKE_CASE : int = batch_size _SCREAMING_SNAKE_CASE : Optional[Any] = embedding_dim _SCREAMING_SNAKE_CASE : Optional[int] = num_embeddings _SCREAMING_SNAKE_CASE : int = torch.randn((batch_size, embedding_dim)).to(_A) _SCREAMING_SNAKE_CASE : int = torch.randn((batch_size, embedding_dim)).to(_A) _SCREAMING_SNAKE_CASE : List[Any] = torch.randn((batch_size, num_embeddings, embedding_dim)).to(_A) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @parameterized.expand( [ # fmt: off [1_3, [-0.5_861, 0.1_283, -0.0_931, 0.0_882, 0.4_476, 0.1_329, -0.0_498, 0.0_640]], [3_7, [-0.4_913, 0.0_110, -0.0_483, 0.0_541, 0.4_954, -0.0_170, 0.0_354, 0.1_651]], # fmt: on ]) def _lowerCAmelCase ( self : Any , _A : List[str] , _A : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = PriorTransformer.from_pretrained("""kandinsky-community/kandinsky-2-1-prior""" , subfolder="""prior""") model.to(_A) _SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_seed_input(seed=_A) with torch.no_grad(): _SCREAMING_SNAKE_CASE : int = model(**_A)[0] assert list(sample.shape) == [1, 7_6_8] _SCREAMING_SNAKE_CASE : Optional[int] = sample[0, :8].flatten().cpu() print(_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(_A) assert torch_all_close(_A , _A , atol=1e-3)
635
"""simple docstring""" import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class _snake_case : """simple docstring""" def __init__( self : int , _A : List[Any] , _A : int , _A : int): """simple docstring""" if dst_width < 0 or dst_height < 0: raise ValueError("""Destination width/height should be > 0""") _SCREAMING_SNAKE_CASE : str = img _SCREAMING_SNAKE_CASE : Optional[Any] = img.shape[1] _SCREAMING_SNAKE_CASE : Tuple = img.shape[0] _SCREAMING_SNAKE_CASE : Any = dst_width _SCREAMING_SNAKE_CASE : Any = dst_height _SCREAMING_SNAKE_CASE : Any = self.src_w / self.dst_w _SCREAMING_SNAKE_CASE : Dict = self.src_h / self.dst_h _SCREAMING_SNAKE_CASE : Optional[Any] = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta) * 2_5_5 ) def _lowerCAmelCase ( self : Tuple): """simple docstring""" for i in range(self.dst_h): for j in range(self.dst_w): _SCREAMING_SNAKE_CASE : Any = self.img[self.get_y(_A)][self.get_x(_A)] def _lowerCAmelCase ( self : int , _A : int): """simple docstring""" return int(self.ratio_x * x) def _lowerCAmelCase ( self : str , _A : int): """simple docstring""" return int(self.ratio_y * y) if __name__ == "__main__": lowerCAmelCase_ , lowerCAmelCase_ = 800, 600 lowerCAmelCase_ = imread('''image_data/lena.jpg''', 1) lowerCAmelCase_ = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}", n.output ) waitKey(0) destroyAllWindows()
635
1
"""simple docstring""" def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> bool: # 1. Validate that path exists between current and next vertices if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> bool: # Base Case if curr_ind == len(__SCREAMING_SNAKE_CASE ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(__SCREAMING_SNAKE_CASE ) ): if valid_connection(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # Insert current vertex into path as next transition _SCREAMING_SNAKE_CASE : Dict = next_ver # Validate created path if util_hamilton_cycle(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , curr_ind + 1 ): return True # Backtrack _SCREAMING_SNAKE_CASE : int = -1 return False def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0 )-> list[int]: _SCREAMING_SNAKE_CASE : Tuple = [-1] * (len(__SCREAMING_SNAKE_CASE ) + 1) # initialize start and end of path with starting index _SCREAMING_SNAKE_CASE : int = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , 1 ) else []
635
"""simple docstring""" import argparse from collections import defaultdict def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> int: _SCREAMING_SNAKE_CASE : str = F"""{file}_{class_name}_{test_name}""" done_test[_id] += 1 with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: _SCREAMING_SNAKE_CASE : Union[str, Any] = f.readlines() _SCREAMING_SNAKE_CASE : Optional[Any] = F"""class {class_name}(""" _SCREAMING_SNAKE_CASE : List[Any] = F"""{4 * " "}def {test_name}(""" _SCREAMING_SNAKE_CASE : Tuple = F"""{8 * " "}{correct_line.split()[0]}""" _SCREAMING_SNAKE_CASE : List[Any] = F"""{16 * " "}{correct_line.split()[0]}""" _SCREAMING_SNAKE_CASE : List[str] = False _SCREAMING_SNAKE_CASE : Tuple = False _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[int] = False _SCREAMING_SNAKE_CASE : Any = 0 _SCREAMING_SNAKE_CASE : Optional[Any] = 0 _SCREAMING_SNAKE_CASE : Dict = [] for line in lines: if line.startswith(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = True elif in_class and line.startswith(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = True elif in_class and in_func and (line.startswith(__SCREAMING_SNAKE_CASE ) or line.startswith(__SCREAMING_SNAKE_CASE )): _SCREAMING_SNAKE_CASE : Dict = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: _SCREAMING_SNAKE_CASE : int = True if in_class and in_func and in_line: if ")" not in line: continue else: _SCREAMING_SNAKE_CASE : Any = True if in_class and in_func and in_line and insert_line: new_lines.append(F"""{spaces * " "}{correct_line}""" ) _SCREAMING_SNAKE_CASE : Optional[int] = False else: new_lines.append(__SCREAMING_SNAKE_CASE ) with open(__SCREAMING_SNAKE_CASE , """w""" ) as f: for line in new_lines: f.write(__SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None )-> Optional[Any]: if fail is not None: with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: _SCREAMING_SNAKE_CASE : Union[str, Any] = {l.strip() for l in f.readlines()} else: _SCREAMING_SNAKE_CASE : str = None with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: _SCREAMING_SNAKE_CASE : str = f.readlines() _SCREAMING_SNAKE_CASE : str = defaultdict(__SCREAMING_SNAKE_CASE ) for line in correct_lines: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = line.split(""";""" ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument('''--correct_filename''', help='''filename of tests with expected result''') parser.add_argument('''--fail_filename''', help='''filename of test failures''', type=str, default=None) lowerCAmelCase_ = parser.parse_args() main(args.correct_filename, args.fail_filename)
635
1
"""simple docstring""" import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip lowerCAmelCase_ = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> List[str]: if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Any: return max(metric_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for gt in ground_truths ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[str]: _SCREAMING_SNAKE_CASE : List[str] = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Dict = [] if args.gold_data_mode == "qa": _SCREAMING_SNAKE_CASE : int = pd.read_csv(__SCREAMING_SNAKE_CASE , sep="""\t""" , header=__SCREAMING_SNAKE_CASE ) for answer_list in data[1]: _SCREAMING_SNAKE_CASE : Union[str, Any] = ast.literal_eval(__SCREAMING_SNAKE_CASE ) answers.append(__SCREAMING_SNAKE_CASE ) else: _SCREAMING_SNAKE_CASE : Optional[Any] = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Optional[int] = [[reference] for reference in references] _SCREAMING_SNAKE_CASE : Optional[int] = 0 for prediction, ground_truths in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): total += 1 em += metric_max_over_ground_truths(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) fa += metric_max_over_ground_truths(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = 1_00.0 * em / total _SCREAMING_SNAKE_CASE : Optional[Any] = 1_00.0 * fa / total logger.info(F"""F1: {fa:.2f}""" ) logger.info(F"""EM: {em:.2f}""" ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Tuple = args.k _SCREAMING_SNAKE_CASE : int = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Any = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Optional[Any] = 0 for hypo, reference in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = set(hypo.split("""\t""" )[:k] ) _SCREAMING_SNAKE_CASE : Union[str, Any] = set(reference.split("""\t""" ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k _SCREAMING_SNAKE_CASE : int = 1_00.0 * em / total logger.info(F"""Precision@{k}: {em: .2f}""" ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: def strip_title(__SCREAMING_SNAKE_CASE ): if title.startswith("""\"""" ): _SCREAMING_SNAKE_CASE : Optional[int] = title[1:] if title.endswith("""\"""" ): _SCREAMING_SNAKE_CASE : str = title[:-1] return title _SCREAMING_SNAKE_CASE : Dict = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( __SCREAMING_SNAKE_CASE , return_tensors="""pt""" , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , )["""input_ids"""].to(args.device ) _SCREAMING_SNAKE_CASE : List[str] = rag_model.rag.question_encoder(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Any = question_enc_outputs[0] _SCREAMING_SNAKE_CASE : List[Any] = rag_model.retriever( __SCREAMING_SNAKE_CASE , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors="""pt""" , ) _SCREAMING_SNAKE_CASE : Optional[int] = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [] for docs in all_docs: _SCREAMING_SNAKE_CASE : str = [strip_title(__SCREAMING_SNAKE_CASE ) for title in docs["""title"""]] provenance_strings.append("""\t""".join(__SCREAMING_SNAKE_CASE ) ) return provenance_strings def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[Any]: with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[Any] = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( __SCREAMING_SNAKE_CASE , return_tensors="""pt""" , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Union[str, Any] = inputs_dict.input_ids.to(args.device ) _SCREAMING_SNAKE_CASE : Union[str, Any] = inputs_dict.attention_mask.to(args.device ) _SCREAMING_SNAKE_CASE : Optional[Any] = rag_model.generate( # rag_model overwrites generate __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=__SCREAMING_SNAKE_CASE , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) _SCREAMING_SNAKE_CASE : Tuple = rag_model.retriever.generator_tokenizer.batch_decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) if args.print_predictions: for q, a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): logger.info("""Q: {} - A: {}""".format(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) return answers def lowerCamelCase_()-> List[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser() parser.add_argument( """--model_type""" , choices=["""rag_sequence""", """rag_token""", """bart"""] , type=__SCREAMING_SNAKE_CASE , help=( """RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the""" """ model_name_or_path""" ) , ) parser.add_argument( """--index_name""" , default=__SCREAMING_SNAKE_CASE , choices=["""exact""", """compressed""", """legacy"""] , type=__SCREAMING_SNAKE_CASE , help="""RAG model retriever type""" , ) parser.add_argument( """--index_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Path to the retrieval index""" , ) parser.add_argument("""--n_docs""" , default=5 , type=__SCREAMING_SNAKE_CASE , help="""Number of retrieved docs""" ) parser.add_argument( """--model_name_or_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to pretrained checkpoints or model identifier from huggingface.co/models""" , ) parser.add_argument( """--eval_mode""" , choices=["""e2e""", """retrieval"""] , default="""e2e""" , type=__SCREAMING_SNAKE_CASE , help=( """Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates""" """ precision@k.""" ) , ) parser.add_argument("""--k""" , default=1 , type=__SCREAMING_SNAKE_CASE , help="""k for the precision@k calculation""" ) parser.add_argument( """--evaluation_set""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to a file containing evaluation samples""" , ) parser.add_argument( """--gold_data_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to a tab-separated file with gold samples""" , ) parser.add_argument( """--gold_data_mode""" , default="""qa""" , type=__SCREAMING_SNAKE_CASE , choices=["""qa""", """ans"""] , help=( """Format of the gold data file""" """qa - a single line in the following format: question [tab] answer_list""" """ans - a single line of the gold file contains the expected answer string""" ) , ) parser.add_argument( """--predictions_path""" , type=__SCREAMING_SNAKE_CASE , default="""predictions.txt""" , help="""Name of the predictions file, to be stored in the checkpoints directory""" , ) parser.add_argument( """--eval_all_checkpoints""" , action="""store_true""" , help="""Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number""" , ) parser.add_argument( """--eval_batch_size""" , default=8 , type=__SCREAMING_SNAKE_CASE , help="""Batch size per GPU/CPU for evaluation.""" , ) parser.add_argument( """--recalculate""" , help="""Recalculate predictions even if the prediction file exists""" , action="""store_true""" , ) parser.add_argument( """--num_beams""" , default=4 , type=__SCREAMING_SNAKE_CASE , help="""Number of beams to be used when generating answers""" , ) parser.add_argument("""--min_length""" , default=1 , type=__SCREAMING_SNAKE_CASE , help="""Min length of the generated answers""" ) parser.add_argument("""--max_length""" , default=50 , type=__SCREAMING_SNAKE_CASE , help="""Max length of the generated answers""" ) parser.add_argument( """--print_predictions""" , action="""store_true""" , help="""If True, prints predictions while evaluating.""" , ) parser.add_argument( """--print_docs""" , action="""store_true""" , help="""If True, prints docs retried while generating.""" , ) _SCREAMING_SNAKE_CASE : Dict = parser.parse_args() _SCREAMING_SNAKE_CASE : Any = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) return args def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: _SCREAMING_SNAKE_CASE : Union[str, Any] = {} if args.model_type is None: _SCREAMING_SNAKE_CASE : Optional[int] = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith("""rag""" ): _SCREAMING_SNAKE_CASE : List[Any] = RagTokenForGeneration if args.model_type == """rag_token""" else RagSequenceForGeneration _SCREAMING_SNAKE_CASE : Optional[Any] = args.n_docs if args.index_name is not None: _SCREAMING_SNAKE_CASE : Optional[Any] = args.index_name if args.index_path is not None: _SCREAMING_SNAKE_CASE : Any = args.index_path else: _SCREAMING_SNAKE_CASE : Any = BartForConditionalGeneration _SCREAMING_SNAKE_CASE : int = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info("""Evaluate the following checkpoints: %s""" , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = get_scores if args.eval_mode == """e2e""" else get_precision_at_k _SCREAMING_SNAKE_CASE : Tuple = evaluate_batch_eae if args.eval_mode == """e2e""" else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info("""Calculating metrics based on an existing predictions file: {}""".format(args.predictions_path ) ) score_fn(__SCREAMING_SNAKE_CASE , args.predictions_path , args.gold_data_path ) continue logger.info("""***** Running evaluation for {} *****""".format(__SCREAMING_SNAKE_CASE ) ) logger.info(""" Batch size = %d""" , args.eval_batch_size ) logger.info(""" Predictions will be stored under {}""".format(args.predictions_path ) ) if args.model_type.startswith("""rag""" ): _SCREAMING_SNAKE_CASE : str = RagRetriever.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = model_class.from_pretrained(__SCREAMING_SNAKE_CASE , retriever=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) model.retriever.init_retrieval() else: _SCREAMING_SNAKE_CASE : str = model_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) model.to(args.device ) with open(args.evaluation_set , """r""" ) as eval_file, open(args.predictions_path , """w""" ) as preds_file: _SCREAMING_SNAKE_CASE : str = [] for line in tqdm(__SCREAMING_SNAKE_CASE ): questions.append(line.strip() ) if len(__SCREAMING_SNAKE_CASE ) == args.eval_batch_size: _SCREAMING_SNAKE_CASE : str = evaluate_batch_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) preds_file.write("""\n""".join(__SCREAMING_SNAKE_CASE ) + """\n""" ) preds_file.flush() _SCREAMING_SNAKE_CASE : Any = [] if len(__SCREAMING_SNAKE_CASE ) > 0: _SCREAMING_SNAKE_CASE : List[str] = evaluate_batch_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) preds_file.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) preds_file.flush() score_fn(__SCREAMING_SNAKE_CASE , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": lowerCAmelCase_ = get_args() main(args)
635
"""simple docstring""" import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel lowerCAmelCase_ = { '''text_branch''': '''text_model''', '''audio_branch''': '''audio_model.audio_encoder''', '''attn''': '''attention.self''', '''self.proj''': '''output.dense''', '''attention.self_mask''': '''attn_mask''', '''mlp.fc1''': '''intermediate.dense''', '''mlp.fc2''': '''output.dense''', '''norm1''': '''layernorm_before''', '''norm2''': '''layernorm_after''', '''bn0''': '''batch_norm''', } lowerCAmelCase_ = AutoFeatureExtractor.from_pretrained('''laion/clap-htsat-unfused''', truncation='''rand_trunc''') def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False )-> str: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = create_model( """HTSAT-tiny""" , """roberta""" , __SCREAMING_SNAKE_CASE , precision="""fp32""" , device="""cuda:0""" if torch.cuda.is_available() else """cpu""" , enable_fusion=__SCREAMING_SNAKE_CASE , fusion_type="""aff_2d""" if enable_fusion else None , ) return model, model_cfg def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = {} _SCREAMING_SNAKE_CASE : Optional[Any] = R""".*sequential.(\d+).*""" _SCREAMING_SNAKE_CASE : Any = R""".*_projection.(\d+).*""" for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: _SCREAMING_SNAKE_CASE : Optional[Any] = key.replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # replace sequential layers with list _SCREAMING_SNAKE_CASE : List[Any] = re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).group(1 ) _SCREAMING_SNAKE_CASE : Dict = key.replace(F"""sequential.{sequential_layer}.""" , F"""layers.{int(__SCREAMING_SNAKE_CASE )//3}.linear.""" ) elif re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = int(re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... _SCREAMING_SNAKE_CASE : Dict = 1 if projecton_layer == 0 else 2 _SCREAMING_SNAKE_CASE : Union[str, Any] = key.replace(F"""_projection.{projecton_layer}.""" , F"""_projection.linear{transformers_projection_layer}.""" ) if "audio" and "qkv" in key: # split qkv into query key and value _SCREAMING_SNAKE_CASE : Dict = value _SCREAMING_SNAKE_CASE : List[Any] = mixed_qkv.size(0 ) // 3 _SCREAMING_SNAKE_CASE : Optional[Any] = mixed_qkv[:qkv_dim] _SCREAMING_SNAKE_CASE : str = mixed_qkv[qkv_dim : qkv_dim * 2] _SCREAMING_SNAKE_CASE : Any = mixed_qkv[qkv_dim * 2 :] _SCREAMING_SNAKE_CASE : Dict = query_layer _SCREAMING_SNAKE_CASE : List[Any] = key_layer _SCREAMING_SNAKE_CASE : Dict = value_layer else: _SCREAMING_SNAKE_CASE : Optional[Any] = value return model_state_dict def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False )-> List[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = init_clap(__SCREAMING_SNAKE_CASE , enable_fusion=__SCREAMING_SNAKE_CASE ) clap_model.eval() _SCREAMING_SNAKE_CASE : Dict = clap_model.state_dict() _SCREAMING_SNAKE_CASE : Tuple = rename_state_dict(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : int = ClapConfig() _SCREAMING_SNAKE_CASE : Tuple = enable_fusion _SCREAMING_SNAKE_CASE : Dict = ClapModel(__SCREAMING_SNAKE_CASE ) # ignore the spectrogram embedding layer model.load_state_dict(__SCREAMING_SNAKE_CASE , strict=__SCREAMING_SNAKE_CASE ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) transformers_config.save_pretrained(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = 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('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument('''--enable_fusion''', action='''store_true''', help='''Whether to enable fusion or not''') lowerCAmelCase_ = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
635
1
"""simple docstring""" import argparse from collections import defaultdict def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> int: _SCREAMING_SNAKE_CASE : str = F"""{file}_{class_name}_{test_name}""" done_test[_id] += 1 with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: _SCREAMING_SNAKE_CASE : Union[str, Any] = f.readlines() _SCREAMING_SNAKE_CASE : Optional[Any] = F"""class {class_name}(""" _SCREAMING_SNAKE_CASE : List[Any] = F"""{4 * " "}def {test_name}(""" _SCREAMING_SNAKE_CASE : Tuple = F"""{8 * " "}{correct_line.split()[0]}""" _SCREAMING_SNAKE_CASE : List[Any] = F"""{16 * " "}{correct_line.split()[0]}""" _SCREAMING_SNAKE_CASE : List[str] = False _SCREAMING_SNAKE_CASE : Tuple = False _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[int] = False _SCREAMING_SNAKE_CASE : Any = 0 _SCREAMING_SNAKE_CASE : Optional[Any] = 0 _SCREAMING_SNAKE_CASE : Dict = [] for line in lines: if line.startswith(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = True elif in_class and line.startswith(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = True elif in_class and in_func and (line.startswith(__SCREAMING_SNAKE_CASE ) or line.startswith(__SCREAMING_SNAKE_CASE )): _SCREAMING_SNAKE_CASE : Dict = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: _SCREAMING_SNAKE_CASE : int = True if in_class and in_func and in_line: if ")" not in line: continue else: _SCREAMING_SNAKE_CASE : Any = True if in_class and in_func and in_line and insert_line: new_lines.append(F"""{spaces * " "}{correct_line}""" ) _SCREAMING_SNAKE_CASE : Optional[int] = False else: new_lines.append(__SCREAMING_SNAKE_CASE ) with open(__SCREAMING_SNAKE_CASE , """w""" ) as f: for line in new_lines: f.write(__SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None )-> Optional[Any]: if fail is not None: with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: _SCREAMING_SNAKE_CASE : Union[str, Any] = {l.strip() for l in f.readlines()} else: _SCREAMING_SNAKE_CASE : str = None with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: _SCREAMING_SNAKE_CASE : str = f.readlines() _SCREAMING_SNAKE_CASE : str = defaultdict(__SCREAMING_SNAKE_CASE ) for line in correct_lines: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = line.split(""";""" ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument('''--correct_filename''', help='''filename of tests with expected result''') parser.add_argument('''--fail_filename''', help='''filename of test failures''', type=str, default=None) lowerCAmelCase_ = parser.parse_args() main(args.correct_filename, args.fail_filename)
635
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import 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.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.g4dn.xlarge", "results": {"train_runtime": 6_50, "eval_accuracy": 0.6, "eval_loss": 0.9}, }, { "framework": "tensorflow", "script": "run_tf.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.g4dn.xlarge", "results": {"train_runtime": 6_00, "eval_accuracy": 0.3, "eval_loss": 0.9}, }, ] ) class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" 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=_A , ) assert hasattr(self , """env""") def _lowerCAmelCase ( self : Union[str, Any] , _A : str=1): """simple docstring""" 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}-single""" , instance_count=_A , instance_type=self.instance_type , debugger_hook_config=_A , hyperparameters={**self.env.hyperparameters, """model_name_or_path""": self.model_name_or_path} , metric_definitions=self.env.metric_definitions , py_version="""py36""" , ) def _lowerCAmelCase ( self : Union[str, Any] , _A : Union[str, Any]): """simple docstring""" TrainingJobAnalytics(_A).export_csv(f"""{self.env.test_path}/{job_name}_metrics.csv""") def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : str = self.create_estimator() # run training estimator.fit() # result dataframe _SCREAMING_SNAKE_CASE : Any = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis _SCREAMING_SNAKE_CASE : Any = list(result_metrics_df[result_metrics_df.metric_name == """eval_accuracy"""]["""value"""]) _SCREAMING_SNAKE_CASE : Tuple = list(result_metrics_df[result_metrics_df.metric_name == """eval_loss"""]["""value"""]) # get train time from SageMaker job, this includes starting, preprocessing, stopping _SCREAMING_SNAKE_CASE : int = ( 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} , _A)
635
1
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''Salesforce/blip-vqa-base''': '''https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json''', '''Salesforce/blip-vqa-capfit-large''': ( '''https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json''' ), '''Salesforce/blip-image-captioning-base''': ( '''https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json''' ), '''Salesforce/blip-image-captioning-large''': ( '''https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json''' ), '''Salesforce/blip-itm-base-coco''': '''https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json''', '''Salesforce/blip-itm-large-coco''': '''https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json''', '''Salesforce/blip-itm-base-flikr''': '''https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json''', '''Salesforce/blip-itm-large-flikr''': ( '''https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json''' ), } class _snake_case ( __snake_case ): """simple docstring""" a = "blip_text_model" def __init__( self : Any , _A : Optional[int]=3_0_5_2_4 , _A : str=7_6_8 , _A : List[Any]=7_6_8 , _A : Tuple=3_0_7_2 , _A : Optional[int]=7_6_8 , _A : Union[str, Any]=1_2 , _A : int=8 , _A : Optional[Any]=5_1_2 , _A : str="gelu" , _A : Any=1e-12 , _A : List[Any]=0.0 , _A : List[str]=0.0 , _A : Dict=0.02 , _A : Any=3_0_5_2_2 , _A : int=2 , _A : Union[str, Any]=0 , _A : str=1_0_2 , _A : Union[str, Any]=True , _A : Union[str, Any]=True , **_A : Optional[int] , ): """simple docstring""" super().__init__( pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , sep_token_id=_A , **_A , ) _SCREAMING_SNAKE_CASE : Dict = vocab_size _SCREAMING_SNAKE_CASE : Optional[int] = hidden_size _SCREAMING_SNAKE_CASE : List[str] = encoder_hidden_size _SCREAMING_SNAKE_CASE : Optional[int] = intermediate_size _SCREAMING_SNAKE_CASE : Any = projection_dim _SCREAMING_SNAKE_CASE : int = hidden_dropout_prob _SCREAMING_SNAKE_CASE : Dict = num_hidden_layers _SCREAMING_SNAKE_CASE : str = num_attention_heads _SCREAMING_SNAKE_CASE : Tuple = max_position_embeddings _SCREAMING_SNAKE_CASE : Tuple = layer_norm_eps _SCREAMING_SNAKE_CASE : int = hidden_act _SCREAMING_SNAKE_CASE : Tuple = initializer_range _SCREAMING_SNAKE_CASE : Any = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : Any = is_decoder _SCREAMING_SNAKE_CASE : List[str] = use_cache @classmethod def _lowerCAmelCase ( cls : Tuple , _A : Union[str, os.PathLike] , **_A : Optional[int]): """simple docstring""" cls._set_token_in_kwargs(_A) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = cls.get_config_dict(_A , **_A) # get the text config dict if we are loading from BlipConfig if config_dict.get("""model_type""") == "blip": _SCREAMING_SNAKE_CASE : Any = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""") and config_dict["model_type"] != cls.model_type: logger.warning( f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""") return cls.from_dict(_A , **_A) class _snake_case ( __snake_case ): """simple docstring""" a = "blip_vision_model" def __init__( self : int , _A : Dict=7_6_8 , _A : Any=3_0_7_2 , _A : Union[str, Any]=5_1_2 , _A : List[str]=1_2 , _A : List[str]=1_2 , _A : int=3_8_4 , _A : Optional[int]=1_6 , _A : Tuple="gelu" , _A : Dict=1e-5 , _A : Dict=0.0 , _A : Optional[Any]=1e-10 , **_A : Dict , ): """simple docstring""" super().__init__(**_A) _SCREAMING_SNAKE_CASE : Any = hidden_size _SCREAMING_SNAKE_CASE : Optional[int] = intermediate_size _SCREAMING_SNAKE_CASE : int = projection_dim _SCREAMING_SNAKE_CASE : List[str] = num_hidden_layers _SCREAMING_SNAKE_CASE : Tuple = num_attention_heads _SCREAMING_SNAKE_CASE : Optional[Any] = patch_size _SCREAMING_SNAKE_CASE : Optional[int] = image_size _SCREAMING_SNAKE_CASE : str = initializer_range _SCREAMING_SNAKE_CASE : Tuple = attention_dropout _SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps _SCREAMING_SNAKE_CASE : Tuple = hidden_act @classmethod def _lowerCAmelCase ( cls : Optional[int] , _A : Union[str, os.PathLike] , **_A : int): """simple docstring""" cls._set_token_in_kwargs(_A) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = cls.get_config_dict(_A , **_A) # get the vision config dict if we are loading from BlipConfig if config_dict.get("""model_type""") == "blip": _SCREAMING_SNAKE_CASE : str = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""") and config_dict["model_type"] != cls.model_type: logger.warning( f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""") return cls.from_dict(_A , **_A) class _snake_case ( __snake_case ): """simple docstring""" a = "blip" a = True def __init__( self : Optional[Any] , _A : Any=None , _A : List[Any]=None , _A : Any=5_1_2 , _A : str=2.6_592 , _A : Union[str, Any]=2_5_6 , **_A : int , ): """simple docstring""" super().__init__(**_A) if text_config is None: _SCREAMING_SNAKE_CASE : Tuple = {} logger.info("""`text_config` is `None`. Initializing the `BlipTextConfig` with default values.""") if vision_config is None: _SCREAMING_SNAKE_CASE : Optional[Any] = {} logger.info("""`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.""") _SCREAMING_SNAKE_CASE : str = BlipTextConfig(**_A) _SCREAMING_SNAKE_CASE : Optional[Any] = BlipVisionConfig(**_A) _SCREAMING_SNAKE_CASE : int = self.vision_config.hidden_size _SCREAMING_SNAKE_CASE : Tuple = projection_dim _SCREAMING_SNAKE_CASE : Dict = logit_scale_init_value _SCREAMING_SNAKE_CASE : List[str] = 1.0 _SCREAMING_SNAKE_CASE : str = 0.02 _SCREAMING_SNAKE_CASE : Union[str, Any] = image_text_hidden_size @classmethod def _lowerCAmelCase ( cls : Optional[Any] , _A : BlipTextConfig , _A : BlipVisionConfig , **_A : int): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_A) def _lowerCAmelCase ( self : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = copy.deepcopy(self.__dict__) _SCREAMING_SNAKE_CASE : List[str] = self.text_config.to_dict() _SCREAMING_SNAKE_CASE : Dict = self.vision_config.to_dict() _SCREAMING_SNAKE_CASE : int = self.__class__.model_type return output
635
"""simple docstring""" import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip lowerCAmelCase_ = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> List[str]: if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Any: return max(metric_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for gt in ground_truths ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[str]: _SCREAMING_SNAKE_CASE : List[str] = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Dict = [] if args.gold_data_mode == "qa": _SCREAMING_SNAKE_CASE : int = pd.read_csv(__SCREAMING_SNAKE_CASE , sep="""\t""" , header=__SCREAMING_SNAKE_CASE ) for answer_list in data[1]: _SCREAMING_SNAKE_CASE : Union[str, Any] = ast.literal_eval(__SCREAMING_SNAKE_CASE ) answers.append(__SCREAMING_SNAKE_CASE ) else: _SCREAMING_SNAKE_CASE : Optional[Any] = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Optional[int] = [[reference] for reference in references] _SCREAMING_SNAKE_CASE : Optional[int] = 0 for prediction, ground_truths in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): total += 1 em += metric_max_over_ground_truths(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) fa += metric_max_over_ground_truths(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = 1_00.0 * em / total _SCREAMING_SNAKE_CASE : Optional[Any] = 1_00.0 * fa / total logger.info(F"""F1: {fa:.2f}""" ) logger.info(F"""EM: {em:.2f}""" ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Tuple = args.k _SCREAMING_SNAKE_CASE : int = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Any = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Optional[Any] = 0 for hypo, reference in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = set(hypo.split("""\t""" )[:k] ) _SCREAMING_SNAKE_CASE : Union[str, Any] = set(reference.split("""\t""" ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k _SCREAMING_SNAKE_CASE : int = 1_00.0 * em / total logger.info(F"""Precision@{k}: {em: .2f}""" ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: def strip_title(__SCREAMING_SNAKE_CASE ): if title.startswith("""\"""" ): _SCREAMING_SNAKE_CASE : Optional[int] = title[1:] if title.endswith("""\"""" ): _SCREAMING_SNAKE_CASE : str = title[:-1] return title _SCREAMING_SNAKE_CASE : Dict = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( __SCREAMING_SNAKE_CASE , return_tensors="""pt""" , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , )["""input_ids"""].to(args.device ) _SCREAMING_SNAKE_CASE : List[str] = rag_model.rag.question_encoder(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Any = question_enc_outputs[0] _SCREAMING_SNAKE_CASE : List[Any] = rag_model.retriever( __SCREAMING_SNAKE_CASE , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors="""pt""" , ) _SCREAMING_SNAKE_CASE : Optional[int] = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [] for docs in all_docs: _SCREAMING_SNAKE_CASE : str = [strip_title(__SCREAMING_SNAKE_CASE ) for title in docs["""title"""]] provenance_strings.append("""\t""".join(__SCREAMING_SNAKE_CASE ) ) return provenance_strings def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[Any]: with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[Any] = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( __SCREAMING_SNAKE_CASE , return_tensors="""pt""" , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Union[str, Any] = inputs_dict.input_ids.to(args.device ) _SCREAMING_SNAKE_CASE : Union[str, Any] = inputs_dict.attention_mask.to(args.device ) _SCREAMING_SNAKE_CASE : Optional[Any] = rag_model.generate( # rag_model overwrites generate __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=__SCREAMING_SNAKE_CASE , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) _SCREAMING_SNAKE_CASE : Tuple = rag_model.retriever.generator_tokenizer.batch_decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) if args.print_predictions: for q, a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): logger.info("""Q: {} - A: {}""".format(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) return answers def lowerCamelCase_()-> List[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser() parser.add_argument( """--model_type""" , choices=["""rag_sequence""", """rag_token""", """bart"""] , type=__SCREAMING_SNAKE_CASE , help=( """RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the""" """ model_name_or_path""" ) , ) parser.add_argument( """--index_name""" , default=__SCREAMING_SNAKE_CASE , choices=["""exact""", """compressed""", """legacy"""] , type=__SCREAMING_SNAKE_CASE , help="""RAG model retriever type""" , ) parser.add_argument( """--index_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Path to the retrieval index""" , ) parser.add_argument("""--n_docs""" , default=5 , type=__SCREAMING_SNAKE_CASE , help="""Number of retrieved docs""" ) parser.add_argument( """--model_name_or_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to pretrained checkpoints or model identifier from huggingface.co/models""" , ) parser.add_argument( """--eval_mode""" , choices=["""e2e""", """retrieval"""] , default="""e2e""" , type=__SCREAMING_SNAKE_CASE , help=( """Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates""" """ precision@k.""" ) , ) parser.add_argument("""--k""" , default=1 , type=__SCREAMING_SNAKE_CASE , help="""k for the precision@k calculation""" ) parser.add_argument( """--evaluation_set""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to a file containing evaluation samples""" , ) parser.add_argument( """--gold_data_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to a tab-separated file with gold samples""" , ) parser.add_argument( """--gold_data_mode""" , default="""qa""" , type=__SCREAMING_SNAKE_CASE , choices=["""qa""", """ans"""] , help=( """Format of the gold data file""" """qa - a single line in the following format: question [tab] answer_list""" """ans - a single line of the gold file contains the expected answer string""" ) , ) parser.add_argument( """--predictions_path""" , type=__SCREAMING_SNAKE_CASE , default="""predictions.txt""" , help="""Name of the predictions file, to be stored in the checkpoints directory""" , ) parser.add_argument( """--eval_all_checkpoints""" , action="""store_true""" , help="""Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number""" , ) parser.add_argument( """--eval_batch_size""" , default=8 , type=__SCREAMING_SNAKE_CASE , help="""Batch size per GPU/CPU for evaluation.""" , ) parser.add_argument( """--recalculate""" , help="""Recalculate predictions even if the prediction file exists""" , action="""store_true""" , ) parser.add_argument( """--num_beams""" , default=4 , type=__SCREAMING_SNAKE_CASE , help="""Number of beams to be used when generating answers""" , ) parser.add_argument("""--min_length""" , default=1 , type=__SCREAMING_SNAKE_CASE , help="""Min length of the generated answers""" ) parser.add_argument("""--max_length""" , default=50 , type=__SCREAMING_SNAKE_CASE , help="""Max length of the generated answers""" ) parser.add_argument( """--print_predictions""" , action="""store_true""" , help="""If True, prints predictions while evaluating.""" , ) parser.add_argument( """--print_docs""" , action="""store_true""" , help="""If True, prints docs retried while generating.""" , ) _SCREAMING_SNAKE_CASE : Dict = parser.parse_args() _SCREAMING_SNAKE_CASE : Any = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) return args def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: _SCREAMING_SNAKE_CASE : Union[str, Any] = {} if args.model_type is None: _SCREAMING_SNAKE_CASE : Optional[int] = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith("""rag""" ): _SCREAMING_SNAKE_CASE : List[Any] = RagTokenForGeneration if args.model_type == """rag_token""" else RagSequenceForGeneration _SCREAMING_SNAKE_CASE : Optional[Any] = args.n_docs if args.index_name is not None: _SCREAMING_SNAKE_CASE : Optional[Any] = args.index_name if args.index_path is not None: _SCREAMING_SNAKE_CASE : Any = args.index_path else: _SCREAMING_SNAKE_CASE : Any = BartForConditionalGeneration _SCREAMING_SNAKE_CASE : int = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info("""Evaluate the following checkpoints: %s""" , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = get_scores if args.eval_mode == """e2e""" else get_precision_at_k _SCREAMING_SNAKE_CASE : Tuple = evaluate_batch_eae if args.eval_mode == """e2e""" else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info("""Calculating metrics based on an existing predictions file: {}""".format(args.predictions_path ) ) score_fn(__SCREAMING_SNAKE_CASE , args.predictions_path , args.gold_data_path ) continue logger.info("""***** Running evaluation for {} *****""".format(__SCREAMING_SNAKE_CASE ) ) logger.info(""" Batch size = %d""" , args.eval_batch_size ) logger.info(""" Predictions will be stored under {}""".format(args.predictions_path ) ) if args.model_type.startswith("""rag""" ): _SCREAMING_SNAKE_CASE : str = RagRetriever.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = model_class.from_pretrained(__SCREAMING_SNAKE_CASE , retriever=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) model.retriever.init_retrieval() else: _SCREAMING_SNAKE_CASE : str = model_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) model.to(args.device ) with open(args.evaluation_set , """r""" ) as eval_file, open(args.predictions_path , """w""" ) as preds_file: _SCREAMING_SNAKE_CASE : str = [] for line in tqdm(__SCREAMING_SNAKE_CASE ): questions.append(line.strip() ) if len(__SCREAMING_SNAKE_CASE ) == args.eval_batch_size: _SCREAMING_SNAKE_CASE : str = evaluate_batch_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) preds_file.write("""\n""".join(__SCREAMING_SNAKE_CASE ) + """\n""" ) preds_file.flush() _SCREAMING_SNAKE_CASE : Any = [] if len(__SCREAMING_SNAKE_CASE ) > 0: _SCREAMING_SNAKE_CASE : List[str] = evaluate_batch_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) preds_file.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) preds_file.flush() score_fn(__SCREAMING_SNAKE_CASE , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": lowerCAmelCase_ = get_args() main(args)
635
1
"""simple docstring""" import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument('''--user''', type=str, default='''ubuntu''') parser.add_argument('''--host''', type=str, default='''localhost''') parser.add_argument('''--key_path''', type=str, default=None) parser.add_argument('''--instance''', type=str, default='''V100:1''') parser.add_argument('''--provider''', type=str, default='''cheapest''') parser.add_argument('''--use_spot''', type=bool, default=False) parser.add_argument('''--example''', type=str, default='''pytorch/text-generation/run_generation.py''') lowerCAmelCase_ , lowerCAmelCase_ = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError('''Cannot specify both BYO and on-demand cluster args''') lowerCAmelCase_ = rh.cluster( name='''rh-cluster''', ips=[args.host], ssh_creds={'''ssh_user''': args.user, '''ssh_private_key''': args.key_path} ) else: lowerCAmelCase_ = rh.cluster( name='''rh-cluster''', instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) lowerCAmelCase_ = args.example.rsplit('''/''', 1)[0] # Set up remote environment cluster.install_packages(['''pip:./''']) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([F"pip install -r transformers/examples/{example_dir}/requirements.txt"]) cluster.run(['''pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117''']) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([F"python transformers/examples/{args.example} {' '.join(shlex.quote(arg) for arg in unknown)}"]) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
635
"""simple docstring""" import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def lowerCamelCase_(__SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=10 , __SCREAMING_SNAKE_CASE=100 , __SCREAMING_SNAKE_CASE=1_026 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE="data/tokenized_stories_train_wikitext103.jbl" , __SCREAMING_SNAKE_CASE="igf_context_pairs.jbl" , )-> Union[str, Any]: set_seed(3 ) # generate train_data and objective_set _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = generate_datasets( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , number=__SCREAMING_SNAKE_CASE , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? _SCREAMING_SNAKE_CASE : Dict = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) # load pretrained model _SCREAMING_SNAKE_CASE : Any = load_gpta("""gpt2""" ).to(__SCREAMING_SNAKE_CASE ) print("""computing perplexity on objective set""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).item() print("""perplexity on objective set:""" , __SCREAMING_SNAKE_CASE ) # collect igf pairs and save to file demo.jbl collect_objective_set(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=15 , __SCREAMING_SNAKE_CASE=128 , __SCREAMING_SNAKE_CASE=100 , __SCREAMING_SNAKE_CASE="igf_model.pt" , )-> Optional[int]: set_seed(42 ) # Load pre-trained model _SCREAMING_SNAKE_CASE : Any = GPTaLMHeadModel.from_pretrained("""gpt2""" ) # Initialize secondary learner to use embedding weights of model _SCREAMING_SNAKE_CASE : Union[str, Any] = SecondaryLearner(__SCREAMING_SNAKE_CASE ) # Train secondary learner _SCREAMING_SNAKE_CASE : Any = train_secondary_learner( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , max_epochs=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , eval_freq=100 , igf_model_path=__SCREAMING_SNAKE_CASE , ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_000 , __SCREAMING_SNAKE_CASE=16 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=recopy_gpta , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=10 , __SCREAMING_SNAKE_CASE="gpt2_finetuned.pt" , )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Tuple = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = RandomSampler(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = DataLoader(__SCREAMING_SNAKE_CASE , sampler=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = max_steps // (len(__SCREAMING_SNAKE_CASE )) + 1 _SCREAMING_SNAKE_CASE : List[Any] = 0 _SCREAMING_SNAKE_CASE : Any = torch.zeros((1, context_len) , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = recopy_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) model.train() if secondary_learner is not None: secondary_learner.to(__SCREAMING_SNAKE_CASE ) secondary_learner.eval() _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : Optional[int] = 0 _SCREAMING_SNAKE_CASE : Optional[Any] = [] _SCREAMING_SNAKE_CASE : int = [] # Compute the performance of the transformer model at the beginning _SCREAMING_SNAKE_CASE : Tuple = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) test_perps.append(__SCREAMING_SNAKE_CASE ) print("""Test perplexity, step""" , __SCREAMING_SNAKE_CASE , """:""" , __SCREAMING_SNAKE_CASE ) for epoch in range(int(__SCREAMING_SNAKE_CASE ) ): for step, example in enumerate(__SCREAMING_SNAKE_CASE ): torch.cuda.empty_cache() _SCREAMING_SNAKE_CASE : Any = random.randint(0 , example.size(2 ) - context_len - 1 ) _SCREAMING_SNAKE_CASE : int = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() _SCREAMING_SNAKE_CASE : Union[str, Any] = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[str] = True if secondary_learner is not None: _SCREAMING_SNAKE_CASE : List[Any] = secondary_learner.forward( torch.tensor(__SCREAMING_SNAKE_CASE , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ).unsqueeze(0 ) )[0].item() observed_qs.append(float(__SCREAMING_SNAKE_CASE ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: _SCREAMING_SNAKE_CASE : Dict = -1 if predicted_q < threshold: _SCREAMING_SNAKE_CASE : List[str] = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() _SCREAMING_SNAKE_CASE : Any = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: _SCREAMING_SNAKE_CASE : Tuple = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) test_perps.append(__SCREAMING_SNAKE_CASE ) print("""Test perplexity, step""" , __SCREAMING_SNAKE_CASE , """:""" , __SCREAMING_SNAKE_CASE ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() , __SCREAMING_SNAKE_CASE ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def lowerCamelCase_()-> Tuple: _SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser(description="""Fine-tune a transformer model with IGF on a language modeling task""" ) # Required parameters parser.add_argument( """--data_dir""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The input data dir. Should contain data files for WikiText.""" , ) parser.add_argument( """--model_name_or_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to pretrained model or model identifier from huggingface.co/models""" , ) parser.add_argument( """--data_file""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help=( """A jbl file containing tokenized data which can be split as objective dataset, """ """train_dataset and test_dataset.""" ) , ) parser.add_argument( """--igf_data_file""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help="""A jbl file containing the context and information gain pairs to train secondary learner.""" , ) parser.add_argument( """--output_dir""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The output directory where the final fine-tuned model is stored.""" , ) parser.add_argument( """--tokenizer_name""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Pretrained tokenizer name or path if not the same as model_name""" , ) parser.add_argument("""--seed""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help="""A seed for reproducible training.""" ) parser.add_argument( """--context_len""" , default=32 , type=__SCREAMING_SNAKE_CASE , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--size_objective_set""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""number of articles that are long enough to be used as our objective set""" , ) parser.add_argument( """--eval_freq""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""secondary model evaluation is triggered at eval_freq""" ) parser.add_argument("""--max_steps""" , default=1_000 , type=__SCREAMING_SNAKE_CASE , help="""To calculate training epochs""" ) parser.add_argument( """--secondary_learner_batch_size""" , default=128 , type=__SCREAMING_SNAKE_CASE , help="""batch size of training data for secondary learner""" , ) parser.add_argument( """--batch_size""" , default=16 , type=__SCREAMING_SNAKE_CASE , help="""batch size of training data of language model(gpt2) """ ) parser.add_argument( """--eval_interval""" , default=10 , type=__SCREAMING_SNAKE_CASE , help=( """decay the selectivity of our secondary learner filter from""" """1 standard deviation above average to 1 below average after 10 batches""" ) , ) parser.add_argument( """--number""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""The number of examples split to be used as objective_set/test_data""" ) parser.add_argument( """--min_len""" , default=1_026 , type=__SCREAMING_SNAKE_CASE , help="""The minimum length of the article to be used as objective set""" ) parser.add_argument( """--secondary_learner_max_epochs""" , default=15 , type=__SCREAMING_SNAKE_CASE , help="""number of epochs to train secondary learner""" ) parser.add_argument("""--trim""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""truncate the example if it exceeds context length""" ) parser.add_argument( """--threshold""" , default=1.0 , type=__SCREAMING_SNAKE_CASE , help=( """The threshold value used by secondary learner to filter the train_data and allow only""" """ informative data as input to the model""" ) , ) parser.add_argument("""--finetuned_model_name""" , default="""gpt2_finetuned.pt""" , type=__SCREAMING_SNAKE_CASE , help="""finetuned_model_name""" ) parser.add_argument( """--recopy_model""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Reset the model to the original pretrained GPT-2 weights after each iteration""" , ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 , max_steps=10 , size_objective_set=100 , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE , data_file="""data/tokenized_stories_train_wikitext103.jbl""" , igf_data_file="""igf_context_pairs.jbl""" , ) # Load train data for secondary learner _SCREAMING_SNAKE_CASE : Optional[int] = joblib.load("""data/IGF_values.jbl""" ) # Train secondary learner _SCREAMING_SNAKE_CASE : int = training_secondary_learner( __SCREAMING_SNAKE_CASE , secondary_learner_max_epochs=15 , secondary_learner_batch_size=128 , eval_freq=100 , igf_model_path="""igf_model.pt""" , ) # load pretrained gpt2 model _SCREAMING_SNAKE_CASE : List[Any] = GPTaLMHeadModel.from_pretrained("""gpt2""" ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = generate_datasets( context_len=32 , file="""data/tokenized_stories_train_wikitext103.jbl""" , number=100 , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , context_len=32 , max_steps=1_000 , batch_size=16 , threshold=1.0 , recopy_model=__SCREAMING_SNAKE_CASE , secondary_learner=__SCREAMING_SNAKE_CASE , eval_interval=10 , finetuned_model_name="""gpt2_finetuned.pt""" , ) if __name__ == "__main__": main()
635
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase_ = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _snake_case ( __snake_case ): """simple docstring""" a = ["image_processor", "tokenizer"] a = "ChineseCLIPImageProcessor" a = ("BertTokenizer", "BertTokenizerFast") def __init__( self : Dict , _A : Tuple=None , _A : List[Any]=None , **_A : int): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , _A , ) _SCREAMING_SNAKE_CASE : str = kwargs.pop("""feature_extractor""") _SCREAMING_SNAKE_CASE : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""") if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""") super().__init__(_A , _A) _SCREAMING_SNAKE_CASE : Dict = self.image_processor def __call__( self : Optional[int] , _A : Optional[Any]=None , _A : Any=None , _A : Tuple=None , **_A : int): """simple docstring""" if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""") if text is not None: _SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer(_A , return_tensors=_A , **_A) if images is not None: _SCREAMING_SNAKE_CASE : List[Any] = self.image_processor(_A , return_tensors=_A , **_A) if text is not None and images is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_A) , tensor_type=_A) def _lowerCAmelCase ( self : str , *_A : Any , **_A : Any): """simple docstring""" return self.tokenizer.batch_decode(*_A , **_A) def _lowerCAmelCase ( self : Union[str, Any] , *_A : List[Any] , **_A : Any): """simple docstring""" return self.tokenizer.decode(*_A , **_A) @property def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.model_input_names _SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def _lowerCAmelCase ( self : List[str]): """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , _A , ) return self.image_processor_class
635
1
"""simple docstring""" import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets lowerCAmelCase_ = '''\ @inproceedings{popovic-2015-chrf, title = "chr{F}: character n-gram {F}-score for automatic {MT} evaluation", author = "Popovi{\'c}, Maja", booktitle = "Proceedings of the Tenth Workshop on Statistical Machine Translation", month = sep, year = "2015", address = "Lisbon, Portugal", publisher = "Association for Computational Linguistics", url = "https://aclanthology.org/W15-3049", doi = "10.18653/v1/W15-3049", pages = "392--395", } @inproceedings{popovic-2017-chrf, title = "chr{F}++: words helping character n-grams", author = "Popovi{\'c}, Maja", booktitle = "Proceedings of the Second Conference on Machine Translation", month = sep, year = "2017", address = "Copenhagen, Denmark", publisher = "Association for Computational Linguistics", url = "https://aclanthology.org/W17-4770", doi = "10.18653/v1/W17-4770", pages = "612--618", } @inproceedings{post-2018-call, title = "A Call for Clarity in Reporting {BLEU} Scores", author = "Post, Matt", booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", month = oct, year = "2018", address = "Belgium, Brussels", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W18-6319", pages = "186--191", } ''' lowerCAmelCase_ = '''\ ChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches, and ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation that is already present in sacrebleu. The implementation here is slightly different from sacrebleu in terms of the required input format. The length of the references and hypotheses lists need to be the same, so you may need to transpose your references compared to sacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534 See the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information. ''' lowerCAmelCase_ = ''' Produces ChrF(++) scores for hypotheses given reference translations. Args: predictions (list of str): The predicted sentences. references (list of list of str): The references. There should be one reference sub-list for each prediction sentence. char_order (int): Character n-gram order. Defaults to `6`. word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`. beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`. lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`. whitespace (bool): If `True`, include whitespaces when extracting character n-grams. eps_smoothing (bool): If `True`, applies epsilon smoothing similar to reference chrF++.py, NLTK and Moses implementations. If `False`, it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`. Returns: \'score\' (float): The chrF (chrF++) score, \'char_order\' (int): The character n-gram order, \'word_order\' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++, \'beta\' (int): Determine the importance of recall w.r.t precision Examples: Example 1--a simple example of calculating chrF: >>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."] >>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]] >>> chrf = datasets.load_metric("chrf") >>> results = chrf.compute(predictions=prediction, references=reference) >>> print(results) {\'score\': 84.64214891738334, \'char_order\': 6, \'word_order\': 0, \'beta\': 2} Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF: >>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."] >>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]] >>> chrf = datasets.load_metric("chrf") >>> results = chrf.compute(predictions=prediction, ... references=reference, ... word_order=2) >>> print(results) {\'score\': 82.87263732906315, \'char_order\': 6, \'word_order\': 2, \'beta\': 2} Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case: >>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."] >>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]] >>> chrf = datasets.load_metric("chrf") >>> results = chrf.compute(predictions=prediction, ... references=reference, ... word_order=2, ... lowercase=True) >>> print(results) {\'score\': 92.12853119829202, \'char_order\': 6, \'word_order\': 2, \'beta\': 2} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : List[Any]): """simple docstring""" if version.parse(scb.__version__) < version.parse("""1.4.12"""): raise ImportWarning( """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n""" """You can install it with `pip install \"sacrebleu>=1.4.12\"`.""") return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://github.com/mjpost/sacreBLEU#chrf--chrf""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence"""), """references""": datasets.Sequence(datasets.Value("""string""" , id="""sequence""") , id="""references"""), }) , codebase_urls=["""https://github.com/mjpost/sacreBLEU#chrf--chrf"""] , reference_urls=[ """https://github.com/m-popovic/chrF""", ] , ) def _lowerCAmelCase ( self : List[str] , _A : str , _A : List[str] , _A : int = CHRF.CHAR_ORDER , _A : int = CHRF.WORD_ORDER , _A : int = CHRF.BETA , _A : bool = False , _A : bool = False , _A : bool = False , ): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = len(references[0]) if any(len(_A) != references_per_prediction for refs in references): raise ValueError("""Sacrebleu requires the same number of references for each prediction""") _SCREAMING_SNAKE_CASE : Any = [[refs[i] for refs in references] for i in range(_A)] _SCREAMING_SNAKE_CASE : Union[str, Any] = CHRF(_A , _A , _A , _A , _A , _A) _SCREAMING_SNAKE_CASE : List[Any] = sb_chrf.corpus_score(_A , _A) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
635
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = ['''model.decoder.embed_positions.weights'''] def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[int]: if "emb" in name: _SCREAMING_SNAKE_CASE : List[Any] = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: _SCREAMING_SNAKE_CASE : List[str] = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: _SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: _SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: _SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: _SCREAMING_SNAKE_CASE : int = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: _SCREAMING_SNAKE_CASE : Dict = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: _SCREAMING_SNAKE_CASE : Dict = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: _SCREAMING_SNAKE_CASE : Tuple = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: _SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: _SCREAMING_SNAKE_CASE : str = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple[Dict, Dict]: _SCREAMING_SNAKE_CASE : str = list(state_dict.keys() ) _SCREAMING_SNAKE_CASE : Tuple = {} for key in keys: _SCREAMING_SNAKE_CASE : Dict = state_dict.pop(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : int = rename_keys(__SCREAMING_SNAKE_CASE ) if "in_proj_weight" in key: # split fused qkv proj _SCREAMING_SNAKE_CASE : str = val[:hidden_size, :] _SCREAMING_SNAKE_CASE : Any = val[hidden_size : 2 * hidden_size, :] _SCREAMING_SNAKE_CASE : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: _SCREAMING_SNAKE_CASE : int = val else: _SCREAMING_SNAKE_CASE : Dict = val return state_dict, enc_dec_proj_state_dict def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> MusicgenDecoderConfig: if checkpoint == "small": # default config values _SCREAMING_SNAKE_CASE : Optional[Any] = 1_024 _SCREAMING_SNAKE_CASE : str = 24 _SCREAMING_SNAKE_CASE : Any = 16 elif checkpoint == "medium": _SCREAMING_SNAKE_CASE : Dict = 1_536 _SCREAMING_SNAKE_CASE : Union[str, Any] = 48 _SCREAMING_SNAKE_CASE : Optional[Any] = 24 elif checkpoint == "large": _SCREAMING_SNAKE_CASE : List[Any] = 2_048 _SCREAMING_SNAKE_CASE : Optional[int] = 48 _SCREAMING_SNAKE_CASE : str = 32 else: raise ValueError(F"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) _SCREAMING_SNAKE_CASE : Optional[Any] = MusicgenDecoderConfig( hidden_size=__SCREAMING_SNAKE_CASE , ffn_dim=hidden_size * 4 , num_hidden_layers=__SCREAMING_SNAKE_CASE , num_attention_heads=__SCREAMING_SNAKE_CASE , ) return config @torch.no_grad() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="cpu" )-> str: _SCREAMING_SNAKE_CASE : str = MusicGen.get_pretrained(__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[str] = decoder_config_from_checkpoint(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[Any] = fairseq_model.lm.state_dict() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = rename_state_dict( __SCREAMING_SNAKE_CASE , hidden_size=decoder_config.hidden_size ) _SCREAMING_SNAKE_CASE : Tuple = TaEncoderModel.from_pretrained("""t5-base""" ) _SCREAMING_SNAKE_CASE : List[Any] = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) _SCREAMING_SNAKE_CASE : str = MusicgenForCausalLM(__SCREAMING_SNAKE_CASE ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = decoder.load_state_dict(__SCREAMING_SNAKE_CASE , strict=__SCREAMING_SNAKE_CASE ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ValueError(F"""Missing key(s) in state_dict: {missing_keys}""" ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ValueError(F"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model _SCREAMING_SNAKE_CASE : Dict = MusicgenForConditionalGeneration(text_encoder=__SCREAMING_SNAKE_CASE , audio_encoder=__SCREAMING_SNAKE_CASE , decoder=__SCREAMING_SNAKE_CASE ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(__SCREAMING_SNAKE_CASE ) # check we can do a forward pass _SCREAMING_SNAKE_CASE : Optional[Any] = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) _SCREAMING_SNAKE_CASE : Dict = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[int] = model(input_ids=__SCREAMING_SNAKE_CASE , decoder_input_ids=__SCREAMING_SNAKE_CASE ).logits if logits.shape != (8, 1, 2_048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor _SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained("""t5-base""" ) _SCREAMING_SNAKE_CASE : List[str] = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) _SCREAMING_SNAKE_CASE : Optional[int] = MusicgenProcessor(feature_extractor=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE ) # set the appropriate bos/pad token ids _SCREAMING_SNAKE_CASE : Optional[Any] = 2_048 _SCREAMING_SNAKE_CASE : List[Any] = 2_048 # set other default generation config params _SCREAMING_SNAKE_CASE : Any = int(30 * audio_encoder.config.frame_rate ) _SCREAMING_SNAKE_CASE : Tuple = True _SCREAMING_SNAKE_CASE : int = 3.0 if pytorch_dump_folder is not None: Path(__SCREAMING_SNAKE_CASE ).mkdir(exist_ok=__SCREAMING_SNAKE_CASE ) logger.info(F"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) processor.save_pretrained(__SCREAMING_SNAKE_CASE ) if repo_id: logger.info(F"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(__SCREAMING_SNAKE_CASE ) processor.push_to_hub(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint''', default='''small''', type=str, help='''Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.''', ) parser.add_argument( '''--pytorch_dump_folder''', required=True, default=None, type=str, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) parser.add_argument( '''--device''', default='''cpu''', type=str, help='''Torch device to run the conversion, either cpu or cuda.''' ) lowerCAmelCase_ = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
635
1
"""simple docstring""" import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class _snake_case ( __snake_case ): """simple docstring""" def _lowerCAmelCase ( self : int): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(_A , """tf_padding""")) self.parent.assertTrue(hasattr(_A , """depth_multiplier""")) class _snake_case : """simple docstring""" def __init__( self : Tuple , _A : Dict , _A : Union[str, Any]=1_3 , _A : str=3 , _A : Tuple=3_2 , _A : Any=0.25 , _A : List[Any]=8 , _A : str=8 , _A : List[Any]=6 , _A : Any=3_2 , _A : Tuple=True , _A : List[Any]=True , _A : int=True , _A : Optional[Any]="relu6" , _A : Tuple=1_2_8_0 , _A : Union[str, Any]=0.1 , _A : Dict=0.02 , _A : Tuple=True , _A : Dict=True , _A : Optional[int]=1_0 , _A : List[str]=None , ): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = parent _SCREAMING_SNAKE_CASE : Optional[Any] = batch_size _SCREAMING_SNAKE_CASE : Union[str, Any] = num_channels _SCREAMING_SNAKE_CASE : List[Any] = image_size _SCREAMING_SNAKE_CASE : str = depth_multiplier _SCREAMING_SNAKE_CASE : Any = depth_divisible_by _SCREAMING_SNAKE_CASE : Dict = min_depth _SCREAMING_SNAKE_CASE : Optional[Any] = expand_ratio _SCREAMING_SNAKE_CASE : Optional[int] = tf_padding _SCREAMING_SNAKE_CASE : List[str] = output_stride _SCREAMING_SNAKE_CASE : str = first_layer_is_expansion _SCREAMING_SNAKE_CASE : Union[str, Any] = finegrained_output _SCREAMING_SNAKE_CASE : int = hidden_act _SCREAMING_SNAKE_CASE : Optional[Any] = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier) _SCREAMING_SNAKE_CASE : Any = classifier_dropout_prob _SCREAMING_SNAKE_CASE : str = use_labels _SCREAMING_SNAKE_CASE : List[str] = is_training _SCREAMING_SNAKE_CASE : List[str] = num_labels _SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range _SCREAMING_SNAKE_CASE : Union[str, Any] = scope def _lowerCAmelCase ( self : int): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) _SCREAMING_SNAKE_CASE : Optional[Any] = None _SCREAMING_SNAKE_CASE : Any = None if self.use_labels: _SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor([self.batch_size] , self.num_labels) _SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels) _SCREAMING_SNAKE_CASE : int = self.get_config() return config, pixel_values, labels, pixel_labels def _lowerCAmelCase ( self : str): """simple docstring""" return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , depth_divisible_by=self.depth_divisible_by , min_depth=self.min_depth , expand_ratio=self.expand_ratio , output_stride=self.output_stride , first_layer_is_expansion=self.first_layer_is_expansion , finegrained_output=self.finegrained_output , hidden_act=self.hidden_act , tf_padding=self.tf_padding , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _lowerCAmelCase ( self : int , _A : Tuple , _A : Optional[int] , _A : List[str] , _A : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = MobileNetVaModel(config=_A) model.to(_A) model.eval() _SCREAMING_SNAKE_CASE : Optional[int] = model(_A) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) self.parent.assertEqual( result.pooler_output.shape , (self.batch_size, self.last_hidden_size) , ) def _lowerCAmelCase ( self : str , _A : List[str] , _A : Dict , _A : Optional[int] , _A : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = self.num_labels _SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaForImageClassification(_A) model.to(_A) model.eval() _SCREAMING_SNAKE_CASE : List[Any] = model(_A , labels=_A) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _lowerCAmelCase ( self : Optional[Any] , _A : Union[str, Any] , _A : str , _A : str , _A : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = self.num_labels _SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaForSemanticSegmentation(_A) model.to(_A) model.eval() _SCREAMING_SNAKE_CASE : Any = model(_A) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) _SCREAMING_SNAKE_CASE : Optional[Any] = model(_A , labels=_A) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : str = self.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = config_and_inputs _SCREAMING_SNAKE_CASE : List[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _snake_case ( __snake_case , __snake_case , unittest.TestCase ): """simple docstring""" a = ( (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation) if is_torch_available() else () ) a = ( { "feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification, "image-segmentation": MobileNetVaForSemanticSegmentation, } if is_torch_available() else {} ) a = False a = False a = False a = False def _lowerCAmelCase ( self : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : str = MobileNetVaModelTester(self) _SCREAMING_SNAKE_CASE : Dict = MobileNetVaConfigTester(self , config_class=_A , has_text_modality=_A) def _lowerCAmelCase ( self : Tuple): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""MobileNetV2 does not use inputs_embeds""") def _lowerCAmelCase ( self : Dict): """simple docstring""" pass @unittest.skip(reason="""MobileNetV2 does not support input and output embeddings""") def _lowerCAmelCase ( self : Tuple): """simple docstring""" pass @unittest.skip(reason="""MobileNetV2 does not output attentions""") def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" pass def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : List[Any] = model_class(_A) _SCREAMING_SNAKE_CASE : Dict = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _SCREAMING_SNAKE_CASE : Any = [*signature.parameters.keys()] _SCREAMING_SNAKE_CASE : Any = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _A) def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A) def _lowerCAmelCase ( self : Tuple): """simple docstring""" def check_hidden_states_output(_A : Optional[Any] , _A : Optional[int] , _A : Dict): _SCREAMING_SNAKE_CASE : List[Any] = model_class(_A) model.to(_A) model.eval() with torch.no_grad(): _SCREAMING_SNAKE_CASE : str = model(**self._prepare_for_class(_A , _A)) _SCREAMING_SNAKE_CASE : int = outputs.hidden_states _SCREAMING_SNAKE_CASE : Optional[int] = 1_6 self.assertEqual(len(_A) , _A) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : List[str] = True check_hidden_states_output(_A , _A , _A) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _SCREAMING_SNAKE_CASE : Tuple = True check_hidden_states_output(_A , _A , _A) def _lowerCAmelCase ( self : int): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A) def _lowerCAmelCase ( self : Union[str, Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_A) @slow def _lowerCAmelCase ( self : Dict): """simple docstring""" for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE : str = MobileNetVaModel.from_pretrained(_A) self.assertIsNotNone(_A) def lowerCamelCase_()-> Tuple: _SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _snake_case ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : Tuple): """simple docstring""" return ( MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v2_1.0_224""") if is_vision_available() else None ) @slow def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v2_1.0_224""").to(_A) _SCREAMING_SNAKE_CASE : Optional[int] = self.default_image_processor _SCREAMING_SNAKE_CASE : Tuple = prepare_img() _SCREAMING_SNAKE_CASE : int = image_processor(images=_A , return_tensors="""pt""").to(_A) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE : Dict = model(**_A) # verify the logits _SCREAMING_SNAKE_CASE : Any = torch.Size((1, 1_0_0_1)) self.assertEqual(outputs.logits.shape , _A) _SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_445, -1.1_993, 0.1_905]).to(_A) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _A , atol=1e-4)) @slow def _lowerCAmelCase ( self : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaForSemanticSegmentation.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513""") _SCREAMING_SNAKE_CASE : str = model.to(_A) _SCREAMING_SNAKE_CASE : Dict = MobileNetVaImageProcessor.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513""") _SCREAMING_SNAKE_CASE : Dict = prepare_img() _SCREAMING_SNAKE_CASE : List[str] = image_processor(images=_A , return_tensors="""pt""").to(_A) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[Any] = model(**_A) _SCREAMING_SNAKE_CASE : Any = outputs.logits # verify the logits _SCREAMING_SNAKE_CASE : Dict = torch.Size((1, 2_1, 6_5, 6_5)) self.assertEqual(logits.shape , _A) _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [ [[17.5_790, 17.7_581, 18.3_355], [18.3_257, 18.4_230, 18.8_973], [18.6_169, 18.8_650, 19.2_187]], [[-2.1_595, -2.0_977, -2.3_741], [-2.4_226, -2.3_028, -2.6_835], [-2.7_819, -2.5_991, -2.7_706]], [[4.2_058, 4.8_317, 4.7_638], [4.4_136, 5.0_361, 4.9_383], [4.5_028, 4.9_644, 4.8_734]], ] , device=_A , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _A , atol=1e-4))
635
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''asapp/sew-tiny-100k''': '''https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json''', # See all SEW models at https://huggingface.co/models?filter=sew } class _snake_case ( __snake_case ): """simple docstring""" a = "sew" def __init__( self : List[Any] , _A : Tuple=3_2 , _A : str=7_6_8 , _A : Dict=1_2 , _A : Tuple=1_2 , _A : Optional[Any]=3_0_7_2 , _A : List[str]=2 , _A : Dict="gelu" , _A : Union[str, Any]=0.1 , _A : Optional[int]=0.1 , _A : Optional[int]=0.1 , _A : Optional[int]=0.0 , _A : str=0.1 , _A : Tuple=0.1 , _A : Optional[int]=0.02 , _A : Dict=1e-5 , _A : str="group" , _A : Tuple="gelu" , _A : Union[str, Any]=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , _A : Optional[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , _A : Any=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , _A : Tuple=False , _A : Tuple=1_2_8 , _A : int=1_6 , _A : Union[str, Any]=True , _A : Optional[Any]=0.05 , _A : List[Any]=1_0 , _A : Union[str, Any]=2 , _A : Tuple=0.0 , _A : Union[str, Any]=1_0 , _A : Optional[int]=0 , _A : Union[str, Any]="mean" , _A : Optional[int]=False , _A : List[Any]=False , _A : int=2_5_6 , _A : str=0 , _A : Optional[int]=1 , _A : List[Any]=2 , **_A : Dict , ): """simple docstring""" super().__init__(**_A , pad_token_id=_A , bos_token_id=_A , eos_token_id=_A) _SCREAMING_SNAKE_CASE : str = hidden_size _SCREAMING_SNAKE_CASE : Optional[int] = feat_extract_norm _SCREAMING_SNAKE_CASE : Optional[int] = feat_extract_activation _SCREAMING_SNAKE_CASE : Dict = list(_A) _SCREAMING_SNAKE_CASE : int = list(_A) _SCREAMING_SNAKE_CASE : int = list(_A) _SCREAMING_SNAKE_CASE : str = conv_bias _SCREAMING_SNAKE_CASE : Tuple = num_conv_pos_embeddings _SCREAMING_SNAKE_CASE : List[str] = num_conv_pos_embedding_groups _SCREAMING_SNAKE_CASE : Tuple = len(self.conv_dim) _SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers _SCREAMING_SNAKE_CASE : List[str] = intermediate_size _SCREAMING_SNAKE_CASE : str = squeeze_factor _SCREAMING_SNAKE_CASE : Dict = hidden_act _SCREAMING_SNAKE_CASE : str = num_attention_heads _SCREAMING_SNAKE_CASE : Dict = hidden_dropout _SCREAMING_SNAKE_CASE : Tuple = attention_dropout _SCREAMING_SNAKE_CASE : int = activation_dropout _SCREAMING_SNAKE_CASE : Any = feat_proj_dropout _SCREAMING_SNAKE_CASE : str = final_dropout _SCREAMING_SNAKE_CASE : Union[str, Any] = layerdrop _SCREAMING_SNAKE_CASE : Any = layer_norm_eps _SCREAMING_SNAKE_CASE : int = initializer_range _SCREAMING_SNAKE_CASE : List[Any] = vocab_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect.""" """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,""" f"""but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride)""" f"""= {len(self.conv_stride)}`, `len(config.conv_kernel) = {len(self.conv_kernel)}`.""") # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _SCREAMING_SNAKE_CASE : List[Any] = apply_spec_augment _SCREAMING_SNAKE_CASE : List[Any] = mask_time_prob _SCREAMING_SNAKE_CASE : List[str] = mask_time_length _SCREAMING_SNAKE_CASE : List[Any] = mask_time_min_masks _SCREAMING_SNAKE_CASE : List[Any] = mask_feature_prob _SCREAMING_SNAKE_CASE : int = mask_feature_length _SCREAMING_SNAKE_CASE : List[Any] = mask_feature_min_masks # ctc loss _SCREAMING_SNAKE_CASE : int = ctc_loss_reduction _SCREAMING_SNAKE_CASE : Optional[int] = ctc_zero_infinity # sequence classification _SCREAMING_SNAKE_CASE : Dict = use_weighted_layer_sum _SCREAMING_SNAKE_CASE : List[str] = classifier_proj_size @property def _lowerCAmelCase ( self : Any): """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1)
635
1
"""simple docstring""" from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput lowerCAmelCase_ = 8 def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=BITS )-> Any: _SCREAMING_SNAKE_CASE : int = x.device _SCREAMING_SNAKE_CASE : Optional[Any] = (x * 255).int().clamp(0 , 255 ) _SCREAMING_SNAKE_CASE : Optional[int] = 2 ** torch.arange(bits - 1 , -1 , -1 , device=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[Any] = rearrange(__SCREAMING_SNAKE_CASE , """d -> d 1 1""" ) _SCREAMING_SNAKE_CASE : Dict = rearrange(__SCREAMING_SNAKE_CASE , """b c h w -> b c 1 h w""" ) _SCREAMING_SNAKE_CASE : Tuple = ((x & mask) != 0).float() _SCREAMING_SNAKE_CASE : Optional[Any] = rearrange(__SCREAMING_SNAKE_CASE , """b c d h w -> b (c d) h w""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = bits * 2 - 1 return bits def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=BITS )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : List[str] = x.device _SCREAMING_SNAKE_CASE : Dict = (x > 0).int() _SCREAMING_SNAKE_CASE : Dict = 2 ** torch.arange(bits - 1 , -1 , -1 , device=__SCREAMING_SNAKE_CASE , dtype=torch.intaa ) _SCREAMING_SNAKE_CASE : List[Any] = rearrange(__SCREAMING_SNAKE_CASE , """d -> d 1 1""" ) _SCREAMING_SNAKE_CASE : Any = rearrange(__SCREAMING_SNAKE_CASE , """b (c d) h w -> b c d h w""" , d=8 ) _SCREAMING_SNAKE_CASE : str = reduce(x * mask , """b c d h w -> b c h w""" , """sum""" ) return (dec / 255).clamp(0.0 , 1.0 ) def lowerCamelCase_(self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0 , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = True , )-> Union[DDIMSchedulerOutput, Tuple]: if self.num_inference_steps is None: raise ValueError( """Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler""" ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) _SCREAMING_SNAKE_CASE : Tuple = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas _SCREAMING_SNAKE_CASE : int = self.alphas_cumprod[timestep] _SCREAMING_SNAKE_CASE : List[str] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod _SCREAMING_SNAKE_CASE : Optional[Any] = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _SCREAMING_SNAKE_CASE : Union[str, Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" _SCREAMING_SNAKE_CASE : Union[str, Any] = self.bit_scale if self.config.clip_sample: _SCREAMING_SNAKE_CASE : Optional[Any] = torch.clamp(__SCREAMING_SNAKE_CASE , -scale , __SCREAMING_SNAKE_CASE ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) _SCREAMING_SNAKE_CASE : Union[str, Any] = self._get_variance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : str = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide _SCREAMING_SNAKE_CASE : List[str] = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _SCREAMING_SNAKE_CASE : Optional[Any] = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _SCREAMING_SNAKE_CASE : Any = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 _SCREAMING_SNAKE_CASE : int = model_output.device if torch.is_tensor(__SCREAMING_SNAKE_CASE ) else """cpu""" _SCREAMING_SNAKE_CASE : List[Any] = torch.randn(model_output.shape , dtype=model_output.dtype , generator=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : int = self._get_variance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ** 0.5 * eta * noise _SCREAMING_SNAKE_CASE : int = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=__SCREAMING_SNAKE_CASE , pred_original_sample=__SCREAMING_SNAKE_CASE ) def lowerCamelCase_(self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="epsilon" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = True , )-> Union[DDPMSchedulerOutput, Tuple]: _SCREAMING_SNAKE_CASE : str = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = torch.split(__SCREAMING_SNAKE_CASE , sample.shape[1] , dim=1 ) else: _SCREAMING_SNAKE_CASE : Any = None # 1. compute alphas, betas _SCREAMING_SNAKE_CASE : Tuple = self.alphas_cumprod[t] _SCREAMING_SNAKE_CASE : Tuple = self.alphas_cumprod[t - 1] if t > 0 else self.one _SCREAMING_SNAKE_CASE : Dict = 1 - alpha_prod_t _SCREAMING_SNAKE_CASE : Union[str, Any] = 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 prediction_type == "epsilon": _SCREAMING_SNAKE_CASE : List[str] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": _SCREAMING_SNAKE_CASE : Optional[Any] = model_output else: raise ValueError(F"""Unsupported prediction_type {prediction_type}.""" ) # 3. Clip "predicted x_0" _SCREAMING_SNAKE_CASE : int = self.bit_scale if self.config.clip_sample: _SCREAMING_SNAKE_CASE : Any = torch.clamp(__SCREAMING_SNAKE_CASE , -scale , __SCREAMING_SNAKE_CASE ) # 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 _SCREAMING_SNAKE_CASE : Tuple = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t _SCREAMING_SNAKE_CASE : Union[str, Any] = self.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 _SCREAMING_SNAKE_CASE : int = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 if t > 0: _SCREAMING_SNAKE_CASE : List[str] = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=__SCREAMING_SNAKE_CASE ).to(model_output.device ) _SCREAMING_SNAKE_CASE : Optional[Any] = (self._get_variance(__SCREAMING_SNAKE_CASE , predicted_variance=__SCREAMING_SNAKE_CASE ) ** 0.5) * noise _SCREAMING_SNAKE_CASE : Any = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=__SCREAMING_SNAKE_CASE , pred_original_sample=__SCREAMING_SNAKE_CASE ) class _snake_case ( __snake_case ): """simple docstring""" def __init__( self : Dict , _A : UNetaDConditionModel , _A : Union[DDIMScheduler, DDPMScheduler] , _A : Optional[float] = 1.0 , ): """simple docstring""" super().__init__() _SCREAMING_SNAKE_CASE : Tuple = bit_scale _SCREAMING_SNAKE_CASE : Optional[Any] = ( ddim_bit_scheduler_step if isinstance(_A , _A) else ddpm_bit_scheduler_step ) self.register_modules(unet=_A , scheduler=_A) @torch.no_grad() def __call__( self : Optional[int] , _A : Optional[int] = 2_5_6 , _A : Optional[int] = 2_5_6 , _A : Optional[int] = 5_0 , _A : Optional[torch.Generator] = None , _A : Optional[int] = 1 , _A : Optional[str] = "pil" , _A : bool = True , **_A : List[Any] , ): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = torch.randn( (batch_size, self.unet.config.in_channels, height, width) , generator=_A , ) _SCREAMING_SNAKE_CASE : Dict = decimal_to_bits(_A) * self.bit_scale _SCREAMING_SNAKE_CASE : Tuple = latents.to(self.device) self.scheduler.set_timesteps(_A) for t in self.progress_bar(self.scheduler.timesteps): # predict the noise residual _SCREAMING_SNAKE_CASE : Tuple = self.unet(_A , _A).sample # compute the previous noisy sample x_t -> x_t-1 _SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.step(_A , _A , _A).prev_sample _SCREAMING_SNAKE_CASE : int = bits_to_decimal(_A) if output_type == "pil": _SCREAMING_SNAKE_CASE : Optional[Any] = self.numpy_to_pil(_A) if not return_dict: return (image,) return ImagePipelineOutput(images=_A)
635
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCAmelCase_ = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
1
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('''.''') def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: _SCREAMING_SNAKE_CASE : int = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( """`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got """ F"""{test_file} instead.""" ) _SCREAMING_SNAKE_CASE : Any = components[-1] if not test_fn.endswith("""py""" ): raise ValueError(F"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith("""test_modeling_""" ): raise ValueError( F"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) _SCREAMING_SNAKE_CASE : str = components[:-1] + [test_fn.replace(""".py""" , """""" )] _SCREAMING_SNAKE_CASE : Dict = """.""".join(__SCREAMING_SNAKE_CASE ) return test_module_path def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[int]: _SCREAMING_SNAKE_CASE : str = get_module_path(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Union[str, Any] = importlib.import_module(__SCREAMING_SNAKE_CASE ) return test_module def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[Any]: _SCREAMING_SNAKE_CASE : List[str] = [] _SCREAMING_SNAKE_CASE : List[str] = get_test_module(__SCREAMING_SNAKE_CASE ) for attr in dir(__SCREAMING_SNAKE_CASE ): if attr.endswith("""ModelTester""" ): tester_classes.append(getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) # sort with class names return sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : List[Any] = get_test_module(__SCREAMING_SNAKE_CASE ) for attr in dir(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). _SCREAMING_SNAKE_CASE : Union[str, Any] = getattr(__SCREAMING_SNAKE_CASE , """all_model_classes""" , [] ) if len(__SCREAMING_SNAKE_CASE ) > 0: test_classes.append(__SCREAMING_SNAKE_CASE ) # sort with class names return sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[Any]: _SCREAMING_SNAKE_CASE : str = get_test_classes(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Any = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : int = test_class() if hasattr(__SCREAMING_SNAKE_CASE , """setUp""" ): test.setUp() _SCREAMING_SNAKE_CASE : List[str] = None if hasattr(__SCREAMING_SNAKE_CASE , """model_tester""" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: _SCREAMING_SNAKE_CASE : Optional[int] = test.model_tester.__class__ return model_tester def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: _SCREAMING_SNAKE_CASE : Union[str, Any] = get_test_classes(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[int] = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(__SCREAMING_SNAKE_CASE ) # sort with class names return sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: _SCREAMING_SNAKE_CASE : int = get_test_classes_for_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [] for test_class in test_classes: _SCREAMING_SNAKE_CASE : str = get_model_tester_from_test_class(__SCREAMING_SNAKE_CASE ) if tester_class is not None: tester_classes.append(__SCREAMING_SNAKE_CASE ) # sort with class names return sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : x.__name__ ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Dict: _SCREAMING_SNAKE_CASE : Optional[int] = get_test_classes(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Any = {test_class: get_model_tester_from_test_class(__SCREAMING_SNAKE_CASE ) for test_class in test_classes} return test_tester_mapping def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Any: _SCREAMING_SNAKE_CASE : List[Any] = get_model_classes(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = { model_class: get_test_classes_for_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_test_mapping def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Any: _SCREAMING_SNAKE_CASE : List[str] = get_model_classes(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Union[str, Any] = { model_class: get_tester_classes_for_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_to_tester_mapping def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[int]: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return o elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return o.__name__ elif isinstance(__SCREAMING_SNAKE_CASE , (list, tuple) ): return [to_json(__SCREAMING_SNAKE_CASE ) for x in o] elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return {to_json(__SCREAMING_SNAKE_CASE ): to_json(__SCREAMING_SNAKE_CASE ) for k, v in o.items()} else: return o
635
"""simple docstring""" import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: _SCREAMING_SNAKE_CASE : List[str] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Union[str, Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _SCREAMING_SNAKE_CASE : List[Any] = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: _SCREAMING_SNAKE_CASE : int = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : str = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : List[Any] = features.copy() if features else default_expected_features _SCREAMING_SNAKE_CASE : List[Any] = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) _SCREAMING_SNAKE_CASE : Optional[Any] = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: _SCREAMING_SNAKE_CASE : Tuple = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : int = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : Dict = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , split=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""" , [str, list] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> str: if issubclass(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = parquet_path elif issubclass(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = [parquet_path] _SCREAMING_SNAKE_CASE : Optional[Any] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Union[str, Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : str = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=("train",) )-> Union[str, Any]: assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for split in splits: _SCREAMING_SNAKE_CASE : int = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Optional[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _SCREAMING_SNAKE_CASE : Tuple = ParquetDatasetReader( {"""train""": parquet_path} , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: _SCREAMING_SNAKE_CASE : Optional[int] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Optional[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : List[str] = features.copy() if features else default_expected_features _SCREAMING_SNAKE_CASE : str = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) _SCREAMING_SNAKE_CASE : int = ParquetDatasetReader({"""train""": parquet_path} , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: if split: _SCREAMING_SNAKE_CASE : Union[str, Any] = {split: parquet_path} else: _SCREAMING_SNAKE_CASE : Optional[int] = """train""" _SCREAMING_SNAKE_CASE : Any = {"""train""": parquet_path, """test""": parquet_path} _SCREAMING_SNAKE_CASE : List[str] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : List[str] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : Union[str, Any] = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[Any]: _SCREAMING_SNAKE_CASE : List[str] = ParquetDatasetWriter(__SCREAMING_SNAKE_CASE , tmp_path / """foo.parquet""" ) assert writer.write() > 0 _SCREAMING_SNAKE_CASE : Tuple = pq.ParquetFile(tmp_path / """foo.parquet""" ) _SCREAMING_SNAKE_CASE : str = pf.read() assert dataset.data.table == output_table def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Dict = str(shared_datadir / """test_image_rgb.jpg""" ) _SCREAMING_SNAKE_CASE : Optional[Any] = {"""image""": [image_path]} _SCREAMING_SNAKE_CASE : Optional[Any] = Features({"""image""": Image()} ) _SCREAMING_SNAKE_CASE : Optional[int] = Dataset.from_dict(__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = ParquetDatasetWriter(__SCREAMING_SNAKE_CASE , tmp_path / """foo.parquet""" ) assert writer.write() > 0 _SCREAMING_SNAKE_CASE : List[str] = Dataset.from_parquet(str(tmp_path / """foo.parquet""" ) ) assert dataset.features == reloaded_dataset.features _SCREAMING_SNAKE_CASE : List[Any] = ParquetDatasetReader(str(tmp_path / """foo.parquet""" ) , streaming=__SCREAMING_SNAKE_CASE ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( """feature, expected""" , [ (Features({"""foo""": Value("""int32""" )} ), None), (Features({"""image""": Image(), """foo""": Value("""int32""" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"""nested""": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> int: assert get_writer_batch_size(__SCREAMING_SNAKE_CASE ) == expected
635
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''microsoft/cvt-13''': '''https://huggingface.co/microsoft/cvt-13/resolve/main/config.json''', # See all Cvt models at https://huggingface.co/models?filter=cvt } class _snake_case ( __snake_case ): """simple docstring""" a = "cvt" def __init__( self : Any , _A : List[Any]=3 , _A : List[Any]=[7, 3, 3] , _A : List[Any]=[4, 2, 2] , _A : Union[str, Any]=[2, 1, 1] , _A : Tuple=[6_4, 1_9_2, 3_8_4] , _A : int=[1, 3, 6] , _A : Tuple=[1, 2, 1_0] , _A : Optional[int]=[4.0, 4.0, 4.0] , _A : Any=[0.0, 0.0, 0.0] , _A : Union[str, Any]=[0.0, 0.0, 0.0] , _A : str=[0.0, 0.0, 0.1] , _A : Any=[True, True, True] , _A : Any=[False, False, True] , _A : Tuple=["dw_bn", "dw_bn", "dw_bn"] , _A : Optional[Any]=[3, 3, 3] , _A : Any=[1, 1, 1] , _A : Tuple=[2, 2, 2] , _A : List[Any]=[1, 1, 1] , _A : Dict=[1, 1, 1] , _A : Dict=0.02 , _A : List[Any]=1e-12 , **_A : List[Any] , ): """simple docstring""" super().__init__(**_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = num_channels _SCREAMING_SNAKE_CASE : List[str] = patch_sizes _SCREAMING_SNAKE_CASE : Any = patch_stride _SCREAMING_SNAKE_CASE : Tuple = patch_padding _SCREAMING_SNAKE_CASE : Tuple = embed_dim _SCREAMING_SNAKE_CASE : int = num_heads _SCREAMING_SNAKE_CASE : Tuple = depth _SCREAMING_SNAKE_CASE : Optional[Any] = mlp_ratio _SCREAMING_SNAKE_CASE : Union[str, Any] = attention_drop_rate _SCREAMING_SNAKE_CASE : Optional[int] = drop_rate _SCREAMING_SNAKE_CASE : Optional[int] = drop_path_rate _SCREAMING_SNAKE_CASE : Any = qkv_bias _SCREAMING_SNAKE_CASE : Dict = cls_token _SCREAMING_SNAKE_CASE : str = qkv_projection_method _SCREAMING_SNAKE_CASE : int = kernel_qkv _SCREAMING_SNAKE_CASE : int = padding_kv _SCREAMING_SNAKE_CASE : List[str] = stride_kv _SCREAMING_SNAKE_CASE : List[Any] = padding_q _SCREAMING_SNAKE_CASE : Dict = stride_q _SCREAMING_SNAKE_CASE : str = initializer_range _SCREAMING_SNAKE_CASE : List[Any] = layer_norm_eps
635
"""simple docstring""" def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise TypeError("""only integers accepted as input""" ) else: _SCREAMING_SNAKE_CASE : List[Any] = str(abs(__SCREAMING_SNAKE_CASE ) ) _SCREAMING_SNAKE_CASE : List[str] = [list(__SCREAMING_SNAKE_CASE ) for char in range(len(__SCREAMING_SNAKE_CASE ) )] for index in range(len(__SCREAMING_SNAKE_CASE ) ): num_transpositions[index].pop(__SCREAMING_SNAKE_CASE ) return max( int("""""".join(list(__SCREAMING_SNAKE_CASE ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('''doctest''').testmod()
635
1
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html lowerCAmelCase_ = '''platform''' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class _snake_case : """simple docstring""" a = PegasusConfig a = {} a = "gelu" def __init__( self : List[str] , _A : str , _A : str=1_3 , _A : Dict=7 , _A : Tuple=True , _A : Tuple=False , _A : Any=9_9 , _A : Union[str, Any]=3_2 , _A : Dict=5 , _A : List[str]=4 , _A : Union[str, Any]=3_7 , _A : int=0.1 , _A : Union[str, Any]=0.1 , _A : Any=2_0 , _A : List[str]=2 , _A : Optional[int]=1 , _A : Optional[Any]=0 , ): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = parent _SCREAMING_SNAKE_CASE : int = batch_size _SCREAMING_SNAKE_CASE : List[Any] = seq_length _SCREAMING_SNAKE_CASE : Tuple = is_training _SCREAMING_SNAKE_CASE : Tuple = use_labels _SCREAMING_SNAKE_CASE : Dict = vocab_size _SCREAMING_SNAKE_CASE : Tuple = hidden_size _SCREAMING_SNAKE_CASE : List[str] = num_hidden_layers _SCREAMING_SNAKE_CASE : str = num_attention_heads _SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size _SCREAMING_SNAKE_CASE : int = hidden_dropout_prob _SCREAMING_SNAKE_CASE : int = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings _SCREAMING_SNAKE_CASE : Tuple = eos_token_id _SCREAMING_SNAKE_CASE : Optional[int] = pad_token_id _SCREAMING_SNAKE_CASE : Any = bos_token_id def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size).clip(3 , self.vocab_size) _SCREAMING_SNAKE_CASE : List[str] = np.expand_dims(np.array([self.eos_token_id] * self.batch_size) , 1) _SCREAMING_SNAKE_CASE : Union[str, Any] = np.concatenate([input_ids, eos_tensor] , axis=1) _SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _SCREAMING_SNAKE_CASE : List[str] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _SCREAMING_SNAKE_CASE : Any = prepare_pegasus_inputs_dict(_A , _A , _A) return config, inputs_dict def _lowerCAmelCase ( self : Dict , _A : Optional[int] , _A : int , _A : Union[str, Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = 2_0 _SCREAMING_SNAKE_CASE : Union[str, Any] = model_class_name(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = model.encode(inputs_dict["""input_ids"""]) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) _SCREAMING_SNAKE_CASE : Dict = model.init_cache(decoder_input_ids.shape[0] , _A , _A) _SCREAMING_SNAKE_CASE : List[str] = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""") _SCREAMING_SNAKE_CASE : str = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _SCREAMING_SNAKE_CASE : List[str] = model.decode( decoder_input_ids[:, :-1] , _A , decoder_attention_mask=_A , past_key_values=_A , decoder_position_ids=_A , ) _SCREAMING_SNAKE_CASE : Tuple = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""") _SCREAMING_SNAKE_CASE : Union[str, Any] = model.decode( decoder_input_ids[:, -1:] , _A , decoder_attention_mask=_A , past_key_values=outputs_cache.past_key_values , decoder_position_ids=_A , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = model.decode(_A , _A) _SCREAMING_SNAKE_CASE : Union[str, Any] = 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 : Optional[int] , _A : Optional[Any] , _A : List[Any] , _A : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = 2_0 _SCREAMING_SNAKE_CASE : int = model_class_name(_A) _SCREAMING_SNAKE_CASE : Tuple = model.encode(inputs_dict["""input_ids"""]) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) _SCREAMING_SNAKE_CASE : Optional[Any] = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])), ] , axis=-1 , ) _SCREAMING_SNAKE_CASE : Optional[Any] = model.init_cache(decoder_input_ids.shape[0] , _A , _A) _SCREAMING_SNAKE_CASE : Optional[Any] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _SCREAMING_SNAKE_CASE : int = model.decode( decoder_input_ids[:, :-1] , _A , decoder_attention_mask=_A , past_key_values=_A , decoder_position_ids=_A , ) _SCREAMING_SNAKE_CASE : List[str] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""") _SCREAMING_SNAKE_CASE : List[str] = model.decode( decoder_input_ids[:, -1:] , _A , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=_A , decoder_position_ids=_A , ) _SCREAMING_SNAKE_CASE : List[str] = model.decode(_A , _A , decoder_attention_mask=_A) _SCREAMING_SNAKE_CASE : Optional[int] = 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_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , )-> Tuple: if attention_mask is None: _SCREAMING_SNAKE_CASE : int = np.not_equal(__SCREAMING_SNAKE_CASE , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: _SCREAMING_SNAKE_CASE : Union[str, Any] = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class _snake_case ( __snake_case , unittest.TestCase ): """simple docstring""" a = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) a = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () a = True a = False a = False a = False def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = FlaxPegasusModelTester(self) _SCREAMING_SNAKE_CASE : Any = ConfigTester(self , config_class=_A) def _lowerCAmelCase ( self : List[str]): """simple docstring""" self.config_tester.run_common_tests() def _lowerCAmelCase ( self : int): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(_A , _A , _A) def _lowerCAmelCase ( self : int): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(_A , _A , _A) def _lowerCAmelCase ( self : int): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__): _SCREAMING_SNAKE_CASE : List[Any] = self._prepare_for_class(_A , _A) _SCREAMING_SNAKE_CASE : str = model_class(_A) @jax.jit def encode_jitted(_A : str , _A : Tuple=None , **_A : Any): return model.encode(input_ids=_A , attention_mask=_A) with self.subTest("""JIT Enabled"""): _SCREAMING_SNAKE_CASE : Any = encode_jitted(**_A).to_tuple() with self.subTest("""JIT Disabled"""): with jax.disable_jit(): _SCREAMING_SNAKE_CASE : List[Any] = encode_jitted(**_A).to_tuple() self.assertEqual(len(_A) , len(_A)) for jitted_output, output in zip(_A , _A): self.assertEqual(jitted_output.shape , output.shape) def _lowerCAmelCase ( self : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__): _SCREAMING_SNAKE_CASE : Any = model_class(_A) _SCREAMING_SNAKE_CASE : str = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""]) _SCREAMING_SNAKE_CASE : List[str] = { """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(_A : Optional[Any] , _A : Optional[int] , _A : int): return model.decode( decoder_input_ids=_A , decoder_attention_mask=_A , encoder_outputs=_A , ) with self.subTest("""JIT Enabled"""): _SCREAMING_SNAKE_CASE : Dict = decode_jitted(**_A).to_tuple() with self.subTest("""JIT Disabled"""): with jax.disable_jit(): _SCREAMING_SNAKE_CASE : List[Any] = decode_jitted(**_A).to_tuple() self.assertEqual(len(_A) , len(_A)) for jitted_output, output in zip(_A , _A): self.assertEqual(jitted_output.shape , output.shape) @slow def _lowerCAmelCase ( self : Dict): """simple docstring""" for model_class_name in self.all_model_classes: _SCREAMING_SNAKE_CASE : Optional[Any] = model_class_name.from_pretrained("""google/pegasus-large""" , from_pt=_A) _SCREAMING_SNAKE_CASE : Optional[int] = np.ones((1, 1)) _SCREAMING_SNAKE_CASE : List[str] = model(_A) self.assertIsNotNone(_A) @slow def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = FlaxPegasusForConditionalGeneration.from_pretrained("""google/pegasus-xsum""") _SCREAMING_SNAKE_CASE : Any = PegasusTokenizer.from_pretrained("""google/pegasus-xsum""") _SCREAMING_SNAKE_CASE : List[Any] = [ """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""", """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" """, ] _SCREAMING_SNAKE_CASE : Any = [ """California's largest electricity provider has turned off power to hundreds of thousands of customers.""", """Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.""", ] _SCREAMING_SNAKE_CASE : Tuple = tokenizer(_A , return_tensors="""np""" , truncation=_A , max_length=5_1_2 , padding=_A) _SCREAMING_SNAKE_CASE : int = model.generate(**_A , num_beams=2).sequences _SCREAMING_SNAKE_CASE : int = tokenizer.batch_decode(_A , skip_special_tokens=_A) assert tgt_text == decoded
635
"""simple docstring""" import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers import AutoModelForCausalLM @require_torch class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : Any = -1 _SCREAMING_SNAKE_CASE : List[str] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : Dict = model.generate(_A , max_new_tokens=1_0 , do_sample=_A) _SCREAMING_SNAKE_CASE : Dict = tokenizer.decode(greedy_ids[0]) with CaptureStdout() as cs: _SCREAMING_SNAKE_CASE : Any = TextStreamer(_A) model.generate(_A , max_new_tokens=1_0 , do_sample=_A , streamer=_A) # The greedy text should be printed to stdout, except for the final "\n" in the streamer _SCREAMING_SNAKE_CASE : str = cs.out[:-1] self.assertEqual(_A , _A) def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : Any = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : List[Any] = -1 _SCREAMING_SNAKE_CASE : str = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = model.generate(_A , max_new_tokens=1_0 , do_sample=_A) _SCREAMING_SNAKE_CASE : Any = tokenizer.decode(greedy_ids[0]) _SCREAMING_SNAKE_CASE : List[Any] = TextIteratorStreamer(_A) _SCREAMING_SNAKE_CASE : Any = {"""input_ids""": input_ids, """max_new_tokens""": 1_0, """do_sample""": False, """streamer""": streamer} _SCREAMING_SNAKE_CASE : List[Any] = Thread(target=model.generate , kwargs=_A) thread.start() _SCREAMING_SNAKE_CASE : Any = """""" for new_text in streamer: streamer_text += new_text self.assertEqual(_A , _A) def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : Any = -1 _SCREAMING_SNAKE_CASE : Any = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = model.generate(_A , max_new_tokens=1_0 , do_sample=_A) _SCREAMING_SNAKE_CASE : str = greedy_ids[:, input_ids.shape[1] :] _SCREAMING_SNAKE_CASE : Dict = tokenizer.decode(new_greedy_ids[0]) with CaptureStdout() as cs: _SCREAMING_SNAKE_CASE : Any = TextStreamer(_A , skip_prompt=_A) model.generate(_A , max_new_tokens=1_0 , do_sample=_A , streamer=_A) # The greedy text should be printed to stdout, except for the final "\n" in the streamer _SCREAMING_SNAKE_CASE : Optional[int] = cs.out[:-1] self.assertEqual(_A , _A) def _lowerCAmelCase ( self : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained("""distilgpt2""") _SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForCausalLM.from_pretrained("""distilgpt2""").to(_A) _SCREAMING_SNAKE_CASE : int = -1 _SCREAMING_SNAKE_CASE : List[str] = torch.ones((1, 5) , device=_A).long() * model.config.bos_token_id with CaptureStdout() as cs: _SCREAMING_SNAKE_CASE : Optional[int] = TextStreamer(_A , skip_special_tokens=_A) model.generate(_A , max_new_tokens=1 , do_sample=_A , streamer=_A) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token _SCREAMING_SNAKE_CASE : Optional[Any] = cs.out[:-1] # Remove the final "\n" _SCREAMING_SNAKE_CASE : Tuple = tokenizer(_A , return_tensors="""pt""") self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1)) def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : List[Any] = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : Tuple = -1 _SCREAMING_SNAKE_CASE : Dict = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : int = TextIteratorStreamer(_A , timeout=0.001) _SCREAMING_SNAKE_CASE : List[Any] = {"""input_ids""": input_ids, """max_new_tokens""": 1_0, """do_sample""": False, """streamer""": streamer} _SCREAMING_SNAKE_CASE : List[str] = Thread(target=model.generate , kwargs=_A) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(_A): _SCREAMING_SNAKE_CASE : str = """""" for new_text in streamer: streamer_text += new_text
635
1
"""simple docstring""" import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class _snake_case : """simple docstring""" @staticmethod def _lowerCAmelCase ( *_A : List[str] , **_A : Tuple): """simple docstring""" pass def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> str: _SCREAMING_SNAKE_CASE : List[Any] = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Dict: _SCREAMING_SNAKE_CASE : List[Any] = np.array(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Any = npimg.shape return {"hash": hashimage(__SCREAMING_SNAKE_CASE ), "shape": shape} @is_pipeline_test @require_vision @require_torch class _snake_case ( unittest.TestCase ): """simple docstring""" a = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) a = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def _lowerCAmelCase ( self : int , _A : List[Any] , _A : Optional[int] , _A : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = MaskGenerationPipeline(model=_A , image_processor=_A) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def _lowerCAmelCase ( self : List[str] , _A : Union[str, Any] , _A : str): """simple docstring""" pass @require_tf @unittest.skip("""Image segmentation not implemented in TF""") def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" pass @slow @require_torch def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = pipeline("""mask-generation""" , model="""facebook/sam-vit-huge""") _SCREAMING_SNAKE_CASE : List[Any] = image_segmenter("""http://images.cocodataset.org/val2017/000000039769.jpg""" , points_per_batch=2_5_6) # Shortening by hashing _SCREAMING_SNAKE_CASE : Tuple = [] for i, o in enumerate(outputs["""masks"""]): new_outupt += [{"mask": mask_to_test_readable(_A), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_A , decimals=4) , [ {"""mask""": {"""hash""": """115ad19f5f""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.0_444}, {"""mask""": {"""hash""": """6affa964c6""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.021}, {"""mask""": {"""hash""": """dfe28a0388""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.0_167}, {"""mask""": {"""hash""": """c0a5f4a318""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.0_132}, {"""mask""": {"""hash""": """fe8065c197""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.0_053}, {"""mask""": {"""hash""": """e2d0b7a0b7""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_967}, {"""mask""": {"""hash""": """453c7844bd""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.993}, {"""mask""": {"""hash""": """3d44f2926d""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_909}, {"""mask""": {"""hash""": """64033ddc3f""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_879}, {"""mask""": {"""hash""": """801064ff79""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_834}, {"""mask""": {"""hash""": """6172f276ef""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_716}, {"""mask""": {"""hash""": """b49e60e084""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_612}, {"""mask""": {"""hash""": """a811e775fd""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_599}, {"""mask""": {"""hash""": """a6a8ebcf4b""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_552}, {"""mask""": {"""hash""": """9d8257e080""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_532}, {"""mask""": {"""hash""": """32de6454a8""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_516}, {"""mask""": {"""hash""": """af3d4af2c8""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_499}, {"""mask""": {"""hash""": """3c6db475fb""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_483}, {"""mask""": {"""hash""": """c290813fb9""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_464}, {"""mask""": {"""hash""": """b6f0b8f606""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.943}, {"""mask""": {"""hash""": """92ce16bfdf""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.943}, {"""mask""": {"""hash""": """c749b25868""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_408}, {"""mask""": {"""hash""": """efb6cab859""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_335}, {"""mask""": {"""hash""": """1ff2eafb30""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_326}, {"""mask""": {"""hash""": """788b798e24""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_262}, {"""mask""": {"""hash""": """abea804f0e""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.8_999}, {"""mask""": {"""hash""": """7b9e8ddb73""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.8_986}, {"""mask""": {"""hash""": """cd24047c8a""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.8_984}, {"""mask""": {"""hash""": """6943e6bcbd""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.8_873}, {"""mask""": {"""hash""": """b5f47c9191""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.8_871} ] , ) # fmt: on @require_torch @slow def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = """facebook/sam-vit-huge""" _SCREAMING_SNAKE_CASE : Union[str, Any] = pipeline("""mask-generation""" , model=_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = image_segmenter( """http://images.cocodataset.org/val2017/000000039769.jpg""" , pred_iou_thresh=1 , points_per_batch=2_5_6) # Shortening by hashing _SCREAMING_SNAKE_CASE : Any = [] for i, o in enumerate(outputs["""masks"""]): new_outupt += [{"mask": mask_to_test_readable(_A), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_A , decimals=4) , [ {"""mask""": {"""hash""": """115ad19f5f""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.0_444}, {"""mask""": {"""hash""": """6affa964c6""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.0_210}, {"""mask""": {"""hash""": """dfe28a0388""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.0_167}, {"""mask""": {"""hash""": """c0a5f4a318""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.0_132}, {"""mask""": {"""hash""": """fe8065c197""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.0_053}, ] , )
635
"""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 torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _snake_case ( __snake_case ): """simple docstring""" a = "facebook/bart-large-mnli" a = ( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) a = "text_classifier" a = AutoTokenizer a = AutoModelForSequenceClassification a = ["text", ["text"]] a = ["text"] def _lowerCAmelCase ( self : int): """simple docstring""" super().setup() _SCREAMING_SNAKE_CASE : Any = self.model.config _SCREAMING_SNAKE_CASE : Any = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail"""): _SCREAMING_SNAKE_CASE : List[Any] = int(_A) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""") def _lowerCAmelCase ( self : Optional[Any] , _A : Tuple , _A : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = labels return self.pre_processor( [text] * len(_A) , [f"""This example is {label}""" for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def _lowerCAmelCase ( self : Tuple , _A : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : str = outputs.logits _SCREAMING_SNAKE_CASE : List[Any] = torch.argmax(logits[:, 2]).item() return self._labels[label_id]
635
1
"""simple docstring""" def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> str: _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 # if input_string is "aba" than new_input_string become "a|b|a" _SCREAMING_SNAKE_CASE : List[str] = """""" _SCREAMING_SNAKE_CASE : Dict = """""" # append each character + "|" in new_string for range(0, length-1) for i in input_string[: len(__SCREAMING_SNAKE_CASE ) - 1]: new_input_string += i + "|" # append last character new_input_string += input_string[-1] # we will store the starting and ending of previous furthest ending palindromic # substring _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = 0, 0 # length[i] shows the length of palindromic substring with center i _SCREAMING_SNAKE_CASE : str = [1 for i in range(len(__SCREAMING_SNAKE_CASE ) )] # for each character in new_string find corresponding palindromic string _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for j in range(len(__SCREAMING_SNAKE_CASE ) ): _SCREAMING_SNAKE_CASE : str = 1 if j > r else min(length[l + r - j] // 2 , r - j + 1 ) while ( j - k >= 0 and j + k < len(__SCREAMING_SNAKE_CASE ) and new_input_string[k + j] == new_input_string[j - k] ): k += 1 _SCREAMING_SNAKE_CASE : List[Any] = 2 * k - 1 # does this string is ending after the previously explored end (that is r) ? # if yes the update the new r to the last index of this if j + k - 1 > r: _SCREAMING_SNAKE_CASE : List[str] = j - k + 1 # noqa: E741 _SCREAMING_SNAKE_CASE : str = j + k - 1 # update max_length and start position if max_length < length[j]: _SCREAMING_SNAKE_CASE : Optional[int] = length[j] _SCREAMING_SNAKE_CASE : Any = j # create that string _SCREAMING_SNAKE_CASE : Dict = new_input_string[start - max_length // 2 : start + max_length // 2 + 1] for i in s: if i != "|": output_string += i return output_string if __name__ == "__main__": import doctest doctest.testmod()
635
"""simple docstring""" import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class _snake_case ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = AutoImageProcessor.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""") _SCREAMING_SNAKE_CASE : str = AutoModelForImageClassification.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""") model.to(_A) from datasets import load_dataset _SCREAMING_SNAKE_CASE : Any = load_dataset("""nielsr/rvlcdip-demo""") _SCREAMING_SNAKE_CASE : Any = dataset["""train"""][0]["""image"""].convert("""RGB""") _SCREAMING_SNAKE_CASE : str = image_processor(_A , return_tensors="""pt""").to(_A) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE : Any = model(**_A) _SCREAMING_SNAKE_CASE : List[Any] = outputs.logits _SCREAMING_SNAKE_CASE : List[str] = torch.Size((1, 1_6)) self.assertEqual(logits.shape , _A) _SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [-0.4_158, -0.4_092, -0.4_347] , device=_A , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , _A , atol=1e-4))
635
1
"""simple docstring""" import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import numpy as np import pandas as pd from datasets import load_dataset import transformers from transformers import ( AutoConfig, BartForSequenceClassification, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, TapexTokenizer, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.17.0.dev0''') require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/text-classification/requirements.txt''') lowerCAmelCase_ = logging.getLogger(__name__) @dataclass class _snake_case : """simple docstring""" a = field( default="tab_fact" , metadata={"help": "The name of the dataset to use (via the datasets library)."} ) a = field( default="tab_fact" , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} , ) a = field( default=10_24 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) a = field( default=__snake_case , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) a = field( default=__snake_case , 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." ) } , ) a = field( default=__snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) a = field( default=__snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) a = field( default=__snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) } , ) a = field( default=__snake_case , metadata={"help": "A csv or a json file containing the training data."} ) a = field( default=__snake_case , metadata={"help": "A csv or a json file containing the validation data."} ) a = field(default=__snake_case , metadata={"help": "A csv or a json file containing the test data."} ) def _lowerCAmelCase ( self : List[str]): """simple docstring""" if self.dataset_name is not None: pass elif self.train_file is None or self.validation_file is None: raise ValueError("""Need either a GLUE task, a training/validation file or a dataset name.""") else: _SCREAMING_SNAKE_CASE : Optional[int] = self.train_file.split(""".""")[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." _SCREAMING_SNAKE_CASE : str = self.validation_file.split(""".""")[-1] assert ( validation_extension == train_extension ), "`validation_file` should have the same extension (csv or json) as `train_file`." @dataclass class _snake_case : """simple docstring""" a = field( default=__snake_case , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) a = field( default=__snake_case , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) a = field( default=__snake_case , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) a = field( default=__snake_case , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) a = field( default=__snake_case , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) a = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) a = field( default=__snake_case , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) def lowerCamelCase_()-> List[str]: # 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. _SCREAMING_SNAKE_CASE : Dict = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args_into_dataclasses() # 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 )] , ) _SCREAMING_SNAKE_CASE : int = training_args.get_process_log_level() logger.setLevel(__SCREAMING_SNAKE_CASE ) datasets.utils.logging.set_verbosity(__SCREAMING_SNAKE_CASE ) transformers.utils.logging.set_verbosity(__SCREAMING_SNAKE_CASE ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(F"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. _SCREAMING_SNAKE_CASE : Dict = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _SCREAMING_SNAKE_CASE : int = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # # For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table. # # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. 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. _SCREAMING_SNAKE_CASE : str = load_dataset( data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) else: # Loading a dataset from your local files. # CSV/JSON training and evaluation files are needed. _SCREAMING_SNAKE_CASE : Dict = {"""train""": data_args.train_file, """validation""": data_args.validation_file} # Get the test dataset: you can provide your own CSV/JSON test file (see below) # when you use `do_predict` without specifying a GLUE benchmark task. if training_args.do_predict: if data_args.test_file is not None: _SCREAMING_SNAKE_CASE : Tuple = data_args.train_file.split(""".""" )[-1] _SCREAMING_SNAKE_CASE : Dict = data_args.test_file.split(""".""" )[-1] assert ( test_extension == train_extension ), "`test_file` should have the same extension (csv or json) as `train_file`." _SCREAMING_SNAKE_CASE : Dict = data_args.test_file else: raise ValueError("""Need either a GLUE task or a test file for `do_predict`.""" ) for key in data_files.keys(): logger.info(F"""load a local file for {key}: {data_files[key]}""" ) if data_args.train_file.endswith(""".csv""" ): # Loading a dataset from local csv files _SCREAMING_SNAKE_CASE : Optional[int] = load_dataset("""csv""" , data_files=__SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir ) else: # Loading a dataset from local json files _SCREAMING_SNAKE_CASE : int = load_dataset("""json""" , data_files=__SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir ) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. # Labels _SCREAMING_SNAKE_CASE : Union[str, Any] = raw_datasets["""train"""].features["""label"""].names _SCREAMING_SNAKE_CASE : Dict = len(__SCREAMING_SNAKE_CASE ) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # load tapex tokenizer _SCREAMING_SNAKE_CASE : str = TapexTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , add_prefix_space=__SCREAMING_SNAKE_CASE , ) _SCREAMING_SNAKE_CASE : List[Any] = BartForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # Padding strategy if data_args.pad_to_max_length: _SCREAMING_SNAKE_CASE : Optional[int] = """max_length""" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch _SCREAMING_SNAKE_CASE : List[str] = False # Some models have set the order of the labels to use, so let's make sure we do use it. _SCREAMING_SNAKE_CASE : int = {"""Refused""": 0, """Entailed""": 1} _SCREAMING_SNAKE_CASE : Dict = {0: """Refused""", 1: """Entailed"""} if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( F"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" F"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) _SCREAMING_SNAKE_CASE : List[str] = min(data_args.max_seq_length , tokenizer.model_max_length ) def preprocess_tabfact_function(__SCREAMING_SNAKE_CASE ): # Tokenize the texts def _convert_table_text_to_pandas(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = [_table_row.split("""#""" ) for _table_row in _table_text.strip("""\n""" ).split("""\n""" )] _SCREAMING_SNAKE_CASE : List[Any] = pd.DataFrame.from_records(_table_content[1:] , columns=_table_content[0] ) return _table_pd _SCREAMING_SNAKE_CASE : Any = examples["""statement"""] _SCREAMING_SNAKE_CASE : Any = list(map(_convert_table_text_to_pandas , examples["""table_text"""] ) ) _SCREAMING_SNAKE_CASE : Any = tokenizer(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[int] = examples["""label"""] return result with training_args.main_process_first(desc="""dataset map pre-processing""" ): _SCREAMING_SNAKE_CASE : int = raw_datasets.map( __SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on dataset""" , ) if training_args.do_train: if "train" not in raw_datasets: raise ValueError("""--do_train requires a train dataset""" ) _SCREAMING_SNAKE_CASE : Optional[int] = raw_datasets["""train"""] if data_args.max_train_samples is not None: _SCREAMING_SNAKE_CASE : List[str] = train_dataset.select(range(data_args.max_train_samples ) ) if training_args.do_eval: if "validation" not in raw_datasets and "validation_matched" not in raw_datasets: raise ValueError("""--do_eval requires a validation dataset""" ) _SCREAMING_SNAKE_CASE : List[Any] = raw_datasets["""validation"""] if data_args.max_eval_samples is not None: _SCREAMING_SNAKE_CASE : List[str] = eval_dataset.select(range(data_args.max_eval_samples ) ) if training_args.do_predict or data_args.test_file is not None: if "test" not in raw_datasets and "test_matched" not in raw_datasets: raise ValueError("""--do_predict requires a test dataset""" ) _SCREAMING_SNAKE_CASE : Any = raw_datasets["""test"""] if data_args.max_predict_samples is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = predict_dataset.select(range(data_args.max_predict_samples ) ) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(__SCREAMING_SNAKE_CASE ) ) , 3 ): logger.info(F"""Sample {index} of the training set: {train_dataset[index]}.""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = p.predictions[0] if isinstance(p.predictions , __SCREAMING_SNAKE_CASE ) else p.predictions _SCREAMING_SNAKE_CASE : Any = np.argmax(__SCREAMING_SNAKE_CASE , axis=1 ) return {"accuracy": (preds == p.label_ids).astype(np.floataa ).mean().item()} # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: _SCREAMING_SNAKE_CASE : List[Any] = default_data_collator elif training_args.fpaa: _SCREAMING_SNAKE_CASE : Optional[int] = DataCollatorWithPadding(__SCREAMING_SNAKE_CASE , pad_to_multiple_of=8 ) else: _SCREAMING_SNAKE_CASE : List[str] = None # Initialize our Trainer _SCREAMING_SNAKE_CASE : str = Trainer( model=__SCREAMING_SNAKE_CASE , args=__SCREAMING_SNAKE_CASE , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE , data_collator=__SCREAMING_SNAKE_CASE , ) # Training if training_args.do_train: _SCREAMING_SNAKE_CASE : str = None if training_args.resume_from_checkpoint is not None: _SCREAMING_SNAKE_CASE : Tuple = training_args.resume_from_checkpoint elif last_checkpoint is not None: _SCREAMING_SNAKE_CASE : int = last_checkpoint _SCREAMING_SNAKE_CASE : Tuple = trainer.train(resume_from_checkpoint=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[str] = train_result.metrics _SCREAMING_SNAKE_CASE : List[str] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__SCREAMING_SNAKE_CASE ) ) _SCREAMING_SNAKE_CASE : List[str] = min(__SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics("""train""" , __SCREAMING_SNAKE_CASE ) trainer.save_metrics("""train""" , __SCREAMING_SNAKE_CASE ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) _SCREAMING_SNAKE_CASE : List[str] = trainer.evaluate(eval_dataset=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Any = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Any = min(__SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE ) ) trainer.log_metrics("""eval""" , __SCREAMING_SNAKE_CASE ) trainer.save_metrics("""eval""" , __SCREAMING_SNAKE_CASE ) if training_args.do_predict: logger.info("""*** Predict ***""" ) # Removing the `label` columns because it contains -1 and Trainer won't like that. _SCREAMING_SNAKE_CASE : Any = predict_dataset.remove_columns("""label""" ) _SCREAMING_SNAKE_CASE : Optional[Any] = trainer.predict(__SCREAMING_SNAKE_CASE , metric_key_prefix="""predict""" ).predictions _SCREAMING_SNAKE_CASE : Any = np.argmax(__SCREAMING_SNAKE_CASE , axis=1 ) _SCREAMING_SNAKE_CASE : int = os.path.join(training_args.output_dir , """predict_results_tabfact.txt""" ) if trainer.is_world_process_zero(): with open(__SCREAMING_SNAKE_CASE , """w""" ) as writer: logger.info("""***** Predict Results *****""" ) writer.write("""index\tprediction\n""" ) for index, item in enumerate(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = label_list[item] writer.write(F"""{index}\t{item}\n""" ) _SCREAMING_SNAKE_CASE : Any = {"""finetuned_from""": model_args.model_name_or_path, """tasks""": """text-classification"""} if training_args.push_to_hub: trainer.push_to_hub(**__SCREAMING_SNAKE_CASE ) else: trainer.create_model_card(**__SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> List[str]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
635
"""simple docstring""" import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class _snake_case ( __snake_case ): """simple docstring""" a = "M-CLIP" def __init__( self : Optional[Any] , _A : List[str]=1_0_2_4 , _A : Union[str, Any]=7_6_8 , **_A : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = transformerDimSize _SCREAMING_SNAKE_CASE : List[str] = imageDimSize super().__init__(**_A) class _snake_case ( __snake_case ): """simple docstring""" a = MCLIPConfig def __init__( self : Dict , _A : Optional[Any] , *_A : Any , **_A : Dict): """simple docstring""" super().__init__(_A , *_A , **_A) _SCREAMING_SNAKE_CASE : Tuple = XLMRobertaModel(_A) _SCREAMING_SNAKE_CASE : List[Any] = torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims) def _lowerCAmelCase ( self : Union[str, Any] , _A : str , _A : int): """simple docstring""" _SCREAMING_SNAKE_CASE : str = self.transformer(input_ids=_A , attention_mask=_A)[0] _SCREAMING_SNAKE_CASE : Optional[Any] = (embs * attention_mask.unsqueeze(2)).sum(dim=1) / attention_mask.sum(dim=1)[:, None] return self.LinearTransformation(_A), embs
635
1
"""simple docstring""" import argparse import torch from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[Any]: # Initialise PyTorch model _SCREAMING_SNAKE_CASE : List[str] = FunnelConfig.from_json_file(__SCREAMING_SNAKE_CASE ) print(F"""Building PyTorch model from configuration: {config}""" ) _SCREAMING_SNAKE_CASE : str = FunnelBaseModel(__SCREAMING_SNAKE_CASE ) if base_model else FunnelModel(__SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_funnel(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--base_model''', action='''store_true''', help='''Whether you want just the base model (no decoder) or not.''' ) lowerCAmelCase_ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model )
635
"""simple docstring""" from decimal import Decimal, getcontext from math import ceil, factorial def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> str: if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise TypeError("""Undefined for non-integers""" ) elif precision < 1: raise ValueError("""Undefined for non-natural numbers""" ) _SCREAMING_SNAKE_CASE : int = precision _SCREAMING_SNAKE_CASE : Dict = ceil(precision / 14 ) _SCREAMING_SNAKE_CASE : int = 426_880 * Decimal(10_005 ).sqrt() _SCREAMING_SNAKE_CASE : Union[str, Any] = 1 _SCREAMING_SNAKE_CASE : str = 13_591_409 _SCREAMING_SNAKE_CASE : Tuple = Decimal(__SCREAMING_SNAKE_CASE ) for k in range(1 , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = factorial(6 * k ) // (factorial(3 * k ) * factorial(__SCREAMING_SNAKE_CASE ) ** 3) linear_term += 545_140_134 exponential_term *= -262_537_412_640_768_000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": lowerCAmelCase_ = 50 print(F"The first {n} digits of pi is: {pi(n)}")
635
1
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_camembert import CamembertTokenizer else: lowerCAmelCase_ = None lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} lowerCAmelCase_ = { '''vocab_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model''', }, '''tokenizer_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/tokenizer.json''', }, } lowerCAmelCase_ = { '''camembert-base''': 512, } lowerCAmelCase_ = '''▁''' class _snake_case ( __snake_case ): """simple docstring""" a = VOCAB_FILES_NAMES a = PRETRAINED_VOCAB_FILES_MAP a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a = ["input_ids", "attention_mask"] a = CamembertTokenizer def __init__( self : str , _A : Optional[int]=None , _A : List[str]=None , _A : int="<s>" , _A : Union[str, Any]="</s>" , _A : List[Any]="</s>" , _A : List[Any]="<s>" , _A : Union[str, Any]="<unk>" , _A : Tuple="<pad>" , _A : Any="<mask>" , _A : Optional[int]=["<s>NOTUSED", "</s>NOTUSED"] , **_A : Dict , ): """simple docstring""" _SCREAMING_SNAKE_CASE : str = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else mask_token super().__init__( _A , tokenizer_file=_A , bos_token=_A , eos_token=_A , sep_token=_A , cls_token=_A , unk_token=_A , pad_token=_A , mask_token=_A , additional_special_tokens=_A , **_A , ) _SCREAMING_SNAKE_CASE : Optional[Any] = vocab_file _SCREAMING_SNAKE_CASE : Union[str, Any] = False if not self.vocab_file else True def _lowerCAmelCase ( self : Any , _A : List[int] , _A : Optional[List[int]] = None): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _SCREAMING_SNAKE_CASE : Tuple = [self.cls_token_id] _SCREAMING_SNAKE_CASE : Optional[Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _lowerCAmelCase ( self : List[Any] , _A : List[int] , _A : Optional[List[int]] = None): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = [self.sep_token_id] _SCREAMING_SNAKE_CASE : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0] def _lowerCAmelCase ( self : Dict , _A : str , _A : Optional[str] = None): """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""") if not os.path.isdir(_A): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""") return _SCREAMING_SNAKE_CASE : Dict = os.path.join( _A , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]) if os.path.abspath(self.vocab_file) != os.path.abspath(_A): copyfile(self.vocab_file , _A) return (out_vocab_file,)
635
"""simple docstring""" import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file _SCREAMING_SNAKE_CASE : Optional[int] = TapasConfig.from_json_file(__SCREAMING_SNAKE_CASE ) # set absolute/relative position embeddings parameter _SCREAMING_SNAKE_CASE : Dict = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": _SCREAMING_SNAKE_CASE : str = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "WTQ": # run_task_main.py hparams _SCREAMING_SNAKE_CASE : Optional[int] = 4 _SCREAMING_SNAKE_CASE : Any = True # hparam_utils.py hparams _SCREAMING_SNAKE_CASE : Any = 0.66_46_94 _SCREAMING_SNAKE_CASE : str = 0.20_79_51 _SCREAMING_SNAKE_CASE : str = 0.12_11_94 _SCREAMING_SNAKE_CASE : List[Any] = True _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = 0.0_35_25_13 _SCREAMING_SNAKE_CASE : Optional[Any] = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams _SCREAMING_SNAKE_CASE : int = 4 _SCREAMING_SNAKE_CASE : Tuple = False # hparam_utils.py hparams _SCREAMING_SNAKE_CASE : Any = 36.45_19 _SCREAMING_SNAKE_CASE : Union[str, Any] = 0.90_34_21 _SCREAMING_SNAKE_CASE : Optional[Any] = 2_22.0_88 _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Optional[int] = True _SCREAMING_SNAKE_CASE : Dict = 0.76_31_41 _SCREAMING_SNAKE_CASE : Union[str, Any] = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "TABFACT": _SCREAMING_SNAKE_CASE : int = TapasForSequenceClassification(config=__SCREAMING_SNAKE_CASE ) elif task == "MLM": _SCREAMING_SNAKE_CASE : int = TapasForMaskedLM(config=__SCREAMING_SNAKE_CASE ) elif task == "INTERMEDIATE_PRETRAINING": _SCREAMING_SNAKE_CASE : int = TapasModel(config=__SCREAMING_SNAKE_CASE ) else: raise ValueError(F"""Task {task} not supported.""" ) print(F"""Building PyTorch model from configuration: {config}""" ) # Load weights from tf checkpoint load_tf_weights_in_tapas(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Save pytorch-model (weights and configuration) print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) # Save tokenizer files print(F"""Save tokenizer files to {pytorch_dump_path}""" ) _SCREAMING_SNAKE_CASE : str = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + """vocab.txt""" , model_max_length=512 ) tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) print("""Used relative position embeddings:""" , model.config.reset_position_index_per_cell ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--task''', default='''SQA''', type=str, help='''Model task for which to convert a checkpoint. Defaults to SQA.''' ) parser.add_argument( '''--reset_position_index_per_cell''', default=False, action='''store_true''', help='''Whether to use relative position embeddings or not. Defaults to True.''', ) parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--tapas_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained TAPAS model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) lowerCAmelCase_ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
635
1
"""simple docstring""" import qiskit def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> qiskit.result.counts.Counts: _SCREAMING_SNAKE_CASE : Any = qiskit.Aer.get_backend("""aer_simulator""" ) # Create a Quantum Circuit acting on the q register _SCREAMING_SNAKE_CASE : List[str] = qiskit.QuantumCircuit(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator _SCREAMING_SNAKE_CASE : Any = qiskit.execute(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , shots=1_000 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(F"Total count for various states are: {single_qubit_measure(1, 1)}")
635
"""simple docstring""" from typing import Any import numpy as np def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> bool: return np.array_equal(__SCREAMING_SNAKE_CASE , matrix.conjugate().T ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Any: _SCREAMING_SNAKE_CASE : Optional[int] = v.conjugate().T _SCREAMING_SNAKE_CASE : Optional[int] = v_star.dot(__SCREAMING_SNAKE_CASE ) assert isinstance(__SCREAMING_SNAKE_CASE , np.ndarray ) return (v_star_dot.dot(__SCREAMING_SNAKE_CASE )) / (v_star.dot(__SCREAMING_SNAKE_CASE )) def lowerCamelCase_()-> None: _SCREAMING_SNAKE_CASE : Optional[Any] = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) _SCREAMING_SNAKE_CASE : int = np.array([[1], [2], [3]] ) assert is_hermitian(__SCREAMING_SNAKE_CASE ), F"""{a} is not hermitian.""" print(rayleigh_quotient(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) _SCREAMING_SNAKE_CASE : int = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(__SCREAMING_SNAKE_CASE ), F"""{a} is not hermitian.""" assert rayleigh_quotient(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
635
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { '''configuration_lilt''': ['''LILT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LiltConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''LILT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LiltForQuestionAnswering''', '''LiltForSequenceClassification''', '''LiltForTokenClassification''', '''LiltModel''', '''LiltPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
"""simple docstring""" from __future__ import annotations def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , )-> tuple: if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError("""You cannot supply more or less than 2 values""" ) elif electron_conc < 0: raise ValueError("""Electron concentration cannot be negative in a semiconductor""" ) elif hole_conc < 0: raise ValueError("""Hole concentration cannot be negative in a semiconductor""" ) elif intrinsic_conc < 0: raise ValueError( """Intrinsic concentration cannot be negative in a semiconductor""" ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
635
1
"""simple docstring""" def lowerCamelCase_(__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()
635
"""simple docstring""" import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCAmelCase_ = 16 lowerCAmelCase_ = 32 def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 16 )-> str: _SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetDict( { """train""": dataset["""train"""].select(__SCREAMING_SNAKE_CASE ), """validation""": dataset["""train"""].select(__SCREAMING_SNAKE_CASE ), """test""": dataset["""validation"""], } ) def tokenize_function(__SCREAMING_SNAKE_CASE ): # max_length=None => use the model max length (it's actually the default) _SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _SCREAMING_SNAKE_CASE : str = datasets.map( __SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _SCREAMING_SNAKE_CASE : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__SCREAMING_SNAKE_CASE ): # On TPU it's best to pad everything to the same length or training will be very slow. _SCREAMING_SNAKE_CASE : Any = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _SCREAMING_SNAKE_CASE : Optional[Any] = 16 elif accelerator.mixed_precision != "no": _SCREAMING_SNAKE_CASE : Any = 8 else: _SCREAMING_SNAKE_CASE : Optional[int] = None return tokenizer.pad( __SCREAMING_SNAKE_CASE , padding="""longest""" , max_length=__SCREAMING_SNAKE_CASE , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" , ) # Instantiate dataloaders. _SCREAMING_SNAKE_CASE : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__SCREAMING_SNAKE_CASE , collate_fn=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[int] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__SCREAMING_SNAKE_CASE , collate_fn=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = DataLoader( tokenized_datasets["""test"""] , shuffle=__SCREAMING_SNAKE_CASE , collate_fn=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE ) return train_dataloader, eval_dataloader, test_dataloader def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: # New Code # _SCREAMING_SNAKE_CASE : Union[str, Any] = [] # Download the dataset _SCREAMING_SNAKE_CASE : Union[str, Any] = load_dataset("""glue""" , """mrpc""" ) # Create our splits _SCREAMING_SNAKE_CASE : Dict = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator _SCREAMING_SNAKE_CASE : Any = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _SCREAMING_SNAKE_CASE : Tuple = config["""lr"""] _SCREAMING_SNAKE_CASE : Tuple = int(config["""num_epochs"""] ) _SCREAMING_SNAKE_CASE : int = int(config["""seed"""] ) _SCREAMING_SNAKE_CASE : int = int(config["""batch_size"""] ) _SCREAMING_SNAKE_CASE : List[str] = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation _SCREAMING_SNAKE_CASE : Any = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _SCREAMING_SNAKE_CASE : List[str] = batch_size // MAX_GPU_BATCH_SIZE _SCREAMING_SNAKE_CASE : List[str] = MAX_GPU_BATCH_SIZE set_seed(__SCREAMING_SNAKE_CASE ) # New Code # # Create our folds: _SCREAMING_SNAKE_CASE : List[str] = kfold.split(np.zeros(datasets["""train"""].num_rows ) , datasets["""train"""]["""label"""] ) _SCREAMING_SNAKE_CASE : Optional[Any] = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = get_fold_dataloaders( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _SCREAMING_SNAKE_CASE : Any = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__SCREAMING_SNAKE_CASE ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _SCREAMING_SNAKE_CASE : Tuple = model.to(accelerator.device ) # Instantiate optimizer _SCREAMING_SNAKE_CASE : int = AdamW(params=model.parameters() , lr=__SCREAMING_SNAKE_CASE ) # Instantiate scheduler _SCREAMING_SNAKE_CASE : int = get_linear_schedule_with_warmup( optimizer=__SCREAMING_SNAKE_CASE , num_warmup_steps=100 , num_training_steps=(len(__SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = accelerator.prepare( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Now we train the model for epoch in range(__SCREAMING_SNAKE_CASE ): model.train() for step, batch in enumerate(__SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _SCREAMING_SNAKE_CASE : Optional[Any] = model(**__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = outputs.loss _SCREAMING_SNAKE_CASE : List[Any] = loss / gradient_accumulation_steps accelerator.backward(__SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[str] = model(**__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : str = outputs.logits.argmax(dim=-1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__SCREAMING_SNAKE_CASE , references=__SCREAMING_SNAKE_CASE , ) _SCREAMING_SNAKE_CASE : Optional[int] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , __SCREAMING_SNAKE_CASE ) # New Code # # We also run predictions on the test set at the very end _SCREAMING_SNAKE_CASE : str = [] for step, batch in enumerate(__SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[str] = model(**__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[Any] = outputs.logits _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(__SCREAMING_SNAKE_CASE , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: _SCREAMING_SNAKE_CASE : Optional[int] = torch.cat(__SCREAMING_SNAKE_CASE , dim=0 ) _SCREAMING_SNAKE_CASE : List[str] = torch.stack(__SCREAMING_SNAKE_CASE , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) _SCREAMING_SNAKE_CASE : int = metric.compute(predictions=__SCREAMING_SNAKE_CASE , references=__SCREAMING_SNAKE_CASE ) accelerator.print("""Average test metrics from all folds:""" , __SCREAMING_SNAKE_CASE ) def lowerCamelCase_()-> Optional[Any]: _SCREAMING_SNAKE_CASE : Any = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) # New Code # parser.add_argument("""--num_folds""" , type=__SCREAMING_SNAKE_CASE , default=3 , help="""The number of splits to perform across the dataset""" ) _SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args() _SCREAMING_SNAKE_CASE : Optional[int] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
635
1
"""simple docstring""" import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = ["""a""", """b""", """c"""] # Defaults to last layer if both are None _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = get_aligned_output_features_output_indices(_A , _A , _A) self.assertEqual(_A , ["""c"""]) self.assertEqual(_A , [2]) # Out indices set to match out features _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = get_aligned_output_features_output_indices(["""a""", """c"""] , _A , _A) self.assertEqual(_A , ["""a""", """c"""]) self.assertEqual(_A , [0, 2]) # Out features set to match out indices _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = get_aligned_output_features_output_indices(_A , [0, 2] , _A) self.assertEqual(_A , ["""a""", """c"""]) self.assertEqual(_A , [0, 2]) # Out features selected from negative indices _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = get_aligned_output_features_output_indices(_A , [-3, -1] , _A) self.assertEqual(_A , ["""a""", """c"""]) self.assertEqual(_A , [-3, -1]) def _lowerCAmelCase ( self : Tuple): """simple docstring""" with self.assertRaises(_A): verify_out_features_out_indices(["""a""", """b"""] , (0, 1) , _A) # Out features must be a list with self.assertRaises(_A): verify_out_features_out_indices(("""a""", """b""") , (0, 1) , ["""a""", """b"""]) # Out features must be a subset of stage names with self.assertRaises(_A): verify_out_features_out_indices(["""a""", """b"""] , (0, 1) , ["""a"""]) # Out indices must be a list or tuple with self.assertRaises(_A): verify_out_features_out_indices(_A , 0 , ["""a""", """b"""]) # Out indices must be a subset of stage names with self.assertRaises(_A): verify_out_features_out_indices(_A , (0, 1) , ["""a"""]) # Out features and out indices must be the same length with self.assertRaises(_A): verify_out_features_out_indices(["""a""", """b"""] , (0,) , ["""a""", """b""", """c"""]) # Out features should match out indices with self.assertRaises(_A): verify_out_features_out_indices(["""a""", """b"""] , (0, 2) , ["""a""", """b""", """c"""]) # Out features and out indices should be in order with self.assertRaises(_A): verify_out_features_out_indices(["""b""", """a"""] , (0, 1) , ["""a""", """b"""]) # Check passes with valid inputs verify_out_features_out_indices(["""a""", """b""", """d"""] , (0, 1, -1) , ["""a""", """b""", """c""", """d"""]) def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = BackboneMixin() _SCREAMING_SNAKE_CASE : List[str] = ["""a""", """b""", """c"""] _SCREAMING_SNAKE_CASE : Optional[int] = ["""a""", """c"""] _SCREAMING_SNAKE_CASE : Union[str, Any] = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ["""a""", """c"""]) self.assertEqual(backbone.out_indices , [0, 2]) # Check out features and indices are updated correctly _SCREAMING_SNAKE_CASE : Optional[Any] = ["""a""", """b"""] self.assertEqual(backbone.out_features , ["""a""", """b"""]) self.assertEqual(backbone.out_indices , [0, 1]) _SCREAMING_SNAKE_CASE : Optional[Any] = [-3, -1] self.assertEqual(backbone.out_features , ["""a""", """c"""]) self.assertEqual(backbone.out_indices , [-3, -1])
635
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { '''configuration_clipseg''': [ '''CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPSegConfig''', '''CLIPSegTextConfig''', '''CLIPSegVisionConfig''', ], '''processing_clipseg''': ['''CLIPSegProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPSegModel''', '''CLIPSegPreTrainedModel''', '''CLIPSegTextModel''', '''CLIPSegVisionModel''', '''CLIPSegForImageSegmentation''', ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
1
"""simple docstring""" from __future__ import annotations import os from typing import Any import requests lowerCAmelCase_ = '''https://api.github.com''' # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user lowerCAmelCase_ = BASE_URL + '''/user''' # https://github.com/settings/tokens lowerCAmelCase_ = os.environ.get('''USER_TOKEN''', '''''') def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> dict[Any, Any]: _SCREAMING_SNAKE_CASE : int = { """Authorization""": F"""token {auth_token}""", """Accept""": """application/vnd.github.v3+json""", } return requests.get(__SCREAMING_SNAKE_CASE , headers=__SCREAMING_SNAKE_CASE ).json() if __name__ == "__main__": # pragma: no cover if USER_TOKEN: for key, value in fetch_github_info(USER_TOKEN).items(): print(F"{key}: {value}") else: raise ValueError('''\'USER_TOKEN\' field cannot be empty.''')
635
"""simple docstring""" import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class _snake_case : """simple docstring""" def __init__( self : int , _A : List[Any] , _A : int , _A : int): """simple docstring""" if dst_width < 0 or dst_height < 0: raise ValueError("""Destination width/height should be > 0""") _SCREAMING_SNAKE_CASE : str = img _SCREAMING_SNAKE_CASE : Optional[Any] = img.shape[1] _SCREAMING_SNAKE_CASE : Tuple = img.shape[0] _SCREAMING_SNAKE_CASE : Any = dst_width _SCREAMING_SNAKE_CASE : Any = dst_height _SCREAMING_SNAKE_CASE : Any = self.src_w / self.dst_w _SCREAMING_SNAKE_CASE : Dict = self.src_h / self.dst_h _SCREAMING_SNAKE_CASE : Optional[Any] = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta) * 2_5_5 ) def _lowerCAmelCase ( self : Tuple): """simple docstring""" for i in range(self.dst_h): for j in range(self.dst_w): _SCREAMING_SNAKE_CASE : Any = self.img[self.get_y(_A)][self.get_x(_A)] def _lowerCAmelCase ( self : int , _A : int): """simple docstring""" return int(self.ratio_x * x) def _lowerCAmelCase ( self : str , _A : int): """simple docstring""" return int(self.ratio_y * y) if __name__ == "__main__": lowerCAmelCase_ , lowerCAmelCase_ = 800, 600 lowerCAmelCase_ = imread('''image_data/lena.jpg''', 1) lowerCAmelCase_ = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}", n.output ) waitKey(0) destroyAllWindows()
635
1
"""simple docstring""" import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel lowerCAmelCase_ = { '''text_branch''': '''text_model''', '''audio_branch''': '''audio_model.audio_encoder''', '''attn''': '''attention.self''', '''self.proj''': '''output.dense''', '''attention.self_mask''': '''attn_mask''', '''mlp.fc1''': '''intermediate.dense''', '''mlp.fc2''': '''output.dense''', '''norm1''': '''layernorm_before''', '''norm2''': '''layernorm_after''', '''bn0''': '''batch_norm''', } lowerCAmelCase_ = AutoFeatureExtractor.from_pretrained('''laion/clap-htsat-unfused''', truncation='''rand_trunc''') def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False )-> str: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = create_model( """HTSAT-tiny""" , """roberta""" , __SCREAMING_SNAKE_CASE , precision="""fp32""" , device="""cuda:0""" if torch.cuda.is_available() else """cpu""" , enable_fusion=__SCREAMING_SNAKE_CASE , fusion_type="""aff_2d""" if enable_fusion else None , ) return model, model_cfg def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = {} _SCREAMING_SNAKE_CASE : Optional[Any] = R""".*sequential.(\d+).*""" _SCREAMING_SNAKE_CASE : Any = R""".*_projection.(\d+).*""" for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: _SCREAMING_SNAKE_CASE : Optional[Any] = key.replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # replace sequential layers with list _SCREAMING_SNAKE_CASE : List[Any] = re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).group(1 ) _SCREAMING_SNAKE_CASE : Dict = key.replace(F"""sequential.{sequential_layer}.""" , F"""layers.{int(__SCREAMING_SNAKE_CASE )//3}.linear.""" ) elif re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = int(re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... _SCREAMING_SNAKE_CASE : Dict = 1 if projecton_layer == 0 else 2 _SCREAMING_SNAKE_CASE : Union[str, Any] = key.replace(F"""_projection.{projecton_layer}.""" , F"""_projection.linear{transformers_projection_layer}.""" ) if "audio" and "qkv" in key: # split qkv into query key and value _SCREAMING_SNAKE_CASE : Dict = value _SCREAMING_SNAKE_CASE : List[Any] = mixed_qkv.size(0 ) // 3 _SCREAMING_SNAKE_CASE : Optional[Any] = mixed_qkv[:qkv_dim] _SCREAMING_SNAKE_CASE : str = mixed_qkv[qkv_dim : qkv_dim * 2] _SCREAMING_SNAKE_CASE : Any = mixed_qkv[qkv_dim * 2 :] _SCREAMING_SNAKE_CASE : Dict = query_layer _SCREAMING_SNAKE_CASE : List[Any] = key_layer _SCREAMING_SNAKE_CASE : Dict = value_layer else: _SCREAMING_SNAKE_CASE : Optional[Any] = value return model_state_dict def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False )-> List[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = init_clap(__SCREAMING_SNAKE_CASE , enable_fusion=__SCREAMING_SNAKE_CASE ) clap_model.eval() _SCREAMING_SNAKE_CASE : Dict = clap_model.state_dict() _SCREAMING_SNAKE_CASE : Tuple = rename_state_dict(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : int = ClapConfig() _SCREAMING_SNAKE_CASE : Tuple = enable_fusion _SCREAMING_SNAKE_CASE : Dict = ClapModel(__SCREAMING_SNAKE_CASE ) # ignore the spectrogram embedding layer model.load_state_dict(__SCREAMING_SNAKE_CASE , strict=__SCREAMING_SNAKE_CASE ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) transformers_config.save_pretrained(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = 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('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument('''--enable_fusion''', action='''store_true''', help='''Whether to enable fusion or not''') lowerCAmelCase_ = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
635
"""simple docstring""" import argparse from collections import defaultdict def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> int: _SCREAMING_SNAKE_CASE : str = F"""{file}_{class_name}_{test_name}""" done_test[_id] += 1 with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: _SCREAMING_SNAKE_CASE : Union[str, Any] = f.readlines() _SCREAMING_SNAKE_CASE : Optional[Any] = F"""class {class_name}(""" _SCREAMING_SNAKE_CASE : List[Any] = F"""{4 * " "}def {test_name}(""" _SCREAMING_SNAKE_CASE : Tuple = F"""{8 * " "}{correct_line.split()[0]}""" _SCREAMING_SNAKE_CASE : List[Any] = F"""{16 * " "}{correct_line.split()[0]}""" _SCREAMING_SNAKE_CASE : List[str] = False _SCREAMING_SNAKE_CASE : Tuple = False _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[int] = False _SCREAMING_SNAKE_CASE : Any = 0 _SCREAMING_SNAKE_CASE : Optional[Any] = 0 _SCREAMING_SNAKE_CASE : Dict = [] for line in lines: if line.startswith(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = True elif in_class and line.startswith(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = True elif in_class and in_func and (line.startswith(__SCREAMING_SNAKE_CASE ) or line.startswith(__SCREAMING_SNAKE_CASE )): _SCREAMING_SNAKE_CASE : Dict = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: _SCREAMING_SNAKE_CASE : int = True if in_class and in_func and in_line: if ")" not in line: continue else: _SCREAMING_SNAKE_CASE : Any = True if in_class and in_func and in_line and insert_line: new_lines.append(F"""{spaces * " "}{correct_line}""" ) _SCREAMING_SNAKE_CASE : Optional[int] = False else: new_lines.append(__SCREAMING_SNAKE_CASE ) with open(__SCREAMING_SNAKE_CASE , """w""" ) as f: for line in new_lines: f.write(__SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None )-> Optional[Any]: if fail is not None: with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: _SCREAMING_SNAKE_CASE : Union[str, Any] = {l.strip() for l in f.readlines()} else: _SCREAMING_SNAKE_CASE : str = None with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: _SCREAMING_SNAKE_CASE : str = f.readlines() _SCREAMING_SNAKE_CASE : str = defaultdict(__SCREAMING_SNAKE_CASE ) for line in correct_lines: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = line.split(""";""" ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument('''--correct_filename''', help='''filename of tests with expected result''') parser.add_argument('''--fail_filename''', help='''filename of test failures''', type=str, default=None) lowerCAmelCase_ = parser.parse_args() main(args.correct_filename, args.fail_filename)
635
1
"""simple docstring""" def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> int: if len(__SCREAMING_SNAKE_CASE ) != len(__SCREAMING_SNAKE_CASE ): raise ValueError("""String lengths must match!""" ) _SCREAMING_SNAKE_CASE : Optional[int] = 0 for chara, chara in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): if chara != chara: count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
635
"""simple docstring""" import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel lowerCAmelCase_ = { '''text_branch''': '''text_model''', '''audio_branch''': '''audio_model.audio_encoder''', '''attn''': '''attention.self''', '''self.proj''': '''output.dense''', '''attention.self_mask''': '''attn_mask''', '''mlp.fc1''': '''intermediate.dense''', '''mlp.fc2''': '''output.dense''', '''norm1''': '''layernorm_before''', '''norm2''': '''layernorm_after''', '''bn0''': '''batch_norm''', } lowerCAmelCase_ = AutoFeatureExtractor.from_pretrained('''laion/clap-htsat-unfused''', truncation='''rand_trunc''') def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False )-> str: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = create_model( """HTSAT-tiny""" , """roberta""" , __SCREAMING_SNAKE_CASE , precision="""fp32""" , device="""cuda:0""" if torch.cuda.is_available() else """cpu""" , enable_fusion=__SCREAMING_SNAKE_CASE , fusion_type="""aff_2d""" if enable_fusion else None , ) return model, model_cfg def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = {} _SCREAMING_SNAKE_CASE : Optional[Any] = R""".*sequential.(\d+).*""" _SCREAMING_SNAKE_CASE : Any = R""".*_projection.(\d+).*""" for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: _SCREAMING_SNAKE_CASE : Optional[Any] = key.replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # replace sequential layers with list _SCREAMING_SNAKE_CASE : List[Any] = re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).group(1 ) _SCREAMING_SNAKE_CASE : Dict = key.replace(F"""sequential.{sequential_layer}.""" , F"""layers.{int(__SCREAMING_SNAKE_CASE )//3}.linear.""" ) elif re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = int(re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... _SCREAMING_SNAKE_CASE : Dict = 1 if projecton_layer == 0 else 2 _SCREAMING_SNAKE_CASE : Union[str, Any] = key.replace(F"""_projection.{projecton_layer}.""" , F"""_projection.linear{transformers_projection_layer}.""" ) if "audio" and "qkv" in key: # split qkv into query key and value _SCREAMING_SNAKE_CASE : Dict = value _SCREAMING_SNAKE_CASE : List[Any] = mixed_qkv.size(0 ) // 3 _SCREAMING_SNAKE_CASE : Optional[Any] = mixed_qkv[:qkv_dim] _SCREAMING_SNAKE_CASE : str = mixed_qkv[qkv_dim : qkv_dim * 2] _SCREAMING_SNAKE_CASE : Any = mixed_qkv[qkv_dim * 2 :] _SCREAMING_SNAKE_CASE : Dict = query_layer _SCREAMING_SNAKE_CASE : List[Any] = key_layer _SCREAMING_SNAKE_CASE : Dict = value_layer else: _SCREAMING_SNAKE_CASE : Optional[Any] = value return model_state_dict def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False )-> List[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = init_clap(__SCREAMING_SNAKE_CASE , enable_fusion=__SCREAMING_SNAKE_CASE ) clap_model.eval() _SCREAMING_SNAKE_CASE : Dict = clap_model.state_dict() _SCREAMING_SNAKE_CASE : Tuple = rename_state_dict(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : int = ClapConfig() _SCREAMING_SNAKE_CASE : Tuple = enable_fusion _SCREAMING_SNAKE_CASE : Dict = ClapModel(__SCREAMING_SNAKE_CASE ) # ignore the spectrogram embedding layer model.load_state_dict(__SCREAMING_SNAKE_CASE , strict=__SCREAMING_SNAKE_CASE ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) transformers_config.save_pretrained(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = 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('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument('''--enable_fusion''', action='''store_true''', help='''Whether to enable fusion or not''') lowerCAmelCase_ = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
635
1
"""simple docstring""" def lowerCamelCase_()-> int: _SCREAMING_SNAKE_CASE : Optional[int] = [] _SCREAMING_SNAKE_CASE : Dict = 1 while len(__SCREAMING_SNAKE_CASE ) < 1e6: constant.append(str(__SCREAMING_SNAKE_CASE ) ) i += 1 _SCREAMING_SNAKE_CASE : int = """""".join(__SCREAMING_SNAKE_CASE ) return ( int(constant[0] ) * int(constant[9] ) * int(constant[99] ) * int(constant[999] ) * int(constant[9_999] ) * int(constant[99_999] ) * int(constant[999_999] ) ) if __name__ == "__main__": print(solution())
635
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import 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.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.g4dn.xlarge", "results": {"train_runtime": 6_50, "eval_accuracy": 0.6, "eval_loss": 0.9}, }, { "framework": "tensorflow", "script": "run_tf.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.g4dn.xlarge", "results": {"train_runtime": 6_00, "eval_accuracy": 0.3, "eval_loss": 0.9}, }, ] ) class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" 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=_A , ) assert hasattr(self , """env""") def _lowerCAmelCase ( self : Union[str, Any] , _A : str=1): """simple docstring""" 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}-single""" , instance_count=_A , instance_type=self.instance_type , debugger_hook_config=_A , hyperparameters={**self.env.hyperparameters, """model_name_or_path""": self.model_name_or_path} , metric_definitions=self.env.metric_definitions , py_version="""py36""" , ) def _lowerCAmelCase ( self : Union[str, Any] , _A : Union[str, Any]): """simple docstring""" TrainingJobAnalytics(_A).export_csv(f"""{self.env.test_path}/{job_name}_metrics.csv""") def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : str = self.create_estimator() # run training estimator.fit() # result dataframe _SCREAMING_SNAKE_CASE : Any = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis _SCREAMING_SNAKE_CASE : Any = list(result_metrics_df[result_metrics_df.metric_name == """eval_accuracy"""]["""value"""]) _SCREAMING_SNAKE_CASE : Tuple = list(result_metrics_df[result_metrics_df.metric_name == """eval_loss"""]["""value"""]) # get train time from SageMaker job, this includes starting, preprocessing, stopping _SCREAMING_SNAKE_CASE : int = ( 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} , _A)
635
1
"""simple docstring""" import string def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> str: _SCREAMING_SNAKE_CASE : str = """""" for i in sequence: _SCREAMING_SNAKE_CASE : int = ord(__SCREAMING_SNAKE_CASE ) if 65 <= extract <= 90: output += chr(155 - extract ) elif 97 <= extract <= 122: output += chr(219 - extract ) else: output += i return output def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> str: _SCREAMING_SNAKE_CASE : int = string.ascii_letters _SCREAMING_SNAKE_CASE : Optional[int] = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(__SCREAMING_SNAKE_CASE )] if c in letters else c for c in sequence ) def lowerCamelCase_()-> None: from timeit import timeit print("""Running performance benchmarks...""" ) _SCREAMING_SNAKE_CASE : Optional[int] = """from string import printable ; from __main__ import atbash, atbash_slow""" print(F"""> atbash_slow(): {timeit("atbash_slow(printable)" , setup=__SCREAMING_SNAKE_CASE )} seconds""" ) print(F"""> atbash(): {timeit("atbash(printable)" , setup=__SCREAMING_SNAKE_CASE )} seconds""" ) if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(F"{example} encrypted in atbash: {atbash(example)}") benchmark()
635
"""simple docstring""" import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip lowerCAmelCase_ = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> List[str]: if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Any: return max(metric_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for gt in ground_truths ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[str]: _SCREAMING_SNAKE_CASE : List[str] = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Dict = [] if args.gold_data_mode == "qa": _SCREAMING_SNAKE_CASE : int = pd.read_csv(__SCREAMING_SNAKE_CASE , sep="""\t""" , header=__SCREAMING_SNAKE_CASE ) for answer_list in data[1]: _SCREAMING_SNAKE_CASE : Union[str, Any] = ast.literal_eval(__SCREAMING_SNAKE_CASE ) answers.append(__SCREAMING_SNAKE_CASE ) else: _SCREAMING_SNAKE_CASE : Optional[Any] = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Optional[int] = [[reference] for reference in references] _SCREAMING_SNAKE_CASE : Optional[int] = 0 for prediction, ground_truths in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): total += 1 em += metric_max_over_ground_truths(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) fa += metric_max_over_ground_truths(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = 1_00.0 * em / total _SCREAMING_SNAKE_CASE : Optional[Any] = 1_00.0 * fa / total logger.info(F"""F1: {fa:.2f}""" ) logger.info(F"""EM: {em:.2f}""" ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Tuple = args.k _SCREAMING_SNAKE_CASE : int = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Any = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Optional[Any] = 0 for hypo, reference in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = set(hypo.split("""\t""" )[:k] ) _SCREAMING_SNAKE_CASE : Union[str, Any] = set(reference.split("""\t""" ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k _SCREAMING_SNAKE_CASE : int = 1_00.0 * em / total logger.info(F"""Precision@{k}: {em: .2f}""" ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: def strip_title(__SCREAMING_SNAKE_CASE ): if title.startswith("""\"""" ): _SCREAMING_SNAKE_CASE : Optional[int] = title[1:] if title.endswith("""\"""" ): _SCREAMING_SNAKE_CASE : str = title[:-1] return title _SCREAMING_SNAKE_CASE : Dict = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( __SCREAMING_SNAKE_CASE , return_tensors="""pt""" , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , )["""input_ids"""].to(args.device ) _SCREAMING_SNAKE_CASE : List[str] = rag_model.rag.question_encoder(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Any = question_enc_outputs[0] _SCREAMING_SNAKE_CASE : List[Any] = rag_model.retriever( __SCREAMING_SNAKE_CASE , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors="""pt""" , ) _SCREAMING_SNAKE_CASE : Optional[int] = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [] for docs in all_docs: _SCREAMING_SNAKE_CASE : str = [strip_title(__SCREAMING_SNAKE_CASE ) for title in docs["""title"""]] provenance_strings.append("""\t""".join(__SCREAMING_SNAKE_CASE ) ) return provenance_strings def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[Any]: with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[Any] = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( __SCREAMING_SNAKE_CASE , return_tensors="""pt""" , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Union[str, Any] = inputs_dict.input_ids.to(args.device ) _SCREAMING_SNAKE_CASE : Union[str, Any] = inputs_dict.attention_mask.to(args.device ) _SCREAMING_SNAKE_CASE : Optional[Any] = rag_model.generate( # rag_model overwrites generate __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=__SCREAMING_SNAKE_CASE , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) _SCREAMING_SNAKE_CASE : Tuple = rag_model.retriever.generator_tokenizer.batch_decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) if args.print_predictions: for q, a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): logger.info("""Q: {} - A: {}""".format(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) return answers def lowerCamelCase_()-> List[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser() parser.add_argument( """--model_type""" , choices=["""rag_sequence""", """rag_token""", """bart"""] , type=__SCREAMING_SNAKE_CASE , help=( """RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the""" """ model_name_or_path""" ) , ) parser.add_argument( """--index_name""" , default=__SCREAMING_SNAKE_CASE , choices=["""exact""", """compressed""", """legacy"""] , type=__SCREAMING_SNAKE_CASE , help="""RAG model retriever type""" , ) parser.add_argument( """--index_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Path to the retrieval index""" , ) parser.add_argument("""--n_docs""" , default=5 , type=__SCREAMING_SNAKE_CASE , help="""Number of retrieved docs""" ) parser.add_argument( """--model_name_or_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to pretrained checkpoints or model identifier from huggingface.co/models""" , ) parser.add_argument( """--eval_mode""" , choices=["""e2e""", """retrieval"""] , default="""e2e""" , type=__SCREAMING_SNAKE_CASE , help=( """Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates""" """ precision@k.""" ) , ) parser.add_argument("""--k""" , default=1 , type=__SCREAMING_SNAKE_CASE , help="""k for the precision@k calculation""" ) parser.add_argument( """--evaluation_set""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to a file containing evaluation samples""" , ) parser.add_argument( """--gold_data_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to a tab-separated file with gold samples""" , ) parser.add_argument( """--gold_data_mode""" , default="""qa""" , type=__SCREAMING_SNAKE_CASE , choices=["""qa""", """ans"""] , help=( """Format of the gold data file""" """qa - a single line in the following format: question [tab] answer_list""" """ans - a single line of the gold file contains the expected answer string""" ) , ) parser.add_argument( """--predictions_path""" , type=__SCREAMING_SNAKE_CASE , default="""predictions.txt""" , help="""Name of the predictions file, to be stored in the checkpoints directory""" , ) parser.add_argument( """--eval_all_checkpoints""" , action="""store_true""" , help="""Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number""" , ) parser.add_argument( """--eval_batch_size""" , default=8 , type=__SCREAMING_SNAKE_CASE , help="""Batch size per GPU/CPU for evaluation.""" , ) parser.add_argument( """--recalculate""" , help="""Recalculate predictions even if the prediction file exists""" , action="""store_true""" , ) parser.add_argument( """--num_beams""" , default=4 , type=__SCREAMING_SNAKE_CASE , help="""Number of beams to be used when generating answers""" , ) parser.add_argument("""--min_length""" , default=1 , type=__SCREAMING_SNAKE_CASE , help="""Min length of the generated answers""" ) parser.add_argument("""--max_length""" , default=50 , type=__SCREAMING_SNAKE_CASE , help="""Max length of the generated answers""" ) parser.add_argument( """--print_predictions""" , action="""store_true""" , help="""If True, prints predictions while evaluating.""" , ) parser.add_argument( """--print_docs""" , action="""store_true""" , help="""If True, prints docs retried while generating.""" , ) _SCREAMING_SNAKE_CASE : Dict = parser.parse_args() _SCREAMING_SNAKE_CASE : Any = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) return args def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: _SCREAMING_SNAKE_CASE : Union[str, Any] = {} if args.model_type is None: _SCREAMING_SNAKE_CASE : Optional[int] = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith("""rag""" ): _SCREAMING_SNAKE_CASE : List[Any] = RagTokenForGeneration if args.model_type == """rag_token""" else RagSequenceForGeneration _SCREAMING_SNAKE_CASE : Optional[Any] = args.n_docs if args.index_name is not None: _SCREAMING_SNAKE_CASE : Optional[Any] = args.index_name if args.index_path is not None: _SCREAMING_SNAKE_CASE : Any = args.index_path else: _SCREAMING_SNAKE_CASE : Any = BartForConditionalGeneration _SCREAMING_SNAKE_CASE : int = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info("""Evaluate the following checkpoints: %s""" , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = get_scores if args.eval_mode == """e2e""" else get_precision_at_k _SCREAMING_SNAKE_CASE : Tuple = evaluate_batch_eae if args.eval_mode == """e2e""" else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info("""Calculating metrics based on an existing predictions file: {}""".format(args.predictions_path ) ) score_fn(__SCREAMING_SNAKE_CASE , args.predictions_path , args.gold_data_path ) continue logger.info("""***** Running evaluation for {} *****""".format(__SCREAMING_SNAKE_CASE ) ) logger.info(""" Batch size = %d""" , args.eval_batch_size ) logger.info(""" Predictions will be stored under {}""".format(args.predictions_path ) ) if args.model_type.startswith("""rag""" ): _SCREAMING_SNAKE_CASE : str = RagRetriever.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = model_class.from_pretrained(__SCREAMING_SNAKE_CASE , retriever=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) model.retriever.init_retrieval() else: _SCREAMING_SNAKE_CASE : str = model_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) model.to(args.device ) with open(args.evaluation_set , """r""" ) as eval_file, open(args.predictions_path , """w""" ) as preds_file: _SCREAMING_SNAKE_CASE : str = [] for line in tqdm(__SCREAMING_SNAKE_CASE ): questions.append(line.strip() ) if len(__SCREAMING_SNAKE_CASE ) == args.eval_batch_size: _SCREAMING_SNAKE_CASE : str = evaluate_batch_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) preds_file.write("""\n""".join(__SCREAMING_SNAKE_CASE ) + """\n""" ) preds_file.flush() _SCREAMING_SNAKE_CASE : Any = [] if len(__SCREAMING_SNAKE_CASE ) > 0: _SCREAMING_SNAKE_CASE : List[str] = evaluate_batch_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) preds_file.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) preds_file.flush() score_fn(__SCREAMING_SNAKE_CASE , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": lowerCAmelCase_ = get_args() main(args)
635
1
"""simple docstring""" from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record lowerCAmelCase_ = '''\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } ''' lowerCAmelCase_ = '''\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. ''' lowerCAmelCase_ = ''' Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for \'record\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'prediction_text\': the predicted answer text - for \'multirc\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question-answer pair as specified by the dataset - \'prediction\': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for \'record\': list of question-answers dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'answers\': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for \'record\': - \'exact_match\': Exact match between answer and gold answer - \'f1\': F1 score - for \'multirc\': - \'exact_match\': Exact match between answer and gold answer - \'f1_m\': Per-question macro-F1 score - \'f1_a\': Average F1 score over all answers - for \'axb\': \'matthews_correlation\': Matthew Correlation - for \'cb\': - \'accuracy\': Accuracy - \'f1\': F1 score - for all others: - \'accuracy\': Accuracy Examples: >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\') >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}] >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\') >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'matthews_correlation\': 1.0} ''' def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[Any]: return float((preds == labels).mean() ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="binary" )-> int: _SCREAMING_SNAKE_CASE : Any = simple_accuracy(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : str = float(fa_score(y_true=__SCREAMING_SNAKE_CASE , y_pred=__SCREAMING_SNAKE_CASE , average=__SCREAMING_SNAKE_CASE ) ) return { "accuracy": acc, "f1": fa, } def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: _SCREAMING_SNAKE_CASE : int = {} for id_pred, label in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = F"""{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}""" _SCREAMING_SNAKE_CASE : Dict = id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: _SCREAMING_SNAKE_CASE : Dict = [(pred, label)] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = [], [] for question, preds_labels in question_map.items(): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = zip(*__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : str = fa_score(y_true=__SCREAMING_SNAKE_CASE , y_pred=__SCREAMING_SNAKE_CASE , average="""macro""" ) fas.append(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[Any] = int(sum(pred == label for pred, label in preds_labels ) == len(__SCREAMING_SNAKE_CASE ) ) ems.append(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Any = float(sum(__SCREAMING_SNAKE_CASE ) / len(__SCREAMING_SNAKE_CASE ) ) _SCREAMING_SNAKE_CASE : str = sum(__SCREAMING_SNAKE_CASE ) / len(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[int] = float(fa_score(y_true=__SCREAMING_SNAKE_CASE , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : str): """simple docstring""" if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""") return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types()) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _lowerCAmelCase ( self : Dict): """simple docstring""" if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64"""), "query": datasets.Value("""int64"""), }, "prediction_text": datasets.Value("""string"""), }, "references": { "idx": { "passage": datasets.Value("""int64"""), "query": datasets.Value("""int64"""), }, "answers": datasets.Sequence(datasets.Value("""string""")), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64"""), "paragraph": datasets.Value("""int64"""), "question": datasets.Value("""int64"""), }, "prediction": datasets.Value("""int64"""), }, "references": datasets.Value("""int64"""), } else: return { "predictions": datasets.Value("""int64"""), "references": datasets.Value("""int64"""), } def _lowerCAmelCase ( self : int , _A : Optional[Any] , _A : List[str]): """simple docstring""" if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_A , _A)} elif self.config_name == "cb": return acc_and_fa(_A , _A , fa_avg="""macro""") elif self.config_name == "record": _SCREAMING_SNAKE_CASE : Optional[int] = [ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] _SCREAMING_SNAKE_CASE : Optional[int] = {pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(_A , _A)[0] elif self.config_name == "multirc": return evaluate_multirc(_A , _A) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_A , _A)} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""")
635
"""simple docstring""" import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def lowerCamelCase_(__SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=10 , __SCREAMING_SNAKE_CASE=100 , __SCREAMING_SNAKE_CASE=1_026 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE="data/tokenized_stories_train_wikitext103.jbl" , __SCREAMING_SNAKE_CASE="igf_context_pairs.jbl" , )-> Union[str, Any]: set_seed(3 ) # generate train_data and objective_set _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = generate_datasets( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , number=__SCREAMING_SNAKE_CASE , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? _SCREAMING_SNAKE_CASE : Dict = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) # load pretrained model _SCREAMING_SNAKE_CASE : Any = load_gpta("""gpt2""" ).to(__SCREAMING_SNAKE_CASE ) print("""computing perplexity on objective set""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).item() print("""perplexity on objective set:""" , __SCREAMING_SNAKE_CASE ) # collect igf pairs and save to file demo.jbl collect_objective_set(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=15 , __SCREAMING_SNAKE_CASE=128 , __SCREAMING_SNAKE_CASE=100 , __SCREAMING_SNAKE_CASE="igf_model.pt" , )-> Optional[int]: set_seed(42 ) # Load pre-trained model _SCREAMING_SNAKE_CASE : Any = GPTaLMHeadModel.from_pretrained("""gpt2""" ) # Initialize secondary learner to use embedding weights of model _SCREAMING_SNAKE_CASE : Union[str, Any] = SecondaryLearner(__SCREAMING_SNAKE_CASE ) # Train secondary learner _SCREAMING_SNAKE_CASE : Any = train_secondary_learner( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , max_epochs=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , eval_freq=100 , igf_model_path=__SCREAMING_SNAKE_CASE , ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_000 , __SCREAMING_SNAKE_CASE=16 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=recopy_gpta , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=10 , __SCREAMING_SNAKE_CASE="gpt2_finetuned.pt" , )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Tuple = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = RandomSampler(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = DataLoader(__SCREAMING_SNAKE_CASE , sampler=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = max_steps // (len(__SCREAMING_SNAKE_CASE )) + 1 _SCREAMING_SNAKE_CASE : List[Any] = 0 _SCREAMING_SNAKE_CASE : Any = torch.zeros((1, context_len) , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = recopy_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) model.train() if secondary_learner is not None: secondary_learner.to(__SCREAMING_SNAKE_CASE ) secondary_learner.eval() _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : Optional[int] = 0 _SCREAMING_SNAKE_CASE : Optional[Any] = [] _SCREAMING_SNAKE_CASE : int = [] # Compute the performance of the transformer model at the beginning _SCREAMING_SNAKE_CASE : Tuple = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) test_perps.append(__SCREAMING_SNAKE_CASE ) print("""Test perplexity, step""" , __SCREAMING_SNAKE_CASE , """:""" , __SCREAMING_SNAKE_CASE ) for epoch in range(int(__SCREAMING_SNAKE_CASE ) ): for step, example in enumerate(__SCREAMING_SNAKE_CASE ): torch.cuda.empty_cache() _SCREAMING_SNAKE_CASE : Any = random.randint(0 , example.size(2 ) - context_len - 1 ) _SCREAMING_SNAKE_CASE : int = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() _SCREAMING_SNAKE_CASE : Union[str, Any] = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[str] = True if secondary_learner is not None: _SCREAMING_SNAKE_CASE : List[Any] = secondary_learner.forward( torch.tensor(__SCREAMING_SNAKE_CASE , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ).unsqueeze(0 ) )[0].item() observed_qs.append(float(__SCREAMING_SNAKE_CASE ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: _SCREAMING_SNAKE_CASE : Dict = -1 if predicted_q < threshold: _SCREAMING_SNAKE_CASE : List[str] = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() _SCREAMING_SNAKE_CASE : Any = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: _SCREAMING_SNAKE_CASE : Tuple = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) test_perps.append(__SCREAMING_SNAKE_CASE ) print("""Test perplexity, step""" , __SCREAMING_SNAKE_CASE , """:""" , __SCREAMING_SNAKE_CASE ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() , __SCREAMING_SNAKE_CASE ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def lowerCamelCase_()-> Tuple: _SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser(description="""Fine-tune a transformer model with IGF on a language modeling task""" ) # Required parameters parser.add_argument( """--data_dir""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The input data dir. Should contain data files for WikiText.""" , ) parser.add_argument( """--model_name_or_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to pretrained model or model identifier from huggingface.co/models""" , ) parser.add_argument( """--data_file""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help=( """A jbl file containing tokenized data which can be split as objective dataset, """ """train_dataset and test_dataset.""" ) , ) parser.add_argument( """--igf_data_file""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help="""A jbl file containing the context and information gain pairs to train secondary learner.""" , ) parser.add_argument( """--output_dir""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The output directory where the final fine-tuned model is stored.""" , ) parser.add_argument( """--tokenizer_name""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Pretrained tokenizer name or path if not the same as model_name""" , ) parser.add_argument("""--seed""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help="""A seed for reproducible training.""" ) parser.add_argument( """--context_len""" , default=32 , type=__SCREAMING_SNAKE_CASE , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--size_objective_set""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""number of articles that are long enough to be used as our objective set""" , ) parser.add_argument( """--eval_freq""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""secondary model evaluation is triggered at eval_freq""" ) parser.add_argument("""--max_steps""" , default=1_000 , type=__SCREAMING_SNAKE_CASE , help="""To calculate training epochs""" ) parser.add_argument( """--secondary_learner_batch_size""" , default=128 , type=__SCREAMING_SNAKE_CASE , help="""batch size of training data for secondary learner""" , ) parser.add_argument( """--batch_size""" , default=16 , type=__SCREAMING_SNAKE_CASE , help="""batch size of training data of language model(gpt2) """ ) parser.add_argument( """--eval_interval""" , default=10 , type=__SCREAMING_SNAKE_CASE , help=( """decay the selectivity of our secondary learner filter from""" """1 standard deviation above average to 1 below average after 10 batches""" ) , ) parser.add_argument( """--number""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""The number of examples split to be used as objective_set/test_data""" ) parser.add_argument( """--min_len""" , default=1_026 , type=__SCREAMING_SNAKE_CASE , help="""The minimum length of the article to be used as objective set""" ) parser.add_argument( """--secondary_learner_max_epochs""" , default=15 , type=__SCREAMING_SNAKE_CASE , help="""number of epochs to train secondary learner""" ) parser.add_argument("""--trim""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""truncate the example if it exceeds context length""" ) parser.add_argument( """--threshold""" , default=1.0 , type=__SCREAMING_SNAKE_CASE , help=( """The threshold value used by secondary learner to filter the train_data and allow only""" """ informative data as input to the model""" ) , ) parser.add_argument("""--finetuned_model_name""" , default="""gpt2_finetuned.pt""" , type=__SCREAMING_SNAKE_CASE , help="""finetuned_model_name""" ) parser.add_argument( """--recopy_model""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Reset the model to the original pretrained GPT-2 weights after each iteration""" , ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 , max_steps=10 , size_objective_set=100 , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE , data_file="""data/tokenized_stories_train_wikitext103.jbl""" , igf_data_file="""igf_context_pairs.jbl""" , ) # Load train data for secondary learner _SCREAMING_SNAKE_CASE : Optional[int] = joblib.load("""data/IGF_values.jbl""" ) # Train secondary learner _SCREAMING_SNAKE_CASE : int = training_secondary_learner( __SCREAMING_SNAKE_CASE , secondary_learner_max_epochs=15 , secondary_learner_batch_size=128 , eval_freq=100 , igf_model_path="""igf_model.pt""" , ) # load pretrained gpt2 model _SCREAMING_SNAKE_CASE : List[Any] = GPTaLMHeadModel.from_pretrained("""gpt2""" ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = generate_datasets( context_len=32 , file="""data/tokenized_stories_train_wikitext103.jbl""" , number=100 , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , context_len=32 , max_steps=1_000 , batch_size=16 , threshold=1.0 , recopy_model=__SCREAMING_SNAKE_CASE , secondary_learner=__SCREAMING_SNAKE_CASE , eval_interval=10 , finetuned_model_name="""gpt2_finetuned.pt""" , ) if __name__ == "__main__": main()
635
1
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo lowerCAmelCase_ = '''\ @misc{wu2016googles, title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } ''' lowerCAmelCase_ = '''\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the \'GLEU score\'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score\'s range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. ''' lowerCAmelCase_ = '''\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: \'google_bleu\': google_bleu score Examples: Example 1: >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\', ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\'] >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\', ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\', ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\'] >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\', ... \'interested\', \'in\', \'world\', \'history\'] >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\', ... \'because\', \'he\', \'read\', \'the\', \'book\'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results["google_bleu"], 2)) 0.44 Example 2: >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\', ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\'] >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\', ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\', ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\'] >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\', ... \'heed\', \'the\', \'cat\', \'commands\'] >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\', ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\', ... \'of\', \'the\', \'cat\'] >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\', ... \'interested\', \'in\', \'world\', \'history\'] >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\', ... \'because\', \'he\', \'read\', \'the\', \'book\'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results["google_bleu"], 2)) 0.61 Example 3: >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\', ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\'] >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\', ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\', ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\'] >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\', ... \'heed\', \'the\', \'cat\', \'commands\'] >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\', ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\', ... \'of\', \'the\', \'cat\'] >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\', ... \'interested\', \'in\', \'world\', \'history\'] >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\', ... \'because\', \'he\', \'read\', \'the\', \'book\'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results["google_bleu"], 2)) 0.53 Example 4: >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\', ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\'] >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\', ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\', ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\'] >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\', ... \'heed\', \'the\', \'cat\', \'commands\'] >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\', ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\', ... \'of\', \'the\', \'cat\'] >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\', ... \'interested\', \'in\', \'world\', \'history\'] >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\', ... \'because\', \'he\', \'read\', \'the\', \'book\'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results["google_bleu"], 2)) 0.4 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence"""), """references""": datasets.Sequence( datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence""") , id="""references"""), }) , ) def _lowerCAmelCase ( self : str , _A : List[List[List[str]]] , _A : List[List[str]] , _A : int = 1 , _A : int = 4 , ): """simple docstring""" return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_A , hypotheses=_A , min_len=_A , max_len=_A) }
635
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _snake_case ( __snake_case ): """simple docstring""" a = ["image_processor", "tokenizer"] a = "ChineseCLIPImageProcessor" a = ("BertTokenizer", "BertTokenizerFast") def __init__( self : Dict , _A : Tuple=None , _A : List[Any]=None , **_A : int): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , _A , ) _SCREAMING_SNAKE_CASE : str = kwargs.pop("""feature_extractor""") _SCREAMING_SNAKE_CASE : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""") if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""") super().__init__(_A , _A) _SCREAMING_SNAKE_CASE : Dict = self.image_processor def __call__( self : Optional[int] , _A : Optional[Any]=None , _A : Any=None , _A : Tuple=None , **_A : int): """simple docstring""" if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""") if text is not None: _SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer(_A , return_tensors=_A , **_A) if images is not None: _SCREAMING_SNAKE_CASE : List[Any] = self.image_processor(_A , return_tensors=_A , **_A) if text is not None and images is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_A) , tensor_type=_A) def _lowerCAmelCase ( self : str , *_A : Any , **_A : Any): """simple docstring""" return self.tokenizer.batch_decode(*_A , **_A) def _lowerCAmelCase ( self : Union[str, Any] , *_A : List[Any] , **_A : Any): """simple docstring""" return self.tokenizer.decode(*_A , **_A) @property def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.model_input_names _SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def _lowerCAmelCase ( self : List[str]): """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , _A , ) return self.image_processor_class
635
1
"""simple docstring""" import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = np.full((len(__SCREAMING_SNAKE_CASE ), sequence_length, 2) , __SCREAMING_SNAKE_CASE ) else: _SCREAMING_SNAKE_CASE : Any = np.full((len(__SCREAMING_SNAKE_CASE ), sequence_length) , __SCREAMING_SNAKE_CASE ) for i, tensor in enumerate(__SCREAMING_SNAKE_CASE ): if padding_side == "right": if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = tensor[:sequence_length] else: _SCREAMING_SNAKE_CASE : int = tensor[:sequence_length] else: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = tensor[:sequence_length] else: _SCREAMING_SNAKE_CASE : List[str] = tensor[:sequence_length] return out_tensor.tolist() def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> List[Any]: _SCREAMING_SNAKE_CASE : List[str] = ord(__SCREAMING_SNAKE_CASE ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True _SCREAMING_SNAKE_CASE : Tuple = unicodedata.category(__SCREAMING_SNAKE_CASE ) if cat.startswith("""P""" ): return True return False @dataclass class _snake_case ( __snake_case ): """simple docstring""" a = 42 a = True a = None a = None a = -1_00 a = "pt" def _lowerCAmelCase ( self : List[str] , _A : str): """simple docstring""" import torch _SCREAMING_SNAKE_CASE : List[str] = """label""" if """label""" in features[0].keys() else """labels""" _SCREAMING_SNAKE_CASE : Optional[Any] = [feature[label_name] for feature in features] if label_name in features[0].keys() else None _SCREAMING_SNAKE_CASE : List[str] = self.tokenizer.pad( _A , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="""pt""" if labels is None else None , ) if labels is None: return batch _SCREAMING_SNAKE_CASE : Tuple = torch.tensor(batch["""entity_ids"""]).shape[1] _SCREAMING_SNAKE_CASE : Tuple = self.tokenizer.padding_side if padding_side == "right": _SCREAMING_SNAKE_CASE : Union[str, Any] = [ list(_A) + [self.label_pad_token_id] * (sequence_length - len(_A)) for label in labels ] else: _SCREAMING_SNAKE_CASE : List[str] = [ [self.label_pad_token_id] * (sequence_length - len(_A)) + list(_A) for label in labels ] _SCREAMING_SNAKE_CASE : Optional[int] = [feature["""ner_tags"""] for feature in features] _SCREAMING_SNAKE_CASE : Tuple = padding_tensor(_A , -1 , _A , _A) _SCREAMING_SNAKE_CASE : Optional[Any] = [feature["""original_entity_spans"""] for feature in features] _SCREAMING_SNAKE_CASE : Dict = padding_tensor(_A , (-1, -1) , _A , _A) _SCREAMING_SNAKE_CASE : Optional[Any] = {k: torch.tensor(_A , dtype=torch.intaa) for k, v in batch.items()} return batch
635
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = ['''model.decoder.embed_positions.weights'''] def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[int]: if "emb" in name: _SCREAMING_SNAKE_CASE : List[Any] = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: _SCREAMING_SNAKE_CASE : List[str] = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: _SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: _SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: _SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: _SCREAMING_SNAKE_CASE : int = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: _SCREAMING_SNAKE_CASE : Dict = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: _SCREAMING_SNAKE_CASE : Dict = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: _SCREAMING_SNAKE_CASE : Tuple = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: _SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: _SCREAMING_SNAKE_CASE : str = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple[Dict, Dict]: _SCREAMING_SNAKE_CASE : str = list(state_dict.keys() ) _SCREAMING_SNAKE_CASE : Tuple = {} for key in keys: _SCREAMING_SNAKE_CASE : Dict = state_dict.pop(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : int = rename_keys(__SCREAMING_SNAKE_CASE ) if "in_proj_weight" in key: # split fused qkv proj _SCREAMING_SNAKE_CASE : str = val[:hidden_size, :] _SCREAMING_SNAKE_CASE : Any = val[hidden_size : 2 * hidden_size, :] _SCREAMING_SNAKE_CASE : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: _SCREAMING_SNAKE_CASE : int = val else: _SCREAMING_SNAKE_CASE : Dict = val return state_dict, enc_dec_proj_state_dict def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> MusicgenDecoderConfig: if checkpoint == "small": # default config values _SCREAMING_SNAKE_CASE : Optional[Any] = 1_024 _SCREAMING_SNAKE_CASE : str = 24 _SCREAMING_SNAKE_CASE : Any = 16 elif checkpoint == "medium": _SCREAMING_SNAKE_CASE : Dict = 1_536 _SCREAMING_SNAKE_CASE : Union[str, Any] = 48 _SCREAMING_SNAKE_CASE : Optional[Any] = 24 elif checkpoint == "large": _SCREAMING_SNAKE_CASE : List[Any] = 2_048 _SCREAMING_SNAKE_CASE : Optional[int] = 48 _SCREAMING_SNAKE_CASE : str = 32 else: raise ValueError(F"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) _SCREAMING_SNAKE_CASE : Optional[Any] = MusicgenDecoderConfig( hidden_size=__SCREAMING_SNAKE_CASE , ffn_dim=hidden_size * 4 , num_hidden_layers=__SCREAMING_SNAKE_CASE , num_attention_heads=__SCREAMING_SNAKE_CASE , ) return config @torch.no_grad() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="cpu" )-> str: _SCREAMING_SNAKE_CASE : str = MusicGen.get_pretrained(__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[str] = decoder_config_from_checkpoint(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[Any] = fairseq_model.lm.state_dict() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = rename_state_dict( __SCREAMING_SNAKE_CASE , hidden_size=decoder_config.hidden_size ) _SCREAMING_SNAKE_CASE : Tuple = TaEncoderModel.from_pretrained("""t5-base""" ) _SCREAMING_SNAKE_CASE : List[Any] = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) _SCREAMING_SNAKE_CASE : str = MusicgenForCausalLM(__SCREAMING_SNAKE_CASE ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = decoder.load_state_dict(__SCREAMING_SNAKE_CASE , strict=__SCREAMING_SNAKE_CASE ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ValueError(F"""Missing key(s) in state_dict: {missing_keys}""" ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ValueError(F"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model _SCREAMING_SNAKE_CASE : Dict = MusicgenForConditionalGeneration(text_encoder=__SCREAMING_SNAKE_CASE , audio_encoder=__SCREAMING_SNAKE_CASE , decoder=__SCREAMING_SNAKE_CASE ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(__SCREAMING_SNAKE_CASE ) # check we can do a forward pass _SCREAMING_SNAKE_CASE : Optional[Any] = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) _SCREAMING_SNAKE_CASE : Dict = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[int] = model(input_ids=__SCREAMING_SNAKE_CASE , decoder_input_ids=__SCREAMING_SNAKE_CASE ).logits if logits.shape != (8, 1, 2_048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor _SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained("""t5-base""" ) _SCREAMING_SNAKE_CASE : List[str] = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) _SCREAMING_SNAKE_CASE : Optional[int] = MusicgenProcessor(feature_extractor=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE ) # set the appropriate bos/pad token ids _SCREAMING_SNAKE_CASE : Optional[Any] = 2_048 _SCREAMING_SNAKE_CASE : List[Any] = 2_048 # set other default generation config params _SCREAMING_SNAKE_CASE : Any = int(30 * audio_encoder.config.frame_rate ) _SCREAMING_SNAKE_CASE : Tuple = True _SCREAMING_SNAKE_CASE : int = 3.0 if pytorch_dump_folder is not None: Path(__SCREAMING_SNAKE_CASE ).mkdir(exist_ok=__SCREAMING_SNAKE_CASE ) logger.info(F"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) processor.save_pretrained(__SCREAMING_SNAKE_CASE ) if repo_id: logger.info(F"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(__SCREAMING_SNAKE_CASE ) processor.push_to_hub(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint''', default='''small''', type=str, help='''Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.''', ) parser.add_argument( '''--pytorch_dump_folder''', required=True, default=None, type=str, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) parser.add_argument( '''--device''', default='''cpu''', type=str, help='''Torch device to run the conversion, either cpu or cuda.''' ) lowerCAmelCase_ = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
635
1
"""simple docstring""" from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar lowerCAmelCase_ = TypeVar('''T''') class _snake_case ( Generic[T] ): """simple docstring""" def __init__( self : List[Any] , _A : list[T] , _A : Callable[[T, T], T]): """simple docstring""" _SCREAMING_SNAKE_CASE : Any | T = None _SCREAMING_SNAKE_CASE : int = len(_A) _SCREAMING_SNAKE_CASE : list[T] = [any_type for _ in range(self.N)] + arr _SCREAMING_SNAKE_CASE : Dict = fnc self.build() def _lowerCAmelCase ( self : str): """simple docstring""" for p in range(self.N - 1 , 0 , -1): _SCREAMING_SNAKE_CASE : str = self.fn(self.st[p * 2] , self.st[p * 2 + 1]) def _lowerCAmelCase ( self : Optional[Any] , _A : int , _A : T): """simple docstring""" p += self.N _SCREAMING_SNAKE_CASE : List[Any] = v while p > 1: _SCREAMING_SNAKE_CASE : Tuple = p // 2 _SCREAMING_SNAKE_CASE : Optional[int] = self.fn(self.st[p * 2] , self.st[p * 2 + 1]) def _lowerCAmelCase ( self : int , _A : int , _A : int): # noqa: E741 """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = l + self.N, r + self.N _SCREAMING_SNAKE_CASE : T | None = None while l <= r: if l % 2 == 1: _SCREAMING_SNAKE_CASE : List[str] = self.st[l] if res is None else self.fn(_A , self.st[l]) if r % 2 == 0: _SCREAMING_SNAKE_CASE : str = self.st[r] if res is None else self.fn(_A , self.st[r]) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = (l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce lowerCAmelCase_ = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12] lowerCAmelCase_ = { 0: 7, 1: 2, 2: 6, 3: -14, 4: 5, 5: 4, 6: 7, 7: -10, 8: 9, 9: 10, 10: 12, 11: 1, } lowerCAmelCase_ = SegmentTree(test_array, min) lowerCAmelCase_ = SegmentTree(test_array, max) lowerCAmelCase_ = SegmentTree(test_array, lambda a, b: a + b) def lowerCamelCase_()-> None: for i in range(len(__SCREAMING_SNAKE_CASE ) ): for j in range(__SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE ) ): _SCREAMING_SNAKE_CASE : List[str] = reduce(__SCREAMING_SNAKE_CASE , test_array[i : j + 1] ) _SCREAMING_SNAKE_CASE : int = reduce(__SCREAMING_SNAKE_CASE , test_array[i : j + 1] ) _SCREAMING_SNAKE_CASE : int = reduce(lambda __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : a + b , test_array[i : j + 1] ) assert min_range == min_segment_tree.query(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert max_range == max_segment_tree.query(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert sum_range == sum_segment_tree.query(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) test_all_segments() for index, value in test_updates.items(): lowerCAmelCase_ = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
635
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''asapp/sew-tiny-100k''': '''https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json''', # See all SEW models at https://huggingface.co/models?filter=sew } class _snake_case ( __snake_case ): """simple docstring""" a = "sew" def __init__( self : List[Any] , _A : Tuple=3_2 , _A : str=7_6_8 , _A : Dict=1_2 , _A : Tuple=1_2 , _A : Optional[Any]=3_0_7_2 , _A : List[str]=2 , _A : Dict="gelu" , _A : Union[str, Any]=0.1 , _A : Optional[int]=0.1 , _A : Optional[int]=0.1 , _A : Optional[int]=0.0 , _A : str=0.1 , _A : Tuple=0.1 , _A : Optional[int]=0.02 , _A : Dict=1e-5 , _A : str="group" , _A : Tuple="gelu" , _A : Union[str, Any]=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , _A : Optional[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , _A : Any=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , _A : Tuple=False , _A : Tuple=1_2_8 , _A : int=1_6 , _A : Union[str, Any]=True , _A : Optional[Any]=0.05 , _A : List[Any]=1_0 , _A : Union[str, Any]=2 , _A : Tuple=0.0 , _A : Union[str, Any]=1_0 , _A : Optional[int]=0 , _A : Union[str, Any]="mean" , _A : Optional[int]=False , _A : List[Any]=False , _A : int=2_5_6 , _A : str=0 , _A : Optional[int]=1 , _A : List[Any]=2 , **_A : Dict , ): """simple docstring""" super().__init__(**_A , pad_token_id=_A , bos_token_id=_A , eos_token_id=_A) _SCREAMING_SNAKE_CASE : str = hidden_size _SCREAMING_SNAKE_CASE : Optional[int] = feat_extract_norm _SCREAMING_SNAKE_CASE : Optional[int] = feat_extract_activation _SCREAMING_SNAKE_CASE : Dict = list(_A) _SCREAMING_SNAKE_CASE : int = list(_A) _SCREAMING_SNAKE_CASE : int = list(_A) _SCREAMING_SNAKE_CASE : str = conv_bias _SCREAMING_SNAKE_CASE : Tuple = num_conv_pos_embeddings _SCREAMING_SNAKE_CASE : List[str] = num_conv_pos_embedding_groups _SCREAMING_SNAKE_CASE : Tuple = len(self.conv_dim) _SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers _SCREAMING_SNAKE_CASE : List[str] = intermediate_size _SCREAMING_SNAKE_CASE : str = squeeze_factor _SCREAMING_SNAKE_CASE : Dict = hidden_act _SCREAMING_SNAKE_CASE : str = num_attention_heads _SCREAMING_SNAKE_CASE : Dict = hidden_dropout _SCREAMING_SNAKE_CASE : Tuple = attention_dropout _SCREAMING_SNAKE_CASE : int = activation_dropout _SCREAMING_SNAKE_CASE : Any = feat_proj_dropout _SCREAMING_SNAKE_CASE : str = final_dropout _SCREAMING_SNAKE_CASE : Union[str, Any] = layerdrop _SCREAMING_SNAKE_CASE : Any = layer_norm_eps _SCREAMING_SNAKE_CASE : int = initializer_range _SCREAMING_SNAKE_CASE : List[Any] = vocab_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect.""" """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,""" f"""but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride)""" f"""= {len(self.conv_stride)}`, `len(config.conv_kernel) = {len(self.conv_kernel)}`.""") # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _SCREAMING_SNAKE_CASE : List[Any] = apply_spec_augment _SCREAMING_SNAKE_CASE : List[Any] = mask_time_prob _SCREAMING_SNAKE_CASE : List[str] = mask_time_length _SCREAMING_SNAKE_CASE : List[Any] = mask_time_min_masks _SCREAMING_SNAKE_CASE : List[Any] = mask_feature_prob _SCREAMING_SNAKE_CASE : int = mask_feature_length _SCREAMING_SNAKE_CASE : List[Any] = mask_feature_min_masks # ctc loss _SCREAMING_SNAKE_CASE : int = ctc_loss_reduction _SCREAMING_SNAKE_CASE : Optional[int] = ctc_zero_infinity # sequence classification _SCREAMING_SNAKE_CASE : Dict = use_weighted_layer_sum _SCREAMING_SNAKE_CASE : List[str] = classifier_proj_size @property def _lowerCAmelCase ( self : Any): """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1)
635
1
"""simple docstring""" from typing import List, Optional, Union import torch from transformers import ( XLMRobertaTokenizer, ) from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) from .text_encoder import MultilingualCLIP lowerCAmelCase_ = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCAmelCase_ = ''' Examples: ```py >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline >>> import torch >>> pipe_prior = KandinskyPriorPipeline.from_pretrained("kandinsky-community/Kandinsky-2-1-prior") >>> pipe_prior.to("cuda") >>> prompt = "red cat, 4k photo" >>> out = pipe_prior(prompt) >>> image_emb = out.image_embeds >>> negative_image_emb = out.negative_image_embeds >>> pipe = KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1") >>> pipe.to("cuda") >>> image = pipe( ... prompt, ... image_embeds=image_emb, ... negative_image_embeds=negative_image_emb, ... height=768, ... width=768, ... num_inference_steps=100, ... ).images >>> image[0].save("cat.png") ``` ''' def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=8 )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : int = h // scale_factor**2 if h % scale_factor**2 != 0: new_h += 1 _SCREAMING_SNAKE_CASE : Optional[int] = w // scale_factor**2 if w % scale_factor**2 != 0: new_w += 1 return new_h * scale_factor, new_w * scale_factor class _snake_case ( __snake_case ): """simple docstring""" def __init__( self : int , _A : MultilingualCLIP , _A : XLMRobertaTokenizer , _A : UNetaDConditionModel , _A : Union[DDIMScheduler, DDPMScheduler] , _A : VQModel , ): """simple docstring""" super().__init__() self.register_modules( text_encoder=_A , tokenizer=_A , unet=_A , scheduler=_A , movq=_A , ) _SCREAMING_SNAKE_CASE : Dict = 2 ** (len(self.movq.config.block_out_channels) - 1) def _lowerCAmelCase ( self : Optional[Any] , _A : Tuple , _A : Optional[Any] , _A : Optional[Any] , _A : Optional[int] , _A : Tuple , _A : Tuple): """simple docstring""" if latents is None: _SCREAMING_SNAKE_CASE : List[Any] = randn_tensor(_A , generator=_A , device=_A , dtype=_A) else: if latents.shape != shape: raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}""") _SCREAMING_SNAKE_CASE : Union[str, Any] = latents.to(_A) _SCREAMING_SNAKE_CASE : int = latents * scheduler.init_noise_sigma return latents def _lowerCAmelCase ( self : Optional[int] , _A : str , _A : List[Any] , _A : Tuple , _A : Optional[int] , _A : Any=None , ): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = len(_A) if isinstance(_A , _A) else 1 # get prompt text embeddings _SCREAMING_SNAKE_CASE : Union[str, Any] = self.tokenizer( _A , padding="""max_length""" , truncation=_A , max_length=7_7 , return_attention_mask=_A , add_special_tokens=_A , return_tensors="""pt""" , ) _SCREAMING_SNAKE_CASE : List[str] = text_inputs.input_ids _SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer(_A , padding="""longest""" , return_tensors="""pt""").input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(_A , _A): _SCREAMING_SNAKE_CASE : Union[str, Any] = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" f""" {self.tokenizer.model_max_length} tokens: {removed_text}""") _SCREAMING_SNAKE_CASE : Optional[Any] = text_input_ids.to(_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = text_inputs.attention_mask.to(_A) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self.text_encoder( input_ids=_A , attention_mask=_A) _SCREAMING_SNAKE_CASE : Optional[Any] = prompt_embeds.repeat_interleave(_A , dim=0) _SCREAMING_SNAKE_CASE : Tuple = text_encoder_hidden_states.repeat_interleave(_A , dim=0) _SCREAMING_SNAKE_CASE : Optional[Any] = text_mask.repeat_interleave(_A , dim=0) if do_classifier_free_guidance: _SCREAMING_SNAKE_CASE : List[str] if negative_prompt is None: _SCREAMING_SNAKE_CASE : Dict = [""""""] * batch_size elif type(_A) is not type(_A): raise TypeError( f"""`negative_prompt` should be the same type to `prompt`, but got {type(_A)} !=""" f""" {type(_A)}.""") elif isinstance(_A , _A): _SCREAMING_SNAKE_CASE : Optional[int] = [negative_prompt] elif batch_size != len(_A): raise ValueError( f"""`negative_prompt`: {negative_prompt} has batch size {len(_A)}, but `prompt`:""" f""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches""" """ the batch size of `prompt`.""") else: _SCREAMING_SNAKE_CASE : int = negative_prompt _SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer( _A , padding="""max_length""" , max_length=7_7 , truncation=_A , return_attention_mask=_A , add_special_tokens=_A , return_tensors="""pt""" , ) _SCREAMING_SNAKE_CASE : List[Any] = uncond_input.input_ids.to(_A) _SCREAMING_SNAKE_CASE : List[str] = uncond_input.attention_mask.to(_A) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = self.text_encoder( input_ids=_A , attention_mask=_A) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method _SCREAMING_SNAKE_CASE : Optional[int] = negative_prompt_embeds.shape[1] _SCREAMING_SNAKE_CASE : List[str] = negative_prompt_embeds.repeat(1 , _A) _SCREAMING_SNAKE_CASE : List[Any] = negative_prompt_embeds.view(batch_size * num_images_per_prompt , _A) _SCREAMING_SNAKE_CASE : Any = uncond_text_encoder_hidden_states.shape[1] _SCREAMING_SNAKE_CASE : Optional[int] = uncond_text_encoder_hidden_states.repeat(1 , _A , 1) _SCREAMING_SNAKE_CASE : List[str] = uncond_text_encoder_hidden_states.view( batch_size * num_images_per_prompt , _A , -1) _SCREAMING_SNAKE_CASE : Dict = uncond_text_mask.repeat_interleave(_A , dim=0) # done duplicates # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes _SCREAMING_SNAKE_CASE : str = torch.cat([negative_prompt_embeds, prompt_embeds]) _SCREAMING_SNAKE_CASE : List[str] = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]) _SCREAMING_SNAKE_CASE : str = torch.cat([uncond_text_mask, text_mask]) return prompt_embeds, text_encoder_hidden_states, text_mask def _lowerCAmelCase ( self : Dict , _A : Union[str, Any]=0): """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""") _SCREAMING_SNAKE_CASE : Dict = torch.device(f"""cuda:{gpu_id}""") _SCREAMING_SNAKE_CASE : Tuple = [ self.unet, self.text_encoder, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_A , _A) def _lowerCAmelCase ( self : List[Any] , _A : Optional[int]=0): """simple docstring""" if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0"""): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""") _SCREAMING_SNAKE_CASE : Optional[int] = torch.device(f"""cuda:{gpu_id}""") if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=_A) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) _SCREAMING_SNAKE_CASE : Any = None for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = cpu_offload_with_hook(_A , _A , prev_module_hook=_A) if self.safety_checker is not None: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = cpu_offload_with_hook(self.safety_checker , _A , prev_module_hook=_A) # We'll offload the last model manually. _SCREAMING_SNAKE_CASE : List[str] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _lowerCAmelCase ( self : List[Any]): """simple docstring""" if not hasattr(self.unet , """_hf_hook"""): return self.device for module in self.unet.modules(): if ( hasattr(_A , """_hf_hook""") and hasattr(module._hf_hook , """execution_device""") and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device) return self.device @torch.no_grad() @replace_example_docstring(_A) def __call__( self : Optional[int] , _A : Union[str, List[str]] , _A : Union[torch.FloatTensor, List[torch.FloatTensor]] , _A : Union[torch.FloatTensor, List[torch.FloatTensor]] , _A : Optional[Union[str, List[str]]] = None , _A : int = 5_1_2 , _A : int = 5_1_2 , _A : int = 1_0_0 , _A : float = 4.0 , _A : int = 1 , _A : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _A : Optional[torch.FloatTensor] = None , _A : Optional[str] = "pil" , _A : bool = True , ): """simple docstring""" if isinstance(_A , _A): _SCREAMING_SNAKE_CASE : List[Any] = 1 elif isinstance(_A , _A): _SCREAMING_SNAKE_CASE : Any = len(_A) else: raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(_A)}""") _SCREAMING_SNAKE_CASE : Tuple = self._execution_device _SCREAMING_SNAKE_CASE : Any = batch_size * num_images_per_prompt _SCREAMING_SNAKE_CASE : Optional[int] = guidance_scale > 1.0 _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self._encode_prompt( _A , _A , _A , _A , _A) if isinstance(_A , _A): _SCREAMING_SNAKE_CASE : str = torch.cat(_A , dim=0) if isinstance(_A , _A): _SCREAMING_SNAKE_CASE : Tuple = torch.cat(_A , dim=0) if do_classifier_free_guidance: _SCREAMING_SNAKE_CASE : str = image_embeds.repeat_interleave(_A , dim=0) _SCREAMING_SNAKE_CASE : Optional[int] = negative_image_embeds.repeat_interleave(_A , dim=0) _SCREAMING_SNAKE_CASE : List[str] = torch.cat([negative_image_embeds, image_embeds] , dim=0).to( dtype=prompt_embeds.dtype , device=_A) self.scheduler.set_timesteps(_A , device=_A) _SCREAMING_SNAKE_CASE : Any = self.scheduler.timesteps _SCREAMING_SNAKE_CASE : Optional[Any] = self.unet.config.in_channels _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = get_new_h_w(_A , _A , self.movq_scale_factor) # create initial latent _SCREAMING_SNAKE_CASE : List[Any] = self.prepare_latents( (batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.dtype , _A , _A , _A , self.scheduler , ) for i, t in enumerate(self.progress_bar(_A)): # expand the latents if we are doing classifier free guidance _SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat([latents] * 2) if do_classifier_free_guidance else latents _SCREAMING_SNAKE_CASE : Union[str, Any] = {"""text_embeds""": prompt_embeds, """image_embeds""": image_embeds} _SCREAMING_SNAKE_CASE : List[Any] = self.unet( sample=_A , timestep=_A , encoder_hidden_states=_A , added_cond_kwargs=_A , return_dict=_A , )[0] if do_classifier_free_guidance: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = noise_pred.split(latents.shape[1] , dim=1) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = noise_pred.chunk(2) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = variance_pred.chunk(2) _SCREAMING_SNAKE_CASE : List[str] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) _SCREAMING_SNAKE_CASE : List[str] = torch.cat([noise_pred, variance_pred_text] , dim=1) if not ( hasattr(self.scheduler.config , """variance_type""") and self.scheduler.config.variance_type in ["learned", "learned_range"] ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = noise_pred.split(latents.shape[1] , dim=1) # compute the previous noisy sample x_t -> x_t-1 _SCREAMING_SNAKE_CASE : Any = self.scheduler.step( _A , _A , _A , generator=_A , ).prev_sample # post-processing _SCREAMING_SNAKE_CASE : Optional[Any] = self.movq.decode(_A , force_not_quantize=_A)["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""") if output_type in ["np", "pil"]: _SCREAMING_SNAKE_CASE : str = image * 0.5 + 0.5 _SCREAMING_SNAKE_CASE : Union[str, Any] = image.clamp(0 , 1) _SCREAMING_SNAKE_CASE : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1).float().numpy() if output_type == "pil": _SCREAMING_SNAKE_CASE : List[str] = self.numpy_to_pil(_A) if not return_dict: return (image,) return ImagePipelineOutput(images=_A)
635
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCAmelCase_ = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
1
"""simple docstring""" import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class _snake_case ( unittest.TestCase , __snake_case ): """simple docstring""" def _lowerCAmelCase ( self : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = load_tool("""text-to-speech""") self.tool.setup() def _lowerCAmelCase ( self : Union[str, Any]): """simple docstring""" torch.manual_seed(0) _SCREAMING_SNAKE_CASE : Any = self.tool("""hey""") _SCREAMING_SNAKE_CASE : int = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , )) def _lowerCAmelCase ( self : Union[str, Any]): """simple docstring""" torch.manual_seed(0) _SCREAMING_SNAKE_CASE : List[Any] = self.tool("""hey""") _SCREAMING_SNAKE_CASE : str = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , ))
635
"""simple docstring""" import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: _SCREAMING_SNAKE_CASE : List[str] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Union[str, Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _SCREAMING_SNAKE_CASE : List[Any] = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: _SCREAMING_SNAKE_CASE : int = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : str = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : List[Any] = features.copy() if features else default_expected_features _SCREAMING_SNAKE_CASE : List[Any] = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) _SCREAMING_SNAKE_CASE : Optional[Any] = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: _SCREAMING_SNAKE_CASE : Tuple = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : int = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : Dict = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , split=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""" , [str, list] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> str: if issubclass(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = parquet_path elif issubclass(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = [parquet_path] _SCREAMING_SNAKE_CASE : Optional[Any] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Union[str, Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : str = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=("train",) )-> Union[str, Any]: assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for split in splits: _SCREAMING_SNAKE_CASE : int = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Optional[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _SCREAMING_SNAKE_CASE : Tuple = ParquetDatasetReader( {"""train""": parquet_path} , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: _SCREAMING_SNAKE_CASE : Optional[int] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Optional[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : List[str] = features.copy() if features else default_expected_features _SCREAMING_SNAKE_CASE : str = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) _SCREAMING_SNAKE_CASE : int = ParquetDatasetReader({"""train""": parquet_path} , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: if split: _SCREAMING_SNAKE_CASE : Union[str, Any] = {split: parquet_path} else: _SCREAMING_SNAKE_CASE : Optional[int] = """train""" _SCREAMING_SNAKE_CASE : Any = {"""train""": parquet_path, """test""": parquet_path} _SCREAMING_SNAKE_CASE : List[str] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : List[str] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : Union[str, Any] = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[Any]: _SCREAMING_SNAKE_CASE : List[str] = ParquetDatasetWriter(__SCREAMING_SNAKE_CASE , tmp_path / """foo.parquet""" ) assert writer.write() > 0 _SCREAMING_SNAKE_CASE : Tuple = pq.ParquetFile(tmp_path / """foo.parquet""" ) _SCREAMING_SNAKE_CASE : str = pf.read() assert dataset.data.table == output_table def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Dict = str(shared_datadir / """test_image_rgb.jpg""" ) _SCREAMING_SNAKE_CASE : Optional[Any] = {"""image""": [image_path]} _SCREAMING_SNAKE_CASE : Optional[Any] = Features({"""image""": Image()} ) _SCREAMING_SNAKE_CASE : Optional[int] = Dataset.from_dict(__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = ParquetDatasetWriter(__SCREAMING_SNAKE_CASE , tmp_path / """foo.parquet""" ) assert writer.write() > 0 _SCREAMING_SNAKE_CASE : List[str] = Dataset.from_parquet(str(tmp_path / """foo.parquet""" ) ) assert dataset.features == reloaded_dataset.features _SCREAMING_SNAKE_CASE : List[Any] = ParquetDatasetReader(str(tmp_path / """foo.parquet""" ) , streaming=__SCREAMING_SNAKE_CASE ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( """feature, expected""" , [ (Features({"""foo""": Value("""int32""" )} ), None), (Features({"""image""": Image(), """foo""": Value("""int32""" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"""nested""": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> int: assert get_writer_batch_size(__SCREAMING_SNAKE_CASE ) == expected
635
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCAmelCase_ = { '''configuration_maskformer''': ['''MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MaskFormerConfig'''], '''configuration_maskformer_swin''': ['''MaskFormerSwinConfig'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''MaskFormerFeatureExtractor'''] lowerCAmelCase_ = ['''MaskFormerImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MaskFormerForInstanceSegmentation''', '''MaskFormerModel''', '''MaskFormerPreTrainedModel''', ] lowerCAmelCase_ = [ '''MaskFormerSwinBackbone''', '''MaskFormerSwinModel''', '''MaskFormerSwinPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig from .configuration_maskformer_swin import MaskFormerSwinConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_maskformer import MaskFormerFeatureExtractor from .image_processing_maskformer import MaskFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskformer import ( MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskFormerForInstanceSegmentation, MaskFormerModel, MaskFormerPreTrainedModel, ) from .modeling_maskformer_swin import ( MaskFormerSwinBackbone, MaskFormerSwinModel, MaskFormerSwinPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
635
"""simple docstring""" def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise TypeError("""only integers accepted as input""" ) else: _SCREAMING_SNAKE_CASE : List[Any] = str(abs(__SCREAMING_SNAKE_CASE ) ) _SCREAMING_SNAKE_CASE : List[str] = [list(__SCREAMING_SNAKE_CASE ) for char in range(len(__SCREAMING_SNAKE_CASE ) )] for index in range(len(__SCREAMING_SNAKE_CASE ) ): num_transpositions[index].pop(__SCREAMING_SNAKE_CASE ) return max( int("""""".join(list(__SCREAMING_SNAKE_CASE ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('''doctest''').testmod()
635
1
"""simple docstring""" import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants lowerCAmelCase_ = Mapping[str, np.ndarray] lowerCAmelCase_ = Mapping[str, Any] # Is a nested dict. lowerCAmelCase_ = 0.01 @dataclasses.dataclass(frozen=__snake_case ) class _snake_case : """simple docstring""" a = 42 # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. a = 42 # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. a = 42 # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. a = 42 # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. a = 42 # [num_res, num_atom_type] # Chain indices for multi-chain predictions a = None # Optional remark about the protein. Included as a comment in output PDB # files a = None # Templates used to generate this protein (prediction-only) a = None # Chain corresponding to each parent a = None def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Protein: _SCREAMING_SNAKE_CASE : Optional[Any] = R"""(\[[A-Z]+\]\n)""" _SCREAMING_SNAKE_CASE : List[str] = [tag.strip() for tag in re.split(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0] _SCREAMING_SNAKE_CASE : Iterator[Tuple[str, List[str]]] = zip(tags[0::2] , [l.split("""\n""" ) for l in tags[1::2]] ) _SCREAMING_SNAKE_CASE : List[str] = ["N", "CA", "C"] _SCREAMING_SNAKE_CASE : List[Any] = None _SCREAMING_SNAKE_CASE : Any = None _SCREAMING_SNAKE_CASE : Any = None for g in groups: if "[PRIMARY]" == g[0]: _SCREAMING_SNAKE_CASE : int = g[1][0].strip() for i in range(len(__SCREAMING_SNAKE_CASE ) ): if seq[i] not in residue_constants.restypes: _SCREAMING_SNAKE_CASE : Optional[int] = """X""" # FIXME: strings are immutable _SCREAMING_SNAKE_CASE : List[Any] = np.array( [residue_constants.restype_order.get(__SCREAMING_SNAKE_CASE , residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: _SCREAMING_SNAKE_CASE : List[List[float]] = [] for axis in range(3 ): tertiary.append(list(map(__SCREAMING_SNAKE_CASE , g[1][axis].split() ) ) ) _SCREAMING_SNAKE_CASE : List[str] = np.array(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[Any] = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: _SCREAMING_SNAKE_CASE : List[str] = np.array(list(map({"""-""": 0, """+""": 1}.get , g[1][0].strip() ) ) ) _SCREAMING_SNAKE_CASE : str = np.zeros( ( len(__SCREAMING_SNAKE_CASE ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=__SCREAMING_SNAKE_CASE , atom_mask=__SCREAMING_SNAKE_CASE , aatype=__SCREAMING_SNAKE_CASE , residue_index=np.arange(len(__SCREAMING_SNAKE_CASE ) ) , b_factors=__SCREAMING_SNAKE_CASE , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0 )-> List[str]: _SCREAMING_SNAKE_CASE : List[str] = [] _SCREAMING_SNAKE_CASE : Union[str, Any] = prot.remark if remark is not None: pdb_headers.append(F"""REMARK {remark}""" ) _SCREAMING_SNAKE_CASE : Optional[int] = prot.parents _SCREAMING_SNAKE_CASE : int = prot.parents_chain_index if parents is not None and parents_chain_index is not None: _SCREAMING_SNAKE_CASE : Optional[Any] = [p for i, p in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if i == chain_id] if parents is None or len(__SCREAMING_SNAKE_CASE ) == 0: _SCREAMING_SNAKE_CASE : Tuple = ["""N/A"""] pdb_headers.append(F"""PARENT {" ".join(__SCREAMING_SNAKE_CASE )}""" ) return pdb_headers def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> str: _SCREAMING_SNAKE_CASE : List[str] = [] _SCREAMING_SNAKE_CASE : Dict = pdb_str.split("""\n""" ) _SCREAMING_SNAKE_CASE : Any = prot.remark if remark is not None: out_pdb_lines.append(F"""REMARK {remark}""" ) _SCREAMING_SNAKE_CASE : List[List[str]] if prot.parents is not None and len(prot.parents ) > 0: _SCREAMING_SNAKE_CASE : Union[str, Any] = [] if prot.parents_chain_index is not None: _SCREAMING_SNAKE_CASE : Dict[str, List[str]] = {} for p, i in zip(prot.parents , prot.parents_chain_index ): parent_dict.setdefault(str(__SCREAMING_SNAKE_CASE ) , [] ) parent_dict[str(__SCREAMING_SNAKE_CASE )].append(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[Any] = max([int(__SCREAMING_SNAKE_CASE ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): _SCREAMING_SNAKE_CASE : Tuple = parent_dict.get(str(__SCREAMING_SNAKE_CASE ) , ["""N/A"""] ) parents_per_chain.append(__SCREAMING_SNAKE_CASE ) else: parents_per_chain.append(list(prot.parents ) ) else: _SCREAMING_SNAKE_CASE : Union[str, Any] = [["""N/A"""]] def make_parent_line(__SCREAMING_SNAKE_CASE ) -> str: return F"""PARENT {" ".join(__SCREAMING_SNAKE_CASE )}""" out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for i, l in enumerate(__SCREAMING_SNAKE_CASE ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(__SCREAMING_SNAKE_CASE ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = parents_per_chain[chain_counter] else: _SCREAMING_SNAKE_CASE : Tuple = ["""N/A"""] out_pdb_lines.append(make_parent_line(__SCREAMING_SNAKE_CASE ) ) return "\n".join(__SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> str: _SCREAMING_SNAKE_CASE : List[Any] = residue_constants.restypes + ["""X"""] def res_atoa(__SCREAMING_SNAKE_CASE ) -> str: return residue_constants.restype_atoa.get(restypes[r] , """UNK""" ) _SCREAMING_SNAKE_CASE : List[str] = residue_constants.atom_types _SCREAMING_SNAKE_CASE : List[str] = [] _SCREAMING_SNAKE_CASE : int = prot.atom_mask _SCREAMING_SNAKE_CASE : Optional[Any] = prot.aatype _SCREAMING_SNAKE_CASE : int = prot.atom_positions _SCREAMING_SNAKE_CASE : List[str] = prot.residue_index.astype(np.intaa ) _SCREAMING_SNAKE_CASE : Optional[int] = prot.b_factors _SCREAMING_SNAKE_CASE : Optional[int] = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError("""Invalid aatypes.""" ) _SCREAMING_SNAKE_CASE : int = get_pdb_headers(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: pdb_lines.extend(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = aatype.shape[0] _SCREAMING_SNAKE_CASE : Optional[Any] = 1 _SCREAMING_SNAKE_CASE : Dict = 0 _SCREAMING_SNAKE_CASE : Union[str, Any] = string.ascii_uppercase _SCREAMING_SNAKE_CASE : int = None # Add all atom sites. for i in range(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(__SCREAMING_SNAKE_CASE , atom_positions[i] , atom_mask[i] , b_factors[i] ): if mask < 0.5: continue _SCREAMING_SNAKE_CASE : List[str] = """ATOM""" _SCREAMING_SNAKE_CASE : Any = atom_name if len(__SCREAMING_SNAKE_CASE ) == 4 else F""" {atom_name}""" _SCREAMING_SNAKE_CASE : Optional[int] = """""" _SCREAMING_SNAKE_CASE : Dict = """""" _SCREAMING_SNAKE_CASE : Union[str, Any] = 1.00 _SCREAMING_SNAKE_CASE : Tuple = atom_name[0] # Protein supports only C, N, O, S, this works. _SCREAMING_SNAKE_CASE : Tuple = """""" _SCREAMING_SNAKE_CASE : Dict = """A""" if chain_index is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! _SCREAMING_SNAKE_CASE : Optional[int] = ( F"""{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}""" F"""{res_name_a:>3} {chain_tag:>1}""" F"""{residue_index[i]:>4}{insertion_code:>1} """ F"""{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}""" F"""{occupancy:>6.2f}{b_factor:>6.2f} """ F"""{element:>2}{charge:>2}""" ) pdb_lines.append(__SCREAMING_SNAKE_CASE ) atom_index += 1 _SCREAMING_SNAKE_CASE : Optional[Any] = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : int = chain_index[i + 1] if should_terminate: # Close the chain. _SCREAMING_SNAKE_CASE : List[str] = """TER""" _SCREAMING_SNAKE_CASE : List[str] = ( F"""{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}""" ) pdb_lines.append(__SCREAMING_SNAKE_CASE ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) pdb_lines.append("""END""" ) pdb_lines.append("""""" ) return "\n".join(__SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> np.ndarray: return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def lowerCamelCase_(__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 , )-> Protein: return Protein( aatype=features["""aatype"""] , atom_positions=result["""final_atom_positions"""] , atom_mask=result["""final_atom_mask"""] , residue_index=features["""residue_index"""] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result["""final_atom_mask"""] ) , chain_index=__SCREAMING_SNAKE_CASE , remark=__SCREAMING_SNAKE_CASE , parents=__SCREAMING_SNAKE_CASE , parents_chain_index=__SCREAMING_SNAKE_CASE , )
635
"""simple docstring""" import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers import AutoModelForCausalLM @require_torch class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : Any = -1 _SCREAMING_SNAKE_CASE : List[str] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : Dict = model.generate(_A , max_new_tokens=1_0 , do_sample=_A) _SCREAMING_SNAKE_CASE : Dict = tokenizer.decode(greedy_ids[0]) with CaptureStdout() as cs: _SCREAMING_SNAKE_CASE : Any = TextStreamer(_A) model.generate(_A , max_new_tokens=1_0 , do_sample=_A , streamer=_A) # The greedy text should be printed to stdout, except for the final "\n" in the streamer _SCREAMING_SNAKE_CASE : str = cs.out[:-1] self.assertEqual(_A , _A) def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : Any = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : List[Any] = -1 _SCREAMING_SNAKE_CASE : str = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = model.generate(_A , max_new_tokens=1_0 , do_sample=_A) _SCREAMING_SNAKE_CASE : Any = tokenizer.decode(greedy_ids[0]) _SCREAMING_SNAKE_CASE : List[Any] = TextIteratorStreamer(_A) _SCREAMING_SNAKE_CASE : Any = {"""input_ids""": input_ids, """max_new_tokens""": 1_0, """do_sample""": False, """streamer""": streamer} _SCREAMING_SNAKE_CASE : List[Any] = Thread(target=model.generate , kwargs=_A) thread.start() _SCREAMING_SNAKE_CASE : Any = """""" for new_text in streamer: streamer_text += new_text self.assertEqual(_A , _A) def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : Any = -1 _SCREAMING_SNAKE_CASE : Any = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = model.generate(_A , max_new_tokens=1_0 , do_sample=_A) _SCREAMING_SNAKE_CASE : str = greedy_ids[:, input_ids.shape[1] :] _SCREAMING_SNAKE_CASE : Dict = tokenizer.decode(new_greedy_ids[0]) with CaptureStdout() as cs: _SCREAMING_SNAKE_CASE : Any = TextStreamer(_A , skip_prompt=_A) model.generate(_A , max_new_tokens=1_0 , do_sample=_A , streamer=_A) # The greedy text should be printed to stdout, except for the final "\n" in the streamer _SCREAMING_SNAKE_CASE : Optional[int] = cs.out[:-1] self.assertEqual(_A , _A) def _lowerCAmelCase ( self : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained("""distilgpt2""") _SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForCausalLM.from_pretrained("""distilgpt2""").to(_A) _SCREAMING_SNAKE_CASE : int = -1 _SCREAMING_SNAKE_CASE : List[str] = torch.ones((1, 5) , device=_A).long() * model.config.bos_token_id with CaptureStdout() as cs: _SCREAMING_SNAKE_CASE : Optional[int] = TextStreamer(_A , skip_special_tokens=_A) model.generate(_A , max_new_tokens=1 , do_sample=_A , streamer=_A) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token _SCREAMING_SNAKE_CASE : Optional[Any] = cs.out[:-1] # Remove the final "\n" _SCREAMING_SNAKE_CASE : Tuple = tokenizer(_A , return_tensors="""pt""") self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1)) def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : List[Any] = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : Tuple = -1 _SCREAMING_SNAKE_CASE : Dict = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : int = TextIteratorStreamer(_A , timeout=0.001) _SCREAMING_SNAKE_CASE : List[Any] = {"""input_ids""": input_ids, """max_new_tokens""": 1_0, """do_sample""": False, """streamer""": streamer} _SCREAMING_SNAKE_CASE : List[str] = Thread(target=model.generate , kwargs=_A) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(_A): _SCREAMING_SNAKE_CASE : str = """""" for new_text in streamer: streamer_text += new_text
635
1
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device lowerCAmelCase_ = False class _snake_case ( unittest.TestCase ): """simple docstring""" pass @nightly @require_torch_gpu class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Tuple): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowerCAmelCase ( self : Union[str, Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = VersatileDiffusionTextToImagePipeline.from_pretrained("""shi-labs/versatile-diffusion""") # remove text_unet pipe.remove_unused_weights() pipe.to(_A) pipe.set_progress_bar_config(disable=_A) _SCREAMING_SNAKE_CASE : List[str] = """A painting of a squirrel eating a burger """ _SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0) _SCREAMING_SNAKE_CASE : str = pipe( prompt=_A , generator=_A , guidance_scale=7.5 , num_inference_steps=2 , output_type="""numpy""").images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(_A) _SCREAMING_SNAKE_CASE : List[str] = VersatileDiffusionTextToImagePipeline.from_pretrained(_A) pipe.to(_A) pipe.set_progress_bar_config(disable=_A) _SCREAMING_SNAKE_CASE : List[str] = generator.manual_seed(0) _SCREAMING_SNAKE_CASE : Any = pipe( prompt=_A , generator=_A , guidance_scale=7.5 , num_inference_steps=2 , output_type="""numpy""").images assert np.abs(image - new_image).sum() < 1e-5, "Models don't have the same forward pass" def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = VersatileDiffusionTextToImagePipeline.from_pretrained( """shi-labs/versatile-diffusion""" , torch_dtype=torch.floataa) pipe.to(_A) pipe.set_progress_bar_config(disable=_A) _SCREAMING_SNAKE_CASE : int = """A painting of a squirrel eating a burger """ _SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(0) _SCREAMING_SNAKE_CASE : Any = pipe( prompt=_A , generator=_A , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="""numpy""").images _SCREAMING_SNAKE_CASE : Dict = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) _SCREAMING_SNAKE_CASE : Optional[Any] = np.array([0.3_367, 0.3_169, 0.2_656, 0.3_870, 0.4_790, 0.3_796, 0.4_009, 0.4_878, 0.4_778]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
635
"""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 torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _snake_case ( __snake_case ): """simple docstring""" a = "facebook/bart-large-mnli" a = ( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) a = "text_classifier" a = AutoTokenizer a = AutoModelForSequenceClassification a = ["text", ["text"]] a = ["text"] def _lowerCAmelCase ( self : int): """simple docstring""" super().setup() _SCREAMING_SNAKE_CASE : Any = self.model.config _SCREAMING_SNAKE_CASE : Any = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail"""): _SCREAMING_SNAKE_CASE : List[Any] = int(_A) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""") def _lowerCAmelCase ( self : Optional[Any] , _A : Tuple , _A : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = labels return self.pre_processor( [text] * len(_A) , [f"""This example is {label}""" for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def _lowerCAmelCase ( self : Tuple , _A : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : str = outputs.logits _SCREAMING_SNAKE_CASE : List[Any] = torch.argmax(logits[:, 2]).item() return self._labels[label_id]
635
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { '''configuration_clipseg''': [ '''CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPSegConfig''', '''CLIPSegTextConfig''', '''CLIPSegVisionConfig''', ], '''processing_clipseg''': ['''CLIPSegProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPSegModel''', '''CLIPSegPreTrainedModel''', '''CLIPSegTextModel''', '''CLIPSegVisionModel''', '''CLIPSegForImageSegmentation''', ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
"""simple docstring""" import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class _snake_case ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = AutoImageProcessor.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""") _SCREAMING_SNAKE_CASE : str = AutoModelForImageClassification.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""") model.to(_A) from datasets import load_dataset _SCREAMING_SNAKE_CASE : Any = load_dataset("""nielsr/rvlcdip-demo""") _SCREAMING_SNAKE_CASE : Any = dataset["""train"""][0]["""image"""].convert("""RGB""") _SCREAMING_SNAKE_CASE : str = image_processor(_A , return_tensors="""pt""").to(_A) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE : Any = model(**_A) _SCREAMING_SNAKE_CASE : List[Any] = outputs.logits _SCREAMING_SNAKE_CASE : List[str] = torch.Size((1, 1_6)) self.assertEqual(logits.shape , _A) _SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [-0.4_158, -0.4_092, -0.4_347] , device=_A , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , _A , atol=1e-4))
635
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = {'''configuration_ibert''': ['''IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''IBertConfig''', '''IBertOnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''IBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''IBertForMaskedLM''', '''IBertForMultipleChoice''', '''IBertForQuestionAnswering''', '''IBertForSequenceClassification''', '''IBertForTokenClassification''', '''IBertModel''', '''IBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_ibert import IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, IBertConfig, IBertOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ibert import ( IBERT_PRETRAINED_MODEL_ARCHIVE_LIST, IBertForMaskedLM, IBertForMultipleChoice, IBertForQuestionAnswering, IBertForSequenceClassification, IBertForTokenClassification, IBertModel, IBertPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
"""simple docstring""" import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class _snake_case ( __snake_case ): """simple docstring""" a = "M-CLIP" def __init__( self : Optional[Any] , _A : List[str]=1_0_2_4 , _A : Union[str, Any]=7_6_8 , **_A : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = transformerDimSize _SCREAMING_SNAKE_CASE : List[str] = imageDimSize super().__init__(**_A) class _snake_case ( __snake_case ): """simple docstring""" a = MCLIPConfig def __init__( self : Dict , _A : Optional[Any] , *_A : Any , **_A : Dict): """simple docstring""" super().__init__(_A , *_A , **_A) _SCREAMING_SNAKE_CASE : Tuple = XLMRobertaModel(_A) _SCREAMING_SNAKE_CASE : List[Any] = torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims) def _lowerCAmelCase ( self : Union[str, Any] , _A : str , _A : int): """simple docstring""" _SCREAMING_SNAKE_CASE : str = self.transformer(input_ids=_A , attention_mask=_A)[0] _SCREAMING_SNAKE_CASE : Optional[Any] = (embs * attention_mask.unsqueeze(2)).sum(dim=1) / attention_mask.sum(dim=1)[:, None] return self.LinearTransformation(_A), embs
635
1
"""simple docstring""" import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCAmelCase_ = 16 lowerCAmelCase_ = 32 def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 16 )-> str: _SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetDict( { """train""": dataset["""train"""].select(__SCREAMING_SNAKE_CASE ), """validation""": dataset["""train"""].select(__SCREAMING_SNAKE_CASE ), """test""": dataset["""validation"""], } ) def tokenize_function(__SCREAMING_SNAKE_CASE ): # max_length=None => use the model max length (it's actually the default) _SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _SCREAMING_SNAKE_CASE : str = datasets.map( __SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _SCREAMING_SNAKE_CASE : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__SCREAMING_SNAKE_CASE ): # On TPU it's best to pad everything to the same length or training will be very slow. _SCREAMING_SNAKE_CASE : Any = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _SCREAMING_SNAKE_CASE : Optional[Any] = 16 elif accelerator.mixed_precision != "no": _SCREAMING_SNAKE_CASE : Any = 8 else: _SCREAMING_SNAKE_CASE : Optional[int] = None return tokenizer.pad( __SCREAMING_SNAKE_CASE , padding="""longest""" , max_length=__SCREAMING_SNAKE_CASE , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" , ) # Instantiate dataloaders. _SCREAMING_SNAKE_CASE : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__SCREAMING_SNAKE_CASE , collate_fn=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[int] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__SCREAMING_SNAKE_CASE , collate_fn=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = DataLoader( tokenized_datasets["""test"""] , shuffle=__SCREAMING_SNAKE_CASE , collate_fn=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE ) return train_dataloader, eval_dataloader, test_dataloader def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: # New Code # _SCREAMING_SNAKE_CASE : Union[str, Any] = [] # Download the dataset _SCREAMING_SNAKE_CASE : Union[str, Any] = load_dataset("""glue""" , """mrpc""" ) # Create our splits _SCREAMING_SNAKE_CASE : Dict = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator _SCREAMING_SNAKE_CASE : Any = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _SCREAMING_SNAKE_CASE : Tuple = config["""lr"""] _SCREAMING_SNAKE_CASE : Tuple = int(config["""num_epochs"""] ) _SCREAMING_SNAKE_CASE : int = int(config["""seed"""] ) _SCREAMING_SNAKE_CASE : int = int(config["""batch_size"""] ) _SCREAMING_SNAKE_CASE : List[str] = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation _SCREAMING_SNAKE_CASE : Any = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _SCREAMING_SNAKE_CASE : List[str] = batch_size // MAX_GPU_BATCH_SIZE _SCREAMING_SNAKE_CASE : List[str] = MAX_GPU_BATCH_SIZE set_seed(__SCREAMING_SNAKE_CASE ) # New Code # # Create our folds: _SCREAMING_SNAKE_CASE : List[str] = kfold.split(np.zeros(datasets["""train"""].num_rows ) , datasets["""train"""]["""label"""] ) _SCREAMING_SNAKE_CASE : Optional[Any] = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = get_fold_dataloaders( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _SCREAMING_SNAKE_CASE : Any = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__SCREAMING_SNAKE_CASE ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _SCREAMING_SNAKE_CASE : Tuple = model.to(accelerator.device ) # Instantiate optimizer _SCREAMING_SNAKE_CASE : int = AdamW(params=model.parameters() , lr=__SCREAMING_SNAKE_CASE ) # Instantiate scheduler _SCREAMING_SNAKE_CASE : int = get_linear_schedule_with_warmup( optimizer=__SCREAMING_SNAKE_CASE , num_warmup_steps=100 , num_training_steps=(len(__SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = accelerator.prepare( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Now we train the model for epoch in range(__SCREAMING_SNAKE_CASE ): model.train() for step, batch in enumerate(__SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _SCREAMING_SNAKE_CASE : Optional[Any] = model(**__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = outputs.loss _SCREAMING_SNAKE_CASE : List[Any] = loss / gradient_accumulation_steps accelerator.backward(__SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[str] = model(**__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : str = outputs.logits.argmax(dim=-1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__SCREAMING_SNAKE_CASE , references=__SCREAMING_SNAKE_CASE , ) _SCREAMING_SNAKE_CASE : Optional[int] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , __SCREAMING_SNAKE_CASE ) # New Code # # We also run predictions on the test set at the very end _SCREAMING_SNAKE_CASE : str = [] for step, batch in enumerate(__SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[str] = model(**__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[Any] = outputs.logits _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(__SCREAMING_SNAKE_CASE , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: _SCREAMING_SNAKE_CASE : Optional[int] = torch.cat(__SCREAMING_SNAKE_CASE , dim=0 ) _SCREAMING_SNAKE_CASE : List[str] = torch.stack(__SCREAMING_SNAKE_CASE , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) _SCREAMING_SNAKE_CASE : int = metric.compute(predictions=__SCREAMING_SNAKE_CASE , references=__SCREAMING_SNAKE_CASE ) accelerator.print("""Average test metrics from all folds:""" , __SCREAMING_SNAKE_CASE ) def lowerCamelCase_()-> Optional[Any]: _SCREAMING_SNAKE_CASE : Any = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) # New Code # parser.add_argument("""--num_folds""" , type=__SCREAMING_SNAKE_CASE , default=3 , help="""The number of splits to perform across the dataset""" ) _SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args() _SCREAMING_SNAKE_CASE : Optional[int] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
635
"""simple docstring""" from decimal import Decimal, getcontext from math import ceil, factorial def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> str: if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise TypeError("""Undefined for non-integers""" ) elif precision < 1: raise ValueError("""Undefined for non-natural numbers""" ) _SCREAMING_SNAKE_CASE : int = precision _SCREAMING_SNAKE_CASE : Dict = ceil(precision / 14 ) _SCREAMING_SNAKE_CASE : int = 426_880 * Decimal(10_005 ).sqrt() _SCREAMING_SNAKE_CASE : Union[str, Any] = 1 _SCREAMING_SNAKE_CASE : str = 13_591_409 _SCREAMING_SNAKE_CASE : Tuple = Decimal(__SCREAMING_SNAKE_CASE ) for k in range(1 , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = factorial(6 * k ) // (factorial(3 * k ) * factorial(__SCREAMING_SNAKE_CASE ) ** 3) linear_term += 545_140_134 exponential_term *= -262_537_412_640_768_000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": lowerCAmelCase_ = 50 print(F"The first {n} digits of pi is: {pi(n)}")
635
1
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[str]: # Initialise PyTorch model _SCREAMING_SNAKE_CASE : Union[str, Any] = BertConfig.from_json_file(__SCREAMING_SNAKE_CASE ) print(F"""Building PyTorch model from configuration: {config}""" ) _SCREAMING_SNAKE_CASE : List[Any] = BertForPreTraining(__SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_bert(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) lowerCAmelCase_ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
635
"""simple docstring""" import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file _SCREAMING_SNAKE_CASE : Optional[int] = TapasConfig.from_json_file(__SCREAMING_SNAKE_CASE ) # set absolute/relative position embeddings parameter _SCREAMING_SNAKE_CASE : Dict = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": _SCREAMING_SNAKE_CASE : str = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "WTQ": # run_task_main.py hparams _SCREAMING_SNAKE_CASE : Optional[int] = 4 _SCREAMING_SNAKE_CASE : Any = True # hparam_utils.py hparams _SCREAMING_SNAKE_CASE : Any = 0.66_46_94 _SCREAMING_SNAKE_CASE : str = 0.20_79_51 _SCREAMING_SNAKE_CASE : str = 0.12_11_94 _SCREAMING_SNAKE_CASE : List[Any] = True _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = 0.0_35_25_13 _SCREAMING_SNAKE_CASE : Optional[Any] = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams _SCREAMING_SNAKE_CASE : int = 4 _SCREAMING_SNAKE_CASE : Tuple = False # hparam_utils.py hparams _SCREAMING_SNAKE_CASE : Any = 36.45_19 _SCREAMING_SNAKE_CASE : Union[str, Any] = 0.90_34_21 _SCREAMING_SNAKE_CASE : Optional[Any] = 2_22.0_88 _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Optional[int] = True _SCREAMING_SNAKE_CASE : Dict = 0.76_31_41 _SCREAMING_SNAKE_CASE : Union[str, Any] = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "TABFACT": _SCREAMING_SNAKE_CASE : int = TapasForSequenceClassification(config=__SCREAMING_SNAKE_CASE ) elif task == "MLM": _SCREAMING_SNAKE_CASE : int = TapasForMaskedLM(config=__SCREAMING_SNAKE_CASE ) elif task == "INTERMEDIATE_PRETRAINING": _SCREAMING_SNAKE_CASE : int = TapasModel(config=__SCREAMING_SNAKE_CASE ) else: raise ValueError(F"""Task {task} not supported.""" ) print(F"""Building PyTorch model from configuration: {config}""" ) # Load weights from tf checkpoint load_tf_weights_in_tapas(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Save pytorch-model (weights and configuration) print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) # Save tokenizer files print(F"""Save tokenizer files to {pytorch_dump_path}""" ) _SCREAMING_SNAKE_CASE : str = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + """vocab.txt""" , model_max_length=512 ) tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) print("""Used relative position embeddings:""" , model.config.reset_position_index_per_cell ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--task''', default='''SQA''', type=str, help='''Model task for which to convert a checkpoint. Defaults to SQA.''' ) parser.add_argument( '''--reset_position_index_per_cell''', default=False, action='''store_true''', help='''Whether to use relative position embeddings or not. Defaults to True.''', ) parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--tapas_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained TAPAS model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) lowerCAmelCase_ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
635
1
"""simple docstring""" # Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries import numpy as np from matplotlib import pyplot as plt from sklearn import datasets def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[int]: return 1 / (1 + np.exp(-z )) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: return (-y * np.log(__SCREAMING_SNAKE_CASE ) - (1 - y) * np.log(1 - h )).mean() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Any: _SCREAMING_SNAKE_CASE : List[Any] = np.dot(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return np.sum(y * scores - np.log(1 + np.exp(__SCREAMING_SNAKE_CASE ) ) ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=70_000 )-> Optional[int]: _SCREAMING_SNAKE_CASE : Tuple = np.zeros(x.shape[1] ) for iterations in range(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = np.dot(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[Any] = sigmoid_function(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Union[str, Any] = np.dot(x.T , h - y ) / y.size _SCREAMING_SNAKE_CASE : Any = theta - alpha * gradient # updating the weights _SCREAMING_SNAKE_CASE : Optional[Any] = np.dot(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[int] = sigmoid_function(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[Any] = cost_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if iterations % 100 == 0: print(F"""loss: {j} \t""" ) # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": lowerCAmelCase_ = datasets.load_iris() lowerCAmelCase_ = iris.data[:, :2] lowerCAmelCase_ = (iris.target != 0) * 1 lowerCAmelCase_ = 0.1 lowerCAmelCase_ = logistic_reg(alpha, x, y, max_iterations=70000) print('''theta: ''', theta) # printing the theta i.e our weights vector def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> List[Any]: return sigmoid_function( np.dot(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color='''b''', label='''0''') plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color='''r''', label='''1''') ((lowerCAmelCase_) , (lowerCAmelCase_)) = (x[:, 0].min(), x[:, 0].max()) ((lowerCAmelCase_) , (lowerCAmelCase_)) = (x[:, 1].min(), x[:, 1].max()) ((lowerCAmelCase_) , (lowerCAmelCase_)) = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max)) lowerCAmelCase_ = np.c_[xxa.ravel(), xxa.ravel()] lowerCAmelCase_ = predict_prob(grid).reshape(xxa.shape) plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors='''black''') plt.legend() plt.show()
635
"""simple docstring""" from typing import Any import numpy as np def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> bool: return np.array_equal(__SCREAMING_SNAKE_CASE , matrix.conjugate().T ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Any: _SCREAMING_SNAKE_CASE : Optional[int] = v.conjugate().T _SCREAMING_SNAKE_CASE : Optional[int] = v_star.dot(__SCREAMING_SNAKE_CASE ) assert isinstance(__SCREAMING_SNAKE_CASE , np.ndarray ) return (v_star_dot.dot(__SCREAMING_SNAKE_CASE )) / (v_star.dot(__SCREAMING_SNAKE_CASE )) def lowerCamelCase_()-> None: _SCREAMING_SNAKE_CASE : Optional[Any] = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) _SCREAMING_SNAKE_CASE : int = np.array([[1], [2], [3]] ) assert is_hermitian(__SCREAMING_SNAKE_CASE ), F"""{a} is not hermitian.""" print(rayleigh_quotient(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) _SCREAMING_SNAKE_CASE : int = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(__SCREAMING_SNAKE_CASE ), F"""{a} is not hermitian.""" assert rayleigh_quotient(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
635
1
"""simple docstring""" import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS_MODULES from ..packaged_modules.parquet.parquet import Parquet from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = np.inf def set_batch_size(__SCREAMING_SNAKE_CASE ) -> None: nonlocal batch_size if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = min(__SCREAMING_SNAKE_CASE , config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = min(__SCREAMING_SNAKE_CASE , config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and feature.dtype == "binary": _SCREAMING_SNAKE_CASE : Tuple = min(__SCREAMING_SNAKE_CASE , config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS ) _visit(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return None if batch_size is np.inf else batch_size class _snake_case ( __snake_case ): """simple docstring""" def __init__( self : int , _A : NestedDataStructureLike[PathLike] , _A : Optional[NamedSplit] = None , _A : Optional[Features] = None , _A : str = None , _A : bool = False , _A : bool = False , _A : Optional[int] = None , **_A : Any , ): """simple docstring""" super().__init__( _A , split=_A , features=_A , cache_dir=_A , keep_in_memory=_A , streaming=_A , num_proc=_A , **_A , ) _SCREAMING_SNAKE_CASE : Tuple = path_or_paths if isinstance(_A , _A) else {self.split: path_or_paths} _SCREAMING_SNAKE_CASE : List[Any] = _PACKAGED_DATASETS_MODULES["""parquet"""][1] _SCREAMING_SNAKE_CASE : Dict = Parquet( cache_dir=_A , data_files=_A , features=_A , hash=_A , **_A , ) def _lowerCAmelCase ( self : Any): """simple docstring""" if self.streaming: _SCREAMING_SNAKE_CASE : List[str] = self.builder.as_streaming_dataset(split=self.split) # Build regular (map-style) dataset else: _SCREAMING_SNAKE_CASE : str = None _SCREAMING_SNAKE_CASE : Any = None _SCREAMING_SNAKE_CASE : List[Any] = None _SCREAMING_SNAKE_CASE : Any = None self.builder.download_and_prepare( download_config=_A , download_mode=_A , verification_mode=_A , base_path=_A , num_proc=self.num_proc , ) _SCREAMING_SNAKE_CASE : Dict = self.builder.as_dataset( split=self.split , verification_mode=_A , in_memory=self.keep_in_memory) return dataset class _snake_case : """simple docstring""" def __init__( self : Optional[int] , _A : Dataset , _A : Union[PathLike, BinaryIO] , _A : Optional[int] = None , **_A : List[Any] , ): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = dataset _SCREAMING_SNAKE_CASE : str = path_or_buf _SCREAMING_SNAKE_CASE : Optional[Any] = batch_size or get_writer_batch_size(dataset.features) _SCREAMING_SNAKE_CASE : Optional[int] = parquet_writer_kwargs def _lowerCAmelCase ( self : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE if isinstance(self.path_or_buf , (str, bytes, os.PathLike)): with open(self.path_or_buf , """wb+""") as buffer: _SCREAMING_SNAKE_CASE : Optional[Any] = self._write(file_obj=_A , batch_size=_A , **self.parquet_writer_kwargs) else: _SCREAMING_SNAKE_CASE : Optional[int] = self._write(file_obj=self.path_or_buf , batch_size=_A , **self.parquet_writer_kwargs) return written def _lowerCAmelCase ( self : Optional[Any] , _A : BinaryIO , _A : int , **_A : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = 0 _SCREAMING_SNAKE_CASE : List[str] = parquet_writer_kwargs.pop("""path_or_buf""" , _A) _SCREAMING_SNAKE_CASE : Any = self.dataset.features.arrow_schema _SCREAMING_SNAKE_CASE : List[str] = pq.ParquetWriter(_A , schema=_A , **_A) for offset in logging.tqdm( range(0 , len(self.dataset) , _A) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating parquet from Arrow format""" , ): _SCREAMING_SNAKE_CASE : Union[str, Any] = query_table( table=self.dataset._data , key=slice(_A , offset + batch_size) , indices=self.dataset._indices if self.dataset._indices is not None else None , ) writer.write_table(_A) written += batch.nbytes writer.close() return written
635
"""simple docstring""" from __future__ import annotations def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , )-> tuple: if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError("""You cannot supply more or less than 2 values""" ) elif electron_conc < 0: raise ValueError("""Electron concentration cannot be negative in a semiconductor""" ) elif hole_conc < 0: raise ValueError("""Hole concentration cannot be negative in a semiconductor""" ) elif intrinsic_conc < 0: raise ValueError( """Intrinsic concentration cannot be negative in a semiconductor""" ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
635
1
"""simple docstring""" import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList lowerCAmelCase_ = ['''\nclass''', '''\ndef''', '''\n#''', '''\n@''', '''\nprint''', '''\nif'''] class _snake_case ( __snake_case ): """simple docstring""" def __init__( self : Optional[int] , _A : List[str] , _A : str , _A : List[Any]=None , _A : Union[str, Any]=1): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = tokenizer _SCREAMING_SNAKE_CASE : int = dataset _SCREAMING_SNAKE_CASE : Tuple = len(_A) if n_tasks is None else n_tasks _SCREAMING_SNAKE_CASE : Tuple = n_copies def __iter__( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = [] for task in range(self.n_tasks): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]["""prompt"""].strip()) _SCREAMING_SNAKE_CASE : Any = self.tokenizer(_A , padding=_A , return_tensors="""pt""") for task in range(self.n_tasks): for _ in range(self.n_copies): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class _snake_case ( __snake_case ): """simple docstring""" def __init__( self : Tuple , _A : int , _A : str , _A : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : int = start_length _SCREAMING_SNAKE_CASE : Dict = eof_strings _SCREAMING_SNAKE_CASE : Any = tokenizer def __call__( self : Union[str, Any] , _A : List[str] , _A : Union[str, Any] , **_A : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.batch_decode(input_ids[:, self.start_length :]) _SCREAMING_SNAKE_CASE : str = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings)) return all(_A) def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> List[str]: _SCREAMING_SNAKE_CASE : Any = re.split("""(%s)""" % """|""".join(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # last string should be "" return "".join(string_list[:-2] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=20 , **__SCREAMING_SNAKE_CASE )-> int: _SCREAMING_SNAKE_CASE : List[str] = defaultdict(__SCREAMING_SNAKE_CASE ) # dict of list of generated tokens for step, batch in tqdm(enumerate(__SCREAMING_SNAKE_CASE ) ): with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[str] = batch["""ids"""].shape[-1] _SCREAMING_SNAKE_CASE : Any = accelerator.unwrap_model(__SCREAMING_SNAKE_CASE ).generate( input_ids=batch["""ids"""][:, : batch["""input_len"""]] , num_return_sequences=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # each task is generated batch_size times _SCREAMING_SNAKE_CASE : Any = batch["""task_id"""].repeat(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[int] = accelerator.pad_across_processes( __SCREAMING_SNAKE_CASE , dim=1 , pad_index=tokenizer.pad_token_id ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = accelerator.gather((generated_tokens, generated_tasks) ) _SCREAMING_SNAKE_CASE : str = generated_tokens.cpu().numpy() _SCREAMING_SNAKE_CASE : Any = generated_tasks.cpu().numpy() for task, generated_tokens in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): gen_token_dict[task].append(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [[] for _ in range(__SCREAMING_SNAKE_CASE )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: _SCREAMING_SNAKE_CASE : Any = tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE ) code_gens[task].append(remove_last_block(__SCREAMING_SNAKE_CASE ) ) return code_gens def lowerCamelCase_()-> Any: # Setup configuration _SCREAMING_SNAKE_CASE : Union[str, Any] = HfArgumentParser(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric _SCREAMING_SNAKE_CASE : Optional[int] = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing _SCREAMING_SNAKE_CASE : Optional[Any] = """false""" if args.num_workers is None: _SCREAMING_SNAKE_CASE : Optional[Any] = multiprocessing.cpu_count() # Use dataset load to feed to accelerate _SCREAMING_SNAKE_CASE : str = Accelerator() set_seed(args.seed , device_specific=__SCREAMING_SNAKE_CASE ) # Load model and tokenizer _SCREAMING_SNAKE_CASE : Union[str, Any] = AutoTokenizer.from_pretrained(args.model_ckpt ) _SCREAMING_SNAKE_CASE : List[str] = tokenizer.eos_token _SCREAMING_SNAKE_CASE : int = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings _SCREAMING_SNAKE_CASE : Optional[int] = { """do_sample""": args.do_sample, """temperature""": args.temperature, """max_new_tokens""": args.max_new_tokens, """top_p""": args.top_p, """top_k""": args.top_k, """stopping_criteria""": StoppingCriteriaList([EndOfFunctionCriteria(0 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )] ), } # Load evaluation dataset and metric _SCREAMING_SNAKE_CASE : Tuple = load_dataset("""openai_humaneval""" ) _SCREAMING_SNAKE_CASE : Any = load_metric("""code_eval""" ) _SCREAMING_SNAKE_CASE : Any = args.num_tasks if args.num_tasks is not None else len(human_eval["""test"""] ) _SCREAMING_SNAKE_CASE : Any = args.n_samples // args.batch_size _SCREAMING_SNAKE_CASE : Optional[int] = TokenizedDataset(__SCREAMING_SNAKE_CASE , human_eval["""test"""] , n_copies=__SCREAMING_SNAKE_CASE , n_tasks=__SCREAMING_SNAKE_CASE ) # do not confuse args.batch_size, which is actually the num_return_sequences _SCREAMING_SNAKE_CASE : List[Any] = DataLoader(__SCREAMING_SNAKE_CASE , batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: _SCREAMING_SNAKE_CASE : Optional[int] = code_eval_metric.compute(references=[""""""] , predictions=[[""""""]] ) except ValueError as exception: print( """Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL=\"1\"`""" """ flag to enable code evaluation.""" ) raise exception _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = accelerator.prepare(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[str] = complete_code( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , n_tasks=__SCREAMING_SNAKE_CASE , batch_size=args.batch_size , **__SCREAMING_SNAKE_CASE , ) if accelerator.is_main_process: _SCREAMING_SNAKE_CASE : Any = [] for task in tqdm(range(__SCREAMING_SNAKE_CASE ) ): _SCREAMING_SNAKE_CASE : Optional[Any] = human_eval["""test"""][task]["""test"""] _SCREAMING_SNAKE_CASE : Any = F"""check({human_eval["test"][task]["entry_point"]})""" references.append("""\n""" + test_func + """\n""" + entry_point ) # Evaluate completions with "code_eval" metric _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = code_eval_metric.compute( references=__SCREAMING_SNAKE_CASE , predictions=__SCREAMING_SNAKE_CASE , num_workers=args.num_workers ) print(F"""Results: {pass_at_k}""" ) # Save results to json file with open(args.output_file , """w""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
635
"""simple docstring""" import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCAmelCase_ = 16 lowerCAmelCase_ = 32 def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 16 )-> str: _SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetDict( { """train""": dataset["""train"""].select(__SCREAMING_SNAKE_CASE ), """validation""": dataset["""train"""].select(__SCREAMING_SNAKE_CASE ), """test""": dataset["""validation"""], } ) def tokenize_function(__SCREAMING_SNAKE_CASE ): # max_length=None => use the model max length (it's actually the default) _SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _SCREAMING_SNAKE_CASE : str = datasets.map( __SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _SCREAMING_SNAKE_CASE : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__SCREAMING_SNAKE_CASE ): # On TPU it's best to pad everything to the same length or training will be very slow. _SCREAMING_SNAKE_CASE : Any = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _SCREAMING_SNAKE_CASE : Optional[Any] = 16 elif accelerator.mixed_precision != "no": _SCREAMING_SNAKE_CASE : Any = 8 else: _SCREAMING_SNAKE_CASE : Optional[int] = None return tokenizer.pad( __SCREAMING_SNAKE_CASE , padding="""longest""" , max_length=__SCREAMING_SNAKE_CASE , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" , ) # Instantiate dataloaders. _SCREAMING_SNAKE_CASE : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__SCREAMING_SNAKE_CASE , collate_fn=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[int] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__SCREAMING_SNAKE_CASE , collate_fn=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = DataLoader( tokenized_datasets["""test"""] , shuffle=__SCREAMING_SNAKE_CASE , collate_fn=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE ) return train_dataloader, eval_dataloader, test_dataloader def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: # New Code # _SCREAMING_SNAKE_CASE : Union[str, Any] = [] # Download the dataset _SCREAMING_SNAKE_CASE : Union[str, Any] = load_dataset("""glue""" , """mrpc""" ) # Create our splits _SCREAMING_SNAKE_CASE : Dict = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator _SCREAMING_SNAKE_CASE : Any = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _SCREAMING_SNAKE_CASE : Tuple = config["""lr"""] _SCREAMING_SNAKE_CASE : Tuple = int(config["""num_epochs"""] ) _SCREAMING_SNAKE_CASE : int = int(config["""seed"""] ) _SCREAMING_SNAKE_CASE : int = int(config["""batch_size"""] ) _SCREAMING_SNAKE_CASE : List[str] = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation _SCREAMING_SNAKE_CASE : Any = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _SCREAMING_SNAKE_CASE : List[str] = batch_size // MAX_GPU_BATCH_SIZE _SCREAMING_SNAKE_CASE : List[str] = MAX_GPU_BATCH_SIZE set_seed(__SCREAMING_SNAKE_CASE ) # New Code # # Create our folds: _SCREAMING_SNAKE_CASE : List[str] = kfold.split(np.zeros(datasets["""train"""].num_rows ) , datasets["""train"""]["""label"""] ) _SCREAMING_SNAKE_CASE : Optional[Any] = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = get_fold_dataloaders( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _SCREAMING_SNAKE_CASE : Any = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__SCREAMING_SNAKE_CASE ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _SCREAMING_SNAKE_CASE : Tuple = model.to(accelerator.device ) # Instantiate optimizer _SCREAMING_SNAKE_CASE : int = AdamW(params=model.parameters() , lr=__SCREAMING_SNAKE_CASE ) # Instantiate scheduler _SCREAMING_SNAKE_CASE : int = get_linear_schedule_with_warmup( optimizer=__SCREAMING_SNAKE_CASE , num_warmup_steps=100 , num_training_steps=(len(__SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = accelerator.prepare( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Now we train the model for epoch in range(__SCREAMING_SNAKE_CASE ): model.train() for step, batch in enumerate(__SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _SCREAMING_SNAKE_CASE : Optional[Any] = model(**__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = outputs.loss _SCREAMING_SNAKE_CASE : List[Any] = loss / gradient_accumulation_steps accelerator.backward(__SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[str] = model(**__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : str = outputs.logits.argmax(dim=-1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__SCREAMING_SNAKE_CASE , references=__SCREAMING_SNAKE_CASE , ) _SCREAMING_SNAKE_CASE : Optional[int] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , __SCREAMING_SNAKE_CASE ) # New Code # # We also run predictions on the test set at the very end _SCREAMING_SNAKE_CASE : str = [] for step, batch in enumerate(__SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[str] = model(**__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[Any] = outputs.logits _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(__SCREAMING_SNAKE_CASE , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: _SCREAMING_SNAKE_CASE : Optional[int] = torch.cat(__SCREAMING_SNAKE_CASE , dim=0 ) _SCREAMING_SNAKE_CASE : List[str] = torch.stack(__SCREAMING_SNAKE_CASE , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) _SCREAMING_SNAKE_CASE : int = metric.compute(predictions=__SCREAMING_SNAKE_CASE , references=__SCREAMING_SNAKE_CASE ) accelerator.print("""Average test metrics from all folds:""" , __SCREAMING_SNAKE_CASE ) def lowerCamelCase_()-> Optional[Any]: _SCREAMING_SNAKE_CASE : Any = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) # New Code # parser.add_argument("""--num_folds""" , type=__SCREAMING_SNAKE_CASE , default=3 , help="""The number of splits to perform across the dataset""" ) _SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args() _SCREAMING_SNAKE_CASE : Optional[int] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
635
1
"""simple docstring""" import argparse import os import re import packaging.version lowerCAmelCase_ = '''examples/''' lowerCAmelCase_ = { '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(R'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(R'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), R'''\1version="VERSION",'''), '''doc''': (re.compile(R'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } lowerCAmelCase_ = { '''init''': '''src/transformers/__init__.py''', '''setup''': '''setup.py''', } lowerCAmelCase_ = '''README.md''' def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[Any]: with open(__SCREAMING_SNAKE_CASE , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: _SCREAMING_SNAKE_CASE : Dict = f.read() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = REPLACE_PATTERNS[pattern] _SCREAMING_SNAKE_CASE : List[Any] = replace.replace("""VERSION""" , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Any = re_pattern.sub(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) with open(__SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.write(__SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: for folder, directories, fnames in os.walk(__SCREAMING_SNAKE_CASE ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("""research_projects""" ) if "legacy" in directories: directories.remove("""legacy""" ) for fname in fnames: if fname.endswith(""".py""" ): update_version_in_file(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , pattern="""examples""" ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False )-> Optional[int]: for pattern, fname in REPLACE_FILES.items(): update_version_in_file(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if not patch: update_version_in_examples(__SCREAMING_SNAKE_CASE ) def lowerCamelCase_()-> Optional[int]: _SCREAMING_SNAKE_CASE : Tuple = """🤗 Transformers currently provides the following architectures""" _SCREAMING_SNAKE_CASE : Any = """1. Want to contribute a new model?""" with open(__SCREAMING_SNAKE_CASE , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: _SCREAMING_SNAKE_CASE : Any = f.readlines() # Find the start of the list. _SCREAMING_SNAKE_CASE : Dict = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 _SCREAMING_SNAKE_CASE : Union[str, Any] = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("""1.""" ): _SCREAMING_SNAKE_CASE : Union[str, Any] = lines[index].replace( """https://huggingface.co/docs/transformers/main/model_doc""" , """https://huggingface.co/docs/transformers/model_doc""" , ) index += 1 with open(__SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(__SCREAMING_SNAKE_CASE ) def lowerCamelCase_()-> Any: with open(REPLACE_FILES["""init"""] , """r""" ) as f: _SCREAMING_SNAKE_CASE : Dict = f.read() _SCREAMING_SNAKE_CASE : Dict = REPLACE_PATTERNS["""init"""][0].search(__SCREAMING_SNAKE_CASE ).groups()[0] return packaging.version.parse(__SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE=False )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Union[str, Any] = get_version() if patch and default_version.is_devrelease: raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" ) if default_version.is_devrelease: _SCREAMING_SNAKE_CASE : Any = default_version.base_version elif patch: _SCREAMING_SNAKE_CASE : Optional[Any] = F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: _SCREAMING_SNAKE_CASE : Dict = F"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. _SCREAMING_SNAKE_CASE : Union[str, Any] = input(F"""Which version are you releasing? [{default_version}]""" ) if len(__SCREAMING_SNAKE_CASE ) == 0: _SCREAMING_SNAKE_CASE : Any = default_version print(F"""Updating version to {version}.""" ) global_version_update(__SCREAMING_SNAKE_CASE , patch=__SCREAMING_SNAKE_CASE ) if not patch: print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() def lowerCamelCase_()-> Any: _SCREAMING_SNAKE_CASE : Optional[int] = get_version() _SCREAMING_SNAKE_CASE : Dict = F"""{current_version.major}.{current_version.minor + 1}.0.dev0""" _SCREAMING_SNAKE_CASE : Optional[int] = current_version.base_version # Check with the user we got that right. _SCREAMING_SNAKE_CASE : Optional[Any] = input(F"""Which version are we developing now? [{dev_version}]""" ) if len(__SCREAMING_SNAKE_CASE ) == 0: _SCREAMING_SNAKE_CASE : Optional[Any] = dev_version print(F"""Updating version to {version}.""" ) global_version_update(__SCREAMING_SNAKE_CASE ) print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') lowerCAmelCase_ = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
635
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { '''configuration_clipseg''': [ '''CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPSegConfig''', '''CLIPSegTextConfig''', '''CLIPSegVisionConfig''', ], '''processing_clipseg''': ['''CLIPSegProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPSegModel''', '''CLIPSegPreTrainedModel''', '''CLIPSegTextModel''', '''CLIPSegVisionModel''', '''CLIPSegForImageSegmentation''', ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
1
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING lowerCAmelCase_ = logging.get_logger(__name__) @add_end_docstrings(__snake_case ) class _snake_case ( __snake_case ): """simple docstring""" def __init__( self : List[str] , **_A : Union[str, Any]): """simple docstring""" super().__init__(**_A) requires_backends(self , """vision""") requires_backends(self , """torch""") if self.framework != "pt": raise ValueError(f"""The {self.__class__} is only available in PyTorch.""") self.check_model_type(_A) def _lowerCAmelCase ( self : Tuple , **_A : Union[str, Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = {} _SCREAMING_SNAKE_CASE : Dict = {} _SCREAMING_SNAKE_CASE : Dict = {} # preprocess args if "points_per_batch" in kwargs: _SCREAMING_SNAKE_CASE : Optional[int] = kwargs["""points_per_batch"""] if "points_per_crop" in kwargs: _SCREAMING_SNAKE_CASE : List[Any] = kwargs["""points_per_crop"""] if "crops_n_layers" in kwargs: _SCREAMING_SNAKE_CASE : Union[str, Any] = kwargs["""crops_n_layers"""] if "crop_overlap_ratio" in kwargs: _SCREAMING_SNAKE_CASE : List[str] = kwargs["""crop_overlap_ratio"""] if "crop_n_points_downscale_factor" in kwargs: _SCREAMING_SNAKE_CASE : List[str] = kwargs["""crop_n_points_downscale_factor"""] # postprocess args if "pred_iou_thresh" in kwargs: _SCREAMING_SNAKE_CASE : Any = kwargs["""pred_iou_thresh"""] if "stability_score_offset" in kwargs: _SCREAMING_SNAKE_CASE : Any = kwargs["""stability_score_offset"""] if "mask_threshold" in kwargs: _SCREAMING_SNAKE_CASE : int = kwargs["""mask_threshold"""] if "stability_score_thresh" in kwargs: _SCREAMING_SNAKE_CASE : str = kwargs["""stability_score_thresh"""] if "crops_nms_thresh" in kwargs: _SCREAMING_SNAKE_CASE : List[str] = kwargs["""crops_nms_thresh"""] if "output_rle_mask" in kwargs: _SCREAMING_SNAKE_CASE : int = kwargs["""output_rle_mask"""] if "output_bboxes_mask" in kwargs: _SCREAMING_SNAKE_CASE : Union[str, Any] = kwargs["""output_bboxes_mask"""] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self : str , _A : Any , *_A : int , _A : Optional[Any]=None , _A : Optional[Any]=None , **_A : Union[str, Any]): """simple docstring""" return super().__call__(_A , *_A , num_workers=_A , batch_size=_A , **_A) def _lowerCAmelCase ( self : int , _A : int , _A : Union[str, Any]=6_4 , _A : int = 0 , _A : float = 5_1_2 / 1_5_0_0 , _A : Optional[int] = 3_2 , _A : Optional[int] = 1 , ): """simple docstring""" _SCREAMING_SNAKE_CASE : int = load_image(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor.size["""longest_edge"""] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor.generate_crop_boxes( _A , _A , _A , _A , _A , _A) _SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor(images=_A , return_tensors="""pt""") with self.device_placement(): if self.framework == "pt": _SCREAMING_SNAKE_CASE : Dict = self.get_inference_context() with inference_context(): _SCREAMING_SNAKE_CASE : Dict = self._ensure_tensor_on_device(_A , device=self.device) _SCREAMING_SNAKE_CASE : Optional[int] = self.model.get_image_embeddings(model_inputs.pop("""pixel_values""")) _SCREAMING_SNAKE_CASE : List[Any] = image_embeddings _SCREAMING_SNAKE_CASE : Dict = grid_points.shape[1] _SCREAMING_SNAKE_CASE : int = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( """Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. """ """To return all points at once, set points_per_batch to None""") for i in range(0 , _A , _A): _SCREAMING_SNAKE_CASE : List[Any] = grid_points[:, i : i + points_per_batch, :, :] _SCREAMING_SNAKE_CASE : Any = input_labels[:, i : i + points_per_batch] _SCREAMING_SNAKE_CASE : Any = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def _lowerCAmelCase ( self : Optional[Any] , _A : Optional[int] , _A : Union[str, Any]=0.88 , _A : List[str]=0.95 , _A : Union[str, Any]=0 , _A : Union[str, Any]=1 , ): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = model_inputs.pop("""input_boxes""") _SCREAMING_SNAKE_CASE : Any = model_inputs.pop("""is_last""") _SCREAMING_SNAKE_CASE : Optional[int] = model_inputs.pop("""original_sizes""").tolist() _SCREAMING_SNAKE_CASE : Optional[int] = model_inputs.pop("""reshaped_input_sizes""").tolist() _SCREAMING_SNAKE_CASE : str = self.model(**_A) # post processing happens here in order to avoid CPU GPU copies of ALL the masks _SCREAMING_SNAKE_CASE : Any = model_outputs["""pred_masks"""] _SCREAMING_SNAKE_CASE : List[str] = self.image_processor.post_process_masks( _A , _A , _A , _A , binarize=_A) _SCREAMING_SNAKE_CASE : Tuple = model_outputs["""iou_scores"""] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , _A , _A , _A , _A , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def _lowerCAmelCase ( self : Tuple , _A : Tuple , _A : Tuple=False , _A : int=False , _A : Dict=0.7 , ): """simple docstring""" _SCREAMING_SNAKE_CASE : int = [] _SCREAMING_SNAKE_CASE : Union[str, Any] = [] _SCREAMING_SNAKE_CASE : Union[str, Any] = [] for model_output in model_outputs: all_scores.append(model_output.pop("""iou_scores""")) all_masks.extend(model_output.pop("""masks""")) all_boxes.append(model_output.pop("""boxes""")) _SCREAMING_SNAKE_CASE : Optional[int] = torch.cat(_A) _SCREAMING_SNAKE_CASE : Tuple = torch.cat(_A) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processor.post_process_for_mask_generation( _A , _A , _A , _A) _SCREAMING_SNAKE_CASE : List[str] = defaultdict(_A) for output in model_outputs: for k, v in output.items(): extra[k].append(_A) _SCREAMING_SNAKE_CASE : Dict = {} if output_rle_mask: _SCREAMING_SNAKE_CASE : Tuple = rle_mask if output_bboxes_mask: _SCREAMING_SNAKE_CASE : int = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
635
"""simple docstring""" import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class _snake_case : """simple docstring""" def __init__( self : int , _A : List[Any] , _A : int , _A : int): """simple docstring""" if dst_width < 0 or dst_height < 0: raise ValueError("""Destination width/height should be > 0""") _SCREAMING_SNAKE_CASE : str = img _SCREAMING_SNAKE_CASE : Optional[Any] = img.shape[1] _SCREAMING_SNAKE_CASE : Tuple = img.shape[0] _SCREAMING_SNAKE_CASE : Any = dst_width _SCREAMING_SNAKE_CASE : Any = dst_height _SCREAMING_SNAKE_CASE : Any = self.src_w / self.dst_w _SCREAMING_SNAKE_CASE : Dict = self.src_h / self.dst_h _SCREAMING_SNAKE_CASE : Optional[Any] = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta) * 2_5_5 ) def _lowerCAmelCase ( self : Tuple): """simple docstring""" for i in range(self.dst_h): for j in range(self.dst_w): _SCREAMING_SNAKE_CASE : Any = self.img[self.get_y(_A)][self.get_x(_A)] def _lowerCAmelCase ( self : int , _A : int): """simple docstring""" return int(self.ratio_x * x) def _lowerCAmelCase ( self : str , _A : int): """simple docstring""" return int(self.ratio_y * y) if __name__ == "__main__": lowerCAmelCase_ , lowerCAmelCase_ = 800, 600 lowerCAmelCase_ = imread('''image_data/lena.jpg''', 1) lowerCAmelCase_ = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}", n.output ) waitKey(0) destroyAllWindows()
635
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { '''configuration_table_transformer''': [ '''TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TableTransformerConfig''', '''TableTransformerOnnxConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TableTransformerForObjectDetection''', '''TableTransformerModel''', '''TableTransformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
"""simple docstring""" import argparse from collections import defaultdict def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> int: _SCREAMING_SNAKE_CASE : str = F"""{file}_{class_name}_{test_name}""" done_test[_id] += 1 with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: _SCREAMING_SNAKE_CASE : Union[str, Any] = f.readlines() _SCREAMING_SNAKE_CASE : Optional[Any] = F"""class {class_name}(""" _SCREAMING_SNAKE_CASE : List[Any] = F"""{4 * " "}def {test_name}(""" _SCREAMING_SNAKE_CASE : Tuple = F"""{8 * " "}{correct_line.split()[0]}""" _SCREAMING_SNAKE_CASE : List[Any] = F"""{16 * " "}{correct_line.split()[0]}""" _SCREAMING_SNAKE_CASE : List[str] = False _SCREAMING_SNAKE_CASE : Tuple = False _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[int] = False _SCREAMING_SNAKE_CASE : Any = 0 _SCREAMING_SNAKE_CASE : Optional[Any] = 0 _SCREAMING_SNAKE_CASE : Dict = [] for line in lines: if line.startswith(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = True elif in_class and line.startswith(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = True elif in_class and in_func and (line.startswith(__SCREAMING_SNAKE_CASE ) or line.startswith(__SCREAMING_SNAKE_CASE )): _SCREAMING_SNAKE_CASE : Dict = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: _SCREAMING_SNAKE_CASE : int = True if in_class and in_func and in_line: if ")" not in line: continue else: _SCREAMING_SNAKE_CASE : Any = True if in_class and in_func and in_line and insert_line: new_lines.append(F"""{spaces * " "}{correct_line}""" ) _SCREAMING_SNAKE_CASE : Optional[int] = False else: new_lines.append(__SCREAMING_SNAKE_CASE ) with open(__SCREAMING_SNAKE_CASE , """w""" ) as f: for line in new_lines: f.write(__SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None )-> Optional[Any]: if fail is not None: with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: _SCREAMING_SNAKE_CASE : Union[str, Any] = {l.strip() for l in f.readlines()} else: _SCREAMING_SNAKE_CASE : str = None with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: _SCREAMING_SNAKE_CASE : str = f.readlines() _SCREAMING_SNAKE_CASE : str = defaultdict(__SCREAMING_SNAKE_CASE ) for line in correct_lines: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = line.split(""";""" ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument('''--correct_filename''', help='''filename of tests with expected result''') parser.add_argument('''--fail_filename''', help='''filename of test failures''', type=str, default=None) lowerCAmelCase_ = parser.parse_args() main(args.correct_filename, args.fail_filename)
635
1
"""simple docstring""" import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = """ZinengTang/tvlt-base""" _SCREAMING_SNAKE_CASE : Optional[Any] = tempfile.mkdtemp() def _lowerCAmelCase ( self : str , **_A : Dict): """simple docstring""" return TvltImageProcessor.from_pretrained(self.checkpoint , **_A) def _lowerCAmelCase ( self : Optional[Any] , **_A : str): """simple docstring""" return TvltFeatureExtractor.from_pretrained(self.checkpoint , **_A) def _lowerCAmelCase ( self : List[Any]): """simple docstring""" shutil.rmtree(self.tmpdirname) def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = self.get_image_processor() _SCREAMING_SNAKE_CASE : Any = self.get_feature_extractor() _SCREAMING_SNAKE_CASE : Optional[Any] = TvltProcessor(image_processor=_A , feature_extractor=_A) processor.save_pretrained(self.tmpdirname) _SCREAMING_SNAKE_CASE : List[str] = TvltProcessor.from_pretrained(self.tmpdirname) self.assertIsInstance(processor.feature_extractor , _A) self.assertIsInstance(processor.image_processor , _A) def _lowerCAmelCase ( self : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE : int = self.get_image_processor() _SCREAMING_SNAKE_CASE : List[str] = self.get_feature_extractor() _SCREAMING_SNAKE_CASE : List[str] = TvltProcessor(image_processor=_A , feature_extractor=_A) _SCREAMING_SNAKE_CASE : int = np.ones([1_2_0_0_0]) _SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(_A , return_tensors="""np""") _SCREAMING_SNAKE_CASE : Union[str, Any] = processor(audio=_A , return_tensors="""np""") for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2) def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() _SCREAMING_SNAKE_CASE : Optional[Any] = self.get_feature_extractor() _SCREAMING_SNAKE_CASE : Union[str, Any] = TvltProcessor(image_processor=_A , feature_extractor=_A) _SCREAMING_SNAKE_CASE : List[str] = np.ones([3, 2_2_4, 2_2_4]) _SCREAMING_SNAKE_CASE : int = image_processor(_A , return_tensors="""np""") _SCREAMING_SNAKE_CASE : Union[str, Any] = processor(images=_A , return_tensors="""np""") for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2) def _lowerCAmelCase ( self : int): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = self.get_image_processor() _SCREAMING_SNAKE_CASE : Optional[Any] = self.get_feature_extractor() _SCREAMING_SNAKE_CASE : List[str] = TvltProcessor(image_processor=_A , feature_extractor=_A) _SCREAMING_SNAKE_CASE : Tuple = np.ones([1_2_0_0_0]) _SCREAMING_SNAKE_CASE : str = np.ones([3, 2_2_4, 2_2_4]) _SCREAMING_SNAKE_CASE : Any = processor(audio=_A , images=_A) self.assertListEqual(list(inputs.keys()) , ["""audio_values""", """audio_mask""", """pixel_values""", """pixel_mask"""]) # test if it raises when no input is passed with pytest.raises(_A): processor() def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() _SCREAMING_SNAKE_CASE : Optional[Any] = self.get_feature_extractor() _SCREAMING_SNAKE_CASE : List[str] = TvltProcessor(image_processor=_A , feature_extractor=_A) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="""`processor` and `image_processor`+`feature_extractor` model input names do not match""" , )
635
"""simple docstring""" import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel lowerCAmelCase_ = { '''text_branch''': '''text_model''', '''audio_branch''': '''audio_model.audio_encoder''', '''attn''': '''attention.self''', '''self.proj''': '''output.dense''', '''attention.self_mask''': '''attn_mask''', '''mlp.fc1''': '''intermediate.dense''', '''mlp.fc2''': '''output.dense''', '''norm1''': '''layernorm_before''', '''norm2''': '''layernorm_after''', '''bn0''': '''batch_norm''', } lowerCAmelCase_ = AutoFeatureExtractor.from_pretrained('''laion/clap-htsat-unfused''', truncation='''rand_trunc''') def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False )-> str: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = create_model( """HTSAT-tiny""" , """roberta""" , __SCREAMING_SNAKE_CASE , precision="""fp32""" , device="""cuda:0""" if torch.cuda.is_available() else """cpu""" , enable_fusion=__SCREAMING_SNAKE_CASE , fusion_type="""aff_2d""" if enable_fusion else None , ) return model, model_cfg def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = {} _SCREAMING_SNAKE_CASE : Optional[Any] = R""".*sequential.(\d+).*""" _SCREAMING_SNAKE_CASE : Any = R""".*_projection.(\d+).*""" for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: _SCREAMING_SNAKE_CASE : Optional[Any] = key.replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # replace sequential layers with list _SCREAMING_SNAKE_CASE : List[Any] = re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).group(1 ) _SCREAMING_SNAKE_CASE : Dict = key.replace(F"""sequential.{sequential_layer}.""" , F"""layers.{int(__SCREAMING_SNAKE_CASE )//3}.linear.""" ) elif re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = int(re.match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... _SCREAMING_SNAKE_CASE : Dict = 1 if projecton_layer == 0 else 2 _SCREAMING_SNAKE_CASE : Union[str, Any] = key.replace(F"""_projection.{projecton_layer}.""" , F"""_projection.linear{transformers_projection_layer}.""" ) if "audio" and "qkv" in key: # split qkv into query key and value _SCREAMING_SNAKE_CASE : Dict = value _SCREAMING_SNAKE_CASE : List[Any] = mixed_qkv.size(0 ) // 3 _SCREAMING_SNAKE_CASE : Optional[Any] = mixed_qkv[:qkv_dim] _SCREAMING_SNAKE_CASE : str = mixed_qkv[qkv_dim : qkv_dim * 2] _SCREAMING_SNAKE_CASE : Any = mixed_qkv[qkv_dim * 2 :] _SCREAMING_SNAKE_CASE : Dict = query_layer _SCREAMING_SNAKE_CASE : List[Any] = key_layer _SCREAMING_SNAKE_CASE : Dict = value_layer else: _SCREAMING_SNAKE_CASE : Optional[Any] = value return model_state_dict def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False )-> List[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = init_clap(__SCREAMING_SNAKE_CASE , enable_fusion=__SCREAMING_SNAKE_CASE ) clap_model.eval() _SCREAMING_SNAKE_CASE : Dict = clap_model.state_dict() _SCREAMING_SNAKE_CASE : Tuple = rename_state_dict(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : int = ClapConfig() _SCREAMING_SNAKE_CASE : Tuple = enable_fusion _SCREAMING_SNAKE_CASE : Dict = ClapModel(__SCREAMING_SNAKE_CASE ) # ignore the spectrogram embedding layer model.load_state_dict(__SCREAMING_SNAKE_CASE , strict=__SCREAMING_SNAKE_CASE ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) transformers_config.save_pretrained(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = 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('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument('''--enable_fusion''', action='''store_true''', help='''Whether to enable fusion or not''') lowerCAmelCase_ = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
635
1
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): """simple docstring""" a = AltDiffusionPipeline a = TEXT_TO_IMAGE_PARAMS a = TEXT_TO_IMAGE_BATCH_PARAMS a = TEXT_TO_IMAGE_IMAGE_PARAMS a = TEXT_TO_IMAGE_IMAGE_PARAMS def _lowerCAmelCase ( self : int): """simple docstring""" torch.manual_seed(0) _SCREAMING_SNAKE_CASE : int = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=3_2 , ) _SCREAMING_SNAKE_CASE : Optional[Any] = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=_A , set_alpha_to_one=_A , ) torch.manual_seed(0) _SCREAMING_SNAKE_CASE : Union[str, Any] = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) # TODO: address the non-deterministic text encoder (fails for save-load tests) # torch.manual_seed(0) # text_encoder_config = RobertaSeriesConfig( # hidden_size=32, # project_dim=32, # intermediate_size=37, # layer_norm_eps=1e-05, # num_attention_heads=4, # num_hidden_layers=5, # vocab_size=5002, # ) # text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config) torch.manual_seed(0) _SCREAMING_SNAKE_CASE : List[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , projection_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5_0_0_2 , ) _SCREAMING_SNAKE_CASE : Dict = CLIPTextModel(_A) _SCREAMING_SNAKE_CASE : Any = XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta""") _SCREAMING_SNAKE_CASE : List[str] = 7_7 _SCREAMING_SNAKE_CASE : List[Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _lowerCAmelCase ( self : Tuple , _A : List[str] , _A : str=0): """simple docstring""" if str(_A).startswith("""mps"""): _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.manual_seed(_A) else: _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device=_A).manual_seed(_A) _SCREAMING_SNAKE_CASE : List[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _lowerCAmelCase ( self : List[str]): """simple docstring""" super().test_attention_slicing_forward_pass(expected_max_diff=3e-3) def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3) def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = """cpu""" # ensure determinism for the device-dependent torch.Generator _SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_components() torch.manual_seed(0) _SCREAMING_SNAKE_CASE : Union[str, Any] = RobertaSeriesConfig( hidden_size=3_2 , project_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5_0_0_2 , ) # TODO: remove after fixing the non-deterministic text encoder _SCREAMING_SNAKE_CASE : Tuple = RobertaSeriesModelWithTransformation(_A) _SCREAMING_SNAKE_CASE : str = text_encoder _SCREAMING_SNAKE_CASE : str = AltDiffusionPipeline(**_A) _SCREAMING_SNAKE_CASE : str = alt_pipe.to(_A) alt_pipe.set_progress_bar_config(disable=_A) _SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = """A photo of an astronaut""" _SCREAMING_SNAKE_CASE : List[str] = alt_pipe(**_A) _SCREAMING_SNAKE_CASE : str = output.images _SCREAMING_SNAKE_CASE : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) _SCREAMING_SNAKE_CASE : Tuple = np.array( [0.5_748_162, 0.60_447_145, 0.48_821_217, 0.50_100_636, 0.5_431_185, 0.45_763_683, 0.49_657_696, 0.48_132_733, 0.47_573_093]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : int = """cpu""" # ensure determinism for the device-dependent torch.Generator _SCREAMING_SNAKE_CASE : Tuple = self.get_dummy_components() _SCREAMING_SNAKE_CASE : Union[str, Any] = PNDMScheduler(skip_prk_steps=_A) torch.manual_seed(0) _SCREAMING_SNAKE_CASE : Union[str, Any] = RobertaSeriesConfig( hidden_size=3_2 , project_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5_0_0_2 , ) # TODO: remove after fixing the non-deterministic text encoder _SCREAMING_SNAKE_CASE : Union[str, Any] = RobertaSeriesModelWithTransformation(_A) _SCREAMING_SNAKE_CASE : Tuple = text_encoder _SCREAMING_SNAKE_CASE : Dict = AltDiffusionPipeline(**_A) _SCREAMING_SNAKE_CASE : str = alt_pipe.to(_A) alt_pipe.set_progress_bar_config(disable=_A) _SCREAMING_SNAKE_CASE : Dict = self.get_dummy_inputs(_A) _SCREAMING_SNAKE_CASE : List[str] = alt_pipe(**_A) _SCREAMING_SNAKE_CASE : List[Any] = output.images _SCREAMING_SNAKE_CASE : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) _SCREAMING_SNAKE_CASE : List[Any] = np.array( [0.51_605_093, 0.5_707_241, 0.47_365_507, 0.50_578_886, 0.5_633_877, 0.4_642_503, 0.5_182_081, 0.48_763_484, 0.49_084_237]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Any): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = AltDiffusionPipeline.from_pretrained("""BAAI/AltDiffusion""" , safety_checker=_A) _SCREAMING_SNAKE_CASE : List[str] = alt_pipe.to(_A) alt_pipe.set_progress_bar_config(disable=_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = """A painting of a squirrel eating a burger""" _SCREAMING_SNAKE_CASE : List[str] = torch.manual_seed(0) _SCREAMING_SNAKE_CASE : Any = alt_pipe([prompt] , generator=_A , guidance_scale=6.0 , num_inference_steps=2_0 , output_type="""np""") _SCREAMING_SNAKE_CASE : Dict = output.images _SCREAMING_SNAKE_CASE : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) _SCREAMING_SNAKE_CASE : Optional[int] = np.array([0.1_010, 0.0_800, 0.0_794, 0.0_885, 0.0_843, 0.0_762, 0.0_769, 0.0_729, 0.0_586]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = DDIMScheduler.from_pretrained("""BAAI/AltDiffusion""" , subfolder="""scheduler""") _SCREAMING_SNAKE_CASE : Union[str, Any] = AltDiffusionPipeline.from_pretrained("""BAAI/AltDiffusion""" , scheduler=_A , safety_checker=_A) _SCREAMING_SNAKE_CASE : Optional[Any] = alt_pipe.to(_A) alt_pipe.set_progress_bar_config(disable=_A) _SCREAMING_SNAKE_CASE : Dict = """A painting of a squirrel eating a burger""" _SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0) _SCREAMING_SNAKE_CASE : str = alt_pipe([prompt] , generator=_A , num_inference_steps=2 , output_type="""numpy""") _SCREAMING_SNAKE_CASE : List[Any] = output.images _SCREAMING_SNAKE_CASE : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) _SCREAMING_SNAKE_CASE : int = np.array([0.4_019, 0.4_052, 0.3_810, 0.4_119, 0.3_916, 0.3_982, 0.4_651, 0.4_195, 0.5_323]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
635
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import 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.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.g4dn.xlarge", "results": {"train_runtime": 6_50, "eval_accuracy": 0.6, "eval_loss": 0.9}, }, { "framework": "tensorflow", "script": "run_tf.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.g4dn.xlarge", "results": {"train_runtime": 6_00, "eval_accuracy": 0.3, "eval_loss": 0.9}, }, ] ) class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" 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=_A , ) assert hasattr(self , """env""") def _lowerCAmelCase ( self : Union[str, Any] , _A : str=1): """simple docstring""" 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}-single""" , instance_count=_A , instance_type=self.instance_type , debugger_hook_config=_A , hyperparameters={**self.env.hyperparameters, """model_name_or_path""": self.model_name_or_path} , metric_definitions=self.env.metric_definitions , py_version="""py36""" , ) def _lowerCAmelCase ( self : Union[str, Any] , _A : Union[str, Any]): """simple docstring""" TrainingJobAnalytics(_A).export_csv(f"""{self.env.test_path}/{job_name}_metrics.csv""") def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : str = self.create_estimator() # run training estimator.fit() # result dataframe _SCREAMING_SNAKE_CASE : Any = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis _SCREAMING_SNAKE_CASE : Any = list(result_metrics_df[result_metrics_df.metric_name == """eval_accuracy"""]["""value"""]) _SCREAMING_SNAKE_CASE : Tuple = list(result_metrics_df[result_metrics_df.metric_name == """eval_loss"""]["""value"""]) # get train time from SageMaker job, this includes starting, preprocessing, stopping _SCREAMING_SNAKE_CASE : int = ( 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} , _A)
635
1
"""simple docstring""" import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def lowerCamelCase_(__SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=10 , __SCREAMING_SNAKE_CASE=100 , __SCREAMING_SNAKE_CASE=1_026 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE="data/tokenized_stories_train_wikitext103.jbl" , __SCREAMING_SNAKE_CASE="igf_context_pairs.jbl" , )-> Union[str, Any]: set_seed(3 ) # generate train_data and objective_set _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = generate_datasets( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , number=__SCREAMING_SNAKE_CASE , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? _SCREAMING_SNAKE_CASE : Dict = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) # load pretrained model _SCREAMING_SNAKE_CASE : Any = load_gpta("""gpt2""" ).to(__SCREAMING_SNAKE_CASE ) print("""computing perplexity on objective set""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).item() print("""perplexity on objective set:""" , __SCREAMING_SNAKE_CASE ) # collect igf pairs and save to file demo.jbl collect_objective_set(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=15 , __SCREAMING_SNAKE_CASE=128 , __SCREAMING_SNAKE_CASE=100 , __SCREAMING_SNAKE_CASE="igf_model.pt" , )-> Optional[int]: set_seed(42 ) # Load pre-trained model _SCREAMING_SNAKE_CASE : Any = GPTaLMHeadModel.from_pretrained("""gpt2""" ) # Initialize secondary learner to use embedding weights of model _SCREAMING_SNAKE_CASE : Union[str, Any] = SecondaryLearner(__SCREAMING_SNAKE_CASE ) # Train secondary learner _SCREAMING_SNAKE_CASE : Any = train_secondary_learner( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , max_epochs=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , eval_freq=100 , igf_model_path=__SCREAMING_SNAKE_CASE , ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_000 , __SCREAMING_SNAKE_CASE=16 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=recopy_gpta , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=10 , __SCREAMING_SNAKE_CASE="gpt2_finetuned.pt" , )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Tuple = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = RandomSampler(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = DataLoader(__SCREAMING_SNAKE_CASE , sampler=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = max_steps // (len(__SCREAMING_SNAKE_CASE )) + 1 _SCREAMING_SNAKE_CASE : List[Any] = 0 _SCREAMING_SNAKE_CASE : Any = torch.zeros((1, context_len) , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = recopy_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) model.train() if secondary_learner is not None: secondary_learner.to(__SCREAMING_SNAKE_CASE ) secondary_learner.eval() _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : Optional[int] = 0 _SCREAMING_SNAKE_CASE : Optional[Any] = [] _SCREAMING_SNAKE_CASE : int = [] # Compute the performance of the transformer model at the beginning _SCREAMING_SNAKE_CASE : Tuple = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) test_perps.append(__SCREAMING_SNAKE_CASE ) print("""Test perplexity, step""" , __SCREAMING_SNAKE_CASE , """:""" , __SCREAMING_SNAKE_CASE ) for epoch in range(int(__SCREAMING_SNAKE_CASE ) ): for step, example in enumerate(__SCREAMING_SNAKE_CASE ): torch.cuda.empty_cache() _SCREAMING_SNAKE_CASE : Any = random.randint(0 , example.size(2 ) - context_len - 1 ) _SCREAMING_SNAKE_CASE : int = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() _SCREAMING_SNAKE_CASE : Union[str, Any] = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[str] = True if secondary_learner is not None: _SCREAMING_SNAKE_CASE : List[Any] = secondary_learner.forward( torch.tensor(__SCREAMING_SNAKE_CASE , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ).unsqueeze(0 ) )[0].item() observed_qs.append(float(__SCREAMING_SNAKE_CASE ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: _SCREAMING_SNAKE_CASE : Dict = -1 if predicted_q < threshold: _SCREAMING_SNAKE_CASE : List[str] = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() _SCREAMING_SNAKE_CASE : Any = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: _SCREAMING_SNAKE_CASE : Tuple = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) test_perps.append(__SCREAMING_SNAKE_CASE ) print("""Test perplexity, step""" , __SCREAMING_SNAKE_CASE , """:""" , __SCREAMING_SNAKE_CASE ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() , __SCREAMING_SNAKE_CASE ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def lowerCamelCase_()-> Tuple: _SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser(description="""Fine-tune a transformer model with IGF on a language modeling task""" ) # Required parameters parser.add_argument( """--data_dir""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The input data dir. Should contain data files for WikiText.""" , ) parser.add_argument( """--model_name_or_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to pretrained model or model identifier from huggingface.co/models""" , ) parser.add_argument( """--data_file""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help=( """A jbl file containing tokenized data which can be split as objective dataset, """ """train_dataset and test_dataset.""" ) , ) parser.add_argument( """--igf_data_file""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help="""A jbl file containing the context and information gain pairs to train secondary learner.""" , ) parser.add_argument( """--output_dir""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The output directory where the final fine-tuned model is stored.""" , ) parser.add_argument( """--tokenizer_name""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Pretrained tokenizer name or path if not the same as model_name""" , ) parser.add_argument("""--seed""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help="""A seed for reproducible training.""" ) parser.add_argument( """--context_len""" , default=32 , type=__SCREAMING_SNAKE_CASE , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--size_objective_set""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""number of articles that are long enough to be used as our objective set""" , ) parser.add_argument( """--eval_freq""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""secondary model evaluation is triggered at eval_freq""" ) parser.add_argument("""--max_steps""" , default=1_000 , type=__SCREAMING_SNAKE_CASE , help="""To calculate training epochs""" ) parser.add_argument( """--secondary_learner_batch_size""" , default=128 , type=__SCREAMING_SNAKE_CASE , help="""batch size of training data for secondary learner""" , ) parser.add_argument( """--batch_size""" , default=16 , type=__SCREAMING_SNAKE_CASE , help="""batch size of training data of language model(gpt2) """ ) parser.add_argument( """--eval_interval""" , default=10 , type=__SCREAMING_SNAKE_CASE , help=( """decay the selectivity of our secondary learner filter from""" """1 standard deviation above average to 1 below average after 10 batches""" ) , ) parser.add_argument( """--number""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""The number of examples split to be used as objective_set/test_data""" ) parser.add_argument( """--min_len""" , default=1_026 , type=__SCREAMING_SNAKE_CASE , help="""The minimum length of the article to be used as objective set""" ) parser.add_argument( """--secondary_learner_max_epochs""" , default=15 , type=__SCREAMING_SNAKE_CASE , help="""number of epochs to train secondary learner""" ) parser.add_argument("""--trim""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""truncate the example if it exceeds context length""" ) parser.add_argument( """--threshold""" , default=1.0 , type=__SCREAMING_SNAKE_CASE , help=( """The threshold value used by secondary learner to filter the train_data and allow only""" """ informative data as input to the model""" ) , ) parser.add_argument("""--finetuned_model_name""" , default="""gpt2_finetuned.pt""" , type=__SCREAMING_SNAKE_CASE , help="""finetuned_model_name""" ) parser.add_argument( """--recopy_model""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Reset the model to the original pretrained GPT-2 weights after each iteration""" , ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 , max_steps=10 , size_objective_set=100 , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE , data_file="""data/tokenized_stories_train_wikitext103.jbl""" , igf_data_file="""igf_context_pairs.jbl""" , ) # Load train data for secondary learner _SCREAMING_SNAKE_CASE : Optional[int] = joblib.load("""data/IGF_values.jbl""" ) # Train secondary learner _SCREAMING_SNAKE_CASE : int = training_secondary_learner( __SCREAMING_SNAKE_CASE , secondary_learner_max_epochs=15 , secondary_learner_batch_size=128 , eval_freq=100 , igf_model_path="""igf_model.pt""" , ) # load pretrained gpt2 model _SCREAMING_SNAKE_CASE : List[Any] = GPTaLMHeadModel.from_pretrained("""gpt2""" ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = generate_datasets( context_len=32 , file="""data/tokenized_stories_train_wikitext103.jbl""" , number=100 , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , context_len=32 , max_steps=1_000 , batch_size=16 , threshold=1.0 , recopy_model=__SCREAMING_SNAKE_CASE , secondary_learner=__SCREAMING_SNAKE_CASE , eval_interval=10 , finetuned_model_name="""gpt2_finetuned.pt""" , ) if __name__ == "__main__": main()
635
"""simple docstring""" import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip lowerCAmelCase_ = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> List[str]: if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Any: return max(metric_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for gt in ground_truths ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[str]: _SCREAMING_SNAKE_CASE : List[str] = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Dict = [] if args.gold_data_mode == "qa": _SCREAMING_SNAKE_CASE : int = pd.read_csv(__SCREAMING_SNAKE_CASE , sep="""\t""" , header=__SCREAMING_SNAKE_CASE ) for answer_list in data[1]: _SCREAMING_SNAKE_CASE : Union[str, Any] = ast.literal_eval(__SCREAMING_SNAKE_CASE ) answers.append(__SCREAMING_SNAKE_CASE ) else: _SCREAMING_SNAKE_CASE : Optional[Any] = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Optional[int] = [[reference] for reference in references] _SCREAMING_SNAKE_CASE : Optional[int] = 0 for prediction, ground_truths in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): total += 1 em += metric_max_over_ground_truths(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) fa += metric_max_over_ground_truths(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Dict = 1_00.0 * em / total _SCREAMING_SNAKE_CASE : Optional[Any] = 1_00.0 * fa / total logger.info(F"""F1: {fa:.2f}""" ) logger.info(F"""EM: {em:.2f}""" ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Tuple = args.k _SCREAMING_SNAKE_CASE : int = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Any = [line.strip() for line in open(__SCREAMING_SNAKE_CASE , """r""" ).readlines()] _SCREAMING_SNAKE_CASE : Optional[Any] = 0 for hypo, reference in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = set(hypo.split("""\t""" )[:k] ) _SCREAMING_SNAKE_CASE : Union[str, Any] = set(reference.split("""\t""" ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k _SCREAMING_SNAKE_CASE : int = 1_00.0 * em / total logger.info(F"""Precision@{k}: {em: .2f}""" ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: def strip_title(__SCREAMING_SNAKE_CASE ): if title.startswith("""\"""" ): _SCREAMING_SNAKE_CASE : Optional[int] = title[1:] if title.endswith("""\"""" ): _SCREAMING_SNAKE_CASE : str = title[:-1] return title _SCREAMING_SNAKE_CASE : Dict = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( __SCREAMING_SNAKE_CASE , return_tensors="""pt""" , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , )["""input_ids"""].to(args.device ) _SCREAMING_SNAKE_CASE : List[str] = rag_model.rag.question_encoder(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Any = question_enc_outputs[0] _SCREAMING_SNAKE_CASE : List[Any] = rag_model.retriever( __SCREAMING_SNAKE_CASE , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors="""pt""" , ) _SCREAMING_SNAKE_CASE : Optional[int] = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [] for docs in all_docs: _SCREAMING_SNAKE_CASE : str = [strip_title(__SCREAMING_SNAKE_CASE ) for title in docs["""title"""]] provenance_strings.append("""\t""".join(__SCREAMING_SNAKE_CASE ) ) return provenance_strings def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[Any]: with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[Any] = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( __SCREAMING_SNAKE_CASE , return_tensors="""pt""" , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Union[str, Any] = inputs_dict.input_ids.to(args.device ) _SCREAMING_SNAKE_CASE : Union[str, Any] = inputs_dict.attention_mask.to(args.device ) _SCREAMING_SNAKE_CASE : Optional[Any] = rag_model.generate( # rag_model overwrites generate __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=__SCREAMING_SNAKE_CASE , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) _SCREAMING_SNAKE_CASE : Tuple = rag_model.retriever.generator_tokenizer.batch_decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) if args.print_predictions: for q, a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): logger.info("""Q: {} - A: {}""".format(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) return answers def lowerCamelCase_()-> List[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser() parser.add_argument( """--model_type""" , choices=["""rag_sequence""", """rag_token""", """bart"""] , type=__SCREAMING_SNAKE_CASE , help=( """RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the""" """ model_name_or_path""" ) , ) parser.add_argument( """--index_name""" , default=__SCREAMING_SNAKE_CASE , choices=["""exact""", """compressed""", """legacy"""] , type=__SCREAMING_SNAKE_CASE , help="""RAG model retriever type""" , ) parser.add_argument( """--index_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Path to the retrieval index""" , ) parser.add_argument("""--n_docs""" , default=5 , type=__SCREAMING_SNAKE_CASE , help="""Number of retrieved docs""" ) parser.add_argument( """--model_name_or_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to pretrained checkpoints or model identifier from huggingface.co/models""" , ) parser.add_argument( """--eval_mode""" , choices=["""e2e""", """retrieval"""] , default="""e2e""" , type=__SCREAMING_SNAKE_CASE , help=( """Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates""" """ precision@k.""" ) , ) parser.add_argument("""--k""" , default=1 , type=__SCREAMING_SNAKE_CASE , help="""k for the precision@k calculation""" ) parser.add_argument( """--evaluation_set""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to a file containing evaluation samples""" , ) parser.add_argument( """--gold_data_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to a tab-separated file with gold samples""" , ) parser.add_argument( """--gold_data_mode""" , default="""qa""" , type=__SCREAMING_SNAKE_CASE , choices=["""qa""", """ans"""] , help=( """Format of the gold data file""" """qa - a single line in the following format: question [tab] answer_list""" """ans - a single line of the gold file contains the expected answer string""" ) , ) parser.add_argument( """--predictions_path""" , type=__SCREAMING_SNAKE_CASE , default="""predictions.txt""" , help="""Name of the predictions file, to be stored in the checkpoints directory""" , ) parser.add_argument( """--eval_all_checkpoints""" , action="""store_true""" , help="""Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number""" , ) parser.add_argument( """--eval_batch_size""" , default=8 , type=__SCREAMING_SNAKE_CASE , help="""Batch size per GPU/CPU for evaluation.""" , ) parser.add_argument( """--recalculate""" , help="""Recalculate predictions even if the prediction file exists""" , action="""store_true""" , ) parser.add_argument( """--num_beams""" , default=4 , type=__SCREAMING_SNAKE_CASE , help="""Number of beams to be used when generating answers""" , ) parser.add_argument("""--min_length""" , default=1 , type=__SCREAMING_SNAKE_CASE , help="""Min length of the generated answers""" ) parser.add_argument("""--max_length""" , default=50 , type=__SCREAMING_SNAKE_CASE , help="""Max length of the generated answers""" ) parser.add_argument( """--print_predictions""" , action="""store_true""" , help="""If True, prints predictions while evaluating.""" , ) parser.add_argument( """--print_docs""" , action="""store_true""" , help="""If True, prints docs retried while generating.""" , ) _SCREAMING_SNAKE_CASE : Dict = parser.parse_args() _SCREAMING_SNAKE_CASE : Any = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) return args def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: _SCREAMING_SNAKE_CASE : Union[str, Any] = {} if args.model_type is None: _SCREAMING_SNAKE_CASE : Optional[int] = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith("""rag""" ): _SCREAMING_SNAKE_CASE : List[Any] = RagTokenForGeneration if args.model_type == """rag_token""" else RagSequenceForGeneration _SCREAMING_SNAKE_CASE : Optional[Any] = args.n_docs if args.index_name is not None: _SCREAMING_SNAKE_CASE : Optional[Any] = args.index_name if args.index_path is not None: _SCREAMING_SNAKE_CASE : Any = args.index_path else: _SCREAMING_SNAKE_CASE : Any = BartForConditionalGeneration _SCREAMING_SNAKE_CASE : int = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info("""Evaluate the following checkpoints: %s""" , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = get_scores if args.eval_mode == """e2e""" else get_precision_at_k _SCREAMING_SNAKE_CASE : Tuple = evaluate_batch_eae if args.eval_mode == """e2e""" else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info("""Calculating metrics based on an existing predictions file: {}""".format(args.predictions_path ) ) score_fn(__SCREAMING_SNAKE_CASE , args.predictions_path , args.gold_data_path ) continue logger.info("""***** Running evaluation for {} *****""".format(__SCREAMING_SNAKE_CASE ) ) logger.info(""" Batch size = %d""" , args.eval_batch_size ) logger.info(""" Predictions will be stored under {}""".format(args.predictions_path ) ) if args.model_type.startswith("""rag""" ): _SCREAMING_SNAKE_CASE : str = RagRetriever.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = model_class.from_pretrained(__SCREAMING_SNAKE_CASE , retriever=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) model.retriever.init_retrieval() else: _SCREAMING_SNAKE_CASE : str = model_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) model.to(args.device ) with open(args.evaluation_set , """r""" ) as eval_file, open(args.predictions_path , """w""" ) as preds_file: _SCREAMING_SNAKE_CASE : str = [] for line in tqdm(__SCREAMING_SNAKE_CASE ): questions.append(line.strip() ) if len(__SCREAMING_SNAKE_CASE ) == args.eval_batch_size: _SCREAMING_SNAKE_CASE : str = evaluate_batch_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) preds_file.write("""\n""".join(__SCREAMING_SNAKE_CASE ) + """\n""" ) preds_file.flush() _SCREAMING_SNAKE_CASE : Any = [] if len(__SCREAMING_SNAKE_CASE ) > 0: _SCREAMING_SNAKE_CASE : List[str] = evaluate_batch_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) preds_file.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) preds_file.flush() score_fn(__SCREAMING_SNAKE_CASE , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": lowerCAmelCase_ = get_args() main(args)
635
1
"""simple docstring""" import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _snake_case ( __snake_case ): """simple docstring""" def __init__( self : Any , _A : VQModel , _A : UNetaDModel , _A : DDIMScheduler): """simple docstring""" super().__init__() self.register_modules(vqvae=_A , unet=_A , scheduler=_A) @torch.no_grad() def __call__( self : List[str] , _A : int = 1 , _A : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _A : float = 0.0 , _A : int = 5_0 , _A : Optional[str] = "pil" , _A : bool = True , **_A : List[str] , ): """simple docstring""" _SCREAMING_SNAKE_CASE : str = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=_A , ) _SCREAMING_SNAKE_CASE : int = latents.to(self.device) # scale the initial noise by the standard deviation required by the scheduler _SCREAMING_SNAKE_CASE : Optional[int] = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(_A) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature _SCREAMING_SNAKE_CASE : Dict = """eta""" in set(inspect.signature(self.scheduler.step).parameters.keys()) _SCREAMING_SNAKE_CASE : Optional[Any] = {} if accepts_eta: _SCREAMING_SNAKE_CASE : Union[str, Any] = eta for t in self.progress_bar(self.scheduler.timesteps): _SCREAMING_SNAKE_CASE : Optional[int] = self.scheduler.scale_model_input(_A , _A) # predict the noise residual _SCREAMING_SNAKE_CASE : Optional[Any] = self.unet(_A , _A).sample # compute the previous noisy sample x_t -> x_t-1 _SCREAMING_SNAKE_CASE : str = self.scheduler.step(_A , _A , _A , **_A).prev_sample # decode the image latents with the VAE _SCREAMING_SNAKE_CASE : Any = self.vqvae.decode(_A).sample _SCREAMING_SNAKE_CASE : str = (image / 2 + 0.5).clamp(0 , 1) _SCREAMING_SNAKE_CASE : List[Any] = image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": _SCREAMING_SNAKE_CASE : str = self.numpy_to_pil(_A) if not return_dict: return (image,) return ImagePipelineOutput(images=_A)
635
"""simple docstring""" import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def lowerCamelCase_(__SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=10 , __SCREAMING_SNAKE_CASE=100 , __SCREAMING_SNAKE_CASE=1_026 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE="data/tokenized_stories_train_wikitext103.jbl" , __SCREAMING_SNAKE_CASE="igf_context_pairs.jbl" , )-> Union[str, Any]: set_seed(3 ) # generate train_data and objective_set _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = generate_datasets( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , number=__SCREAMING_SNAKE_CASE , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? _SCREAMING_SNAKE_CASE : Dict = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) # load pretrained model _SCREAMING_SNAKE_CASE : Any = load_gpta("""gpt2""" ).to(__SCREAMING_SNAKE_CASE ) print("""computing perplexity on objective set""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).item() print("""perplexity on objective set:""" , __SCREAMING_SNAKE_CASE ) # collect igf pairs and save to file demo.jbl collect_objective_set(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=15 , __SCREAMING_SNAKE_CASE=128 , __SCREAMING_SNAKE_CASE=100 , __SCREAMING_SNAKE_CASE="igf_model.pt" , )-> Optional[int]: set_seed(42 ) # Load pre-trained model _SCREAMING_SNAKE_CASE : Any = GPTaLMHeadModel.from_pretrained("""gpt2""" ) # Initialize secondary learner to use embedding weights of model _SCREAMING_SNAKE_CASE : Union[str, Any] = SecondaryLearner(__SCREAMING_SNAKE_CASE ) # Train secondary learner _SCREAMING_SNAKE_CASE : Any = train_secondary_learner( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , max_epochs=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , eval_freq=100 , igf_model_path=__SCREAMING_SNAKE_CASE , ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_000 , __SCREAMING_SNAKE_CASE=16 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=recopy_gpta , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=10 , __SCREAMING_SNAKE_CASE="gpt2_finetuned.pt" , )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Tuple = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = RandomSampler(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = DataLoader(__SCREAMING_SNAKE_CASE , sampler=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = max_steps // (len(__SCREAMING_SNAKE_CASE )) + 1 _SCREAMING_SNAKE_CASE : List[Any] = 0 _SCREAMING_SNAKE_CASE : Any = torch.zeros((1, context_len) , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = recopy_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) model.train() if secondary_learner is not None: secondary_learner.to(__SCREAMING_SNAKE_CASE ) secondary_learner.eval() _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : Optional[int] = 0 _SCREAMING_SNAKE_CASE : Optional[Any] = [] _SCREAMING_SNAKE_CASE : int = [] # Compute the performance of the transformer model at the beginning _SCREAMING_SNAKE_CASE : Tuple = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) test_perps.append(__SCREAMING_SNAKE_CASE ) print("""Test perplexity, step""" , __SCREAMING_SNAKE_CASE , """:""" , __SCREAMING_SNAKE_CASE ) for epoch in range(int(__SCREAMING_SNAKE_CASE ) ): for step, example in enumerate(__SCREAMING_SNAKE_CASE ): torch.cuda.empty_cache() _SCREAMING_SNAKE_CASE : Any = random.randint(0 , example.size(2 ) - context_len - 1 ) _SCREAMING_SNAKE_CASE : int = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() _SCREAMING_SNAKE_CASE : Union[str, Any] = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[str] = True if secondary_learner is not None: _SCREAMING_SNAKE_CASE : List[Any] = secondary_learner.forward( torch.tensor(__SCREAMING_SNAKE_CASE , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ).unsqueeze(0 ) )[0].item() observed_qs.append(float(__SCREAMING_SNAKE_CASE ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: _SCREAMING_SNAKE_CASE : Dict = -1 if predicted_q < threshold: _SCREAMING_SNAKE_CASE : List[str] = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() _SCREAMING_SNAKE_CASE : Any = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: _SCREAMING_SNAKE_CASE : Tuple = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) test_perps.append(__SCREAMING_SNAKE_CASE ) print("""Test perplexity, step""" , __SCREAMING_SNAKE_CASE , """:""" , __SCREAMING_SNAKE_CASE ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() , __SCREAMING_SNAKE_CASE ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def lowerCamelCase_()-> Tuple: _SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser(description="""Fine-tune a transformer model with IGF on a language modeling task""" ) # Required parameters parser.add_argument( """--data_dir""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The input data dir. Should contain data files for WikiText.""" , ) parser.add_argument( """--model_name_or_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to pretrained model or model identifier from huggingface.co/models""" , ) parser.add_argument( """--data_file""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help=( """A jbl file containing tokenized data which can be split as objective dataset, """ """train_dataset and test_dataset.""" ) , ) parser.add_argument( """--igf_data_file""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help="""A jbl file containing the context and information gain pairs to train secondary learner.""" , ) parser.add_argument( """--output_dir""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The output directory where the final fine-tuned model is stored.""" , ) parser.add_argument( """--tokenizer_name""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Pretrained tokenizer name or path if not the same as model_name""" , ) parser.add_argument("""--seed""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help="""A seed for reproducible training.""" ) parser.add_argument( """--context_len""" , default=32 , type=__SCREAMING_SNAKE_CASE , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--size_objective_set""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""number of articles that are long enough to be used as our objective set""" , ) parser.add_argument( """--eval_freq""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""secondary model evaluation is triggered at eval_freq""" ) parser.add_argument("""--max_steps""" , default=1_000 , type=__SCREAMING_SNAKE_CASE , help="""To calculate training epochs""" ) parser.add_argument( """--secondary_learner_batch_size""" , default=128 , type=__SCREAMING_SNAKE_CASE , help="""batch size of training data for secondary learner""" , ) parser.add_argument( """--batch_size""" , default=16 , type=__SCREAMING_SNAKE_CASE , help="""batch size of training data of language model(gpt2) """ ) parser.add_argument( """--eval_interval""" , default=10 , type=__SCREAMING_SNAKE_CASE , help=( """decay the selectivity of our secondary learner filter from""" """1 standard deviation above average to 1 below average after 10 batches""" ) , ) parser.add_argument( """--number""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""The number of examples split to be used as objective_set/test_data""" ) parser.add_argument( """--min_len""" , default=1_026 , type=__SCREAMING_SNAKE_CASE , help="""The minimum length of the article to be used as objective set""" ) parser.add_argument( """--secondary_learner_max_epochs""" , default=15 , type=__SCREAMING_SNAKE_CASE , help="""number of epochs to train secondary learner""" ) parser.add_argument("""--trim""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""truncate the example if it exceeds context length""" ) parser.add_argument( """--threshold""" , default=1.0 , type=__SCREAMING_SNAKE_CASE , help=( """The threshold value used by secondary learner to filter the train_data and allow only""" """ informative data as input to the model""" ) , ) parser.add_argument("""--finetuned_model_name""" , default="""gpt2_finetuned.pt""" , type=__SCREAMING_SNAKE_CASE , help="""finetuned_model_name""" ) parser.add_argument( """--recopy_model""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Reset the model to the original pretrained GPT-2 weights after each iteration""" , ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 , max_steps=10 , size_objective_set=100 , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE , data_file="""data/tokenized_stories_train_wikitext103.jbl""" , igf_data_file="""igf_context_pairs.jbl""" , ) # Load train data for secondary learner _SCREAMING_SNAKE_CASE : Optional[int] = joblib.load("""data/IGF_values.jbl""" ) # Train secondary learner _SCREAMING_SNAKE_CASE : int = training_secondary_learner( __SCREAMING_SNAKE_CASE , secondary_learner_max_epochs=15 , secondary_learner_batch_size=128 , eval_freq=100 , igf_model_path="""igf_model.pt""" , ) # load pretrained gpt2 model _SCREAMING_SNAKE_CASE : List[Any] = GPTaLMHeadModel.from_pretrained("""gpt2""" ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = generate_datasets( context_len=32 , file="""data/tokenized_stories_train_wikitext103.jbl""" , number=100 , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , context_len=32 , max_steps=1_000 , batch_size=16 , threshold=1.0 , recopy_model=__SCREAMING_SNAKE_CASE , secondary_learner=__SCREAMING_SNAKE_CASE , eval_interval=10 , finetuned_model_name="""gpt2_finetuned.pt""" , ) if __name__ == "__main__": main()
635
1
"""simple docstring""" import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version lowerCAmelCase_ = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.14.0''', '''To fix: pip install -r examples/pytorch/audio-classification/requirements.txt''') def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 16_000 )-> List[Any]: _SCREAMING_SNAKE_CASE : Tuple = int(round(sample_rate * max_length ) ) if len(__SCREAMING_SNAKE_CASE ) <= sample_length: return wav _SCREAMING_SNAKE_CASE : int = randint(0 , len(__SCREAMING_SNAKE_CASE ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class _snake_case : """simple docstring""" a = field(default=__snake_case , metadata={"help": "Name of a dataset from the datasets package"} ) a = field( default=__snake_case , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) a = field( default=__snake_case , metadata={"help": "A file containing the training audio paths and labels."} ) a = field( default=__snake_case , metadata={"help": "A file containing the validation audio paths and labels."} ) a = field( default="train" , metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } , ) a = field( default="validation" , metadata={ "help": ( "The name of the training data set split to use (via the datasets library). Defaults to 'validation'" ) } , ) a = field( default="audio" , metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"} , ) a = field( default="label" , metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"} ) a = field( default=__snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) a = field( default=__snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) a = field( default=20 , metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."} , ) @dataclass class _snake_case : """simple docstring""" a = field( default="facebook/wav2vec2-base" , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} , ) a = field( default=__snake_case , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) a = field( default=__snake_case , metadata={"help": "Where do you want to store the pretrained models downloaded from the Hub"} ) a = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) a = field( default=__snake_case , metadata={"help": "Name or path of preprocessor config."} ) a = field( default=__snake_case , metadata={"help": "Whether to freeze the feature encoder layers of the model."} ) a = field( default=__snake_case , metadata={"help": "Whether to generate an attention mask in the feature extractor."} ) a = field( default=__snake_case , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) a = field( default=__snake_case , metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) a = field( default=__snake_case , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , ) def _lowerCAmelCase ( self : List[Any]): """simple docstring""" if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( """The argument `--freeze_feature_extractor` is deprecated and """ """will be removed in a future version. Use `--freeze_feature_encoder`""" """instead. Setting `freeze_feature_encoder==True`.""" , _A , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( """The argument `--freeze_feature_extractor` is deprecated and """ """should not be used in combination with `--freeze_feature_encoder`.""" """Only make use of `--freeze_feature_encoder`.""") def lowerCamelCase_()-> List[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. _SCREAMING_SNAKE_CASE : str = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_audio_classification""" , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _SCREAMING_SNAKE_CASE : Tuple = training_args.get_process_log_level() logger.setLevel(__SCREAMING_SNAKE_CASE ) transformers.utils.logging.set_verbosity(__SCREAMING_SNAKE_CASE ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} """ + F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(F"""Training/evaluation parameters {training_args}""" ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. _SCREAMING_SNAKE_CASE : str = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _SCREAMING_SNAKE_CASE : int = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ """Use --overwrite_output_dir to train from scratch.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset and prepare it for the audio classification task. _SCREAMING_SNAKE_CASE : Any = DatasetDict() _SCREAMING_SNAKE_CASE : str = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.train_split_name , use_auth_token=True if model_args.use_auth_token else None , ) _SCREAMING_SNAKE_CASE : List[str] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.eval_split_name , use_auth_token=True if model_args.use_auth_token else None , ) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( F"""--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. """ """Make sure to set `--audio_column_name` to the correct audio column - one of """ F"""{", ".join(raw_datasets["train"].column_names )}.""" ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( F"""--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. """ """Make sure to set `--label_column_name` to the correct text column - one of """ F"""{", ".join(raw_datasets["train"].column_names )}.""" ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy _SCREAMING_SNAKE_CASE : Optional[int] = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path , return_attention_mask=model_args.attention_mask , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. _SCREAMING_SNAKE_CASE : int = raw_datasets.cast_column( data_args.audio_column_name , datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = feature_extractor.model_input_names[0] def train_transforms(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = [] for audio in batch[data_args.audio_column_name]: _SCREAMING_SNAKE_CASE : Dict = random_subsample( audio["""array"""] , max_length=data_args.max_length_seconds , sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = feature_extractor(__SCREAMING_SNAKE_CASE , sampling_rate=feature_extractor.sampling_rate ) _SCREAMING_SNAKE_CASE : Tuple = {model_input_name: inputs.get(__SCREAMING_SNAKE_CASE )} _SCREAMING_SNAKE_CASE : List[Any] = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = [audio["""array"""] for audio in batch[data_args.audio_column_name]] _SCREAMING_SNAKE_CASE : List[str] = feature_extractor(__SCREAMING_SNAKE_CASE , sampling_rate=feature_extractor.sampling_rate ) _SCREAMING_SNAKE_CASE : Optional[Any] = {model_input_name: inputs.get(__SCREAMING_SNAKE_CASE )} _SCREAMING_SNAKE_CASE : List[str] = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. _SCREAMING_SNAKE_CASE : Optional[int] = raw_datasets["""train"""].features[data_args.label_column_name].names _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = {}, {} for i, label in enumerate(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : int = str(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[int] = label # Load the accuracy metric from the datasets package _SCREAMING_SNAKE_CASE : Tuple = evaluate.load("""accuracy""" ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = np.argmax(eval_pred.predictions , axis=1 ) return metric.compute(predictions=__SCREAMING_SNAKE_CASE , references=eval_pred.label_ids ) _SCREAMING_SNAKE_CASE : int = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(__SCREAMING_SNAKE_CASE ) , labelaid=__SCREAMING_SNAKE_CASE , idalabel=__SCREAMING_SNAKE_CASE , finetuning_task="""audio-classification""" , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) _SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: _SCREAMING_SNAKE_CASE : Dict = ( raw_datasets["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(__SCREAMING_SNAKE_CASE , output_all_columns=__SCREAMING_SNAKE_CASE ) if training_args.do_eval: if data_args.max_eval_samples is not None: _SCREAMING_SNAKE_CASE : int = ( raw_datasets["""eval"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(__SCREAMING_SNAKE_CASE , output_all_columns=__SCREAMING_SNAKE_CASE ) # Initialize our trainer _SCREAMING_SNAKE_CASE : Union[str, Any] = Trainer( model=__SCREAMING_SNAKE_CASE , args=__SCREAMING_SNAKE_CASE , train_dataset=raw_datasets["""train"""] if training_args.do_train else None , eval_dataset=raw_datasets["""eval"""] if training_args.do_eval else None , compute_metrics=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE , ) # Training if training_args.do_train: _SCREAMING_SNAKE_CASE : List[str] = None if training_args.resume_from_checkpoint is not None: _SCREAMING_SNAKE_CASE : List[str] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _SCREAMING_SNAKE_CASE : List[str] = last_checkpoint _SCREAMING_SNAKE_CASE : Any = trainer.train(resume_from_checkpoint=__SCREAMING_SNAKE_CASE ) trainer.save_model() trainer.log_metrics("""train""" , train_result.metrics ) trainer.save_metrics("""train""" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _SCREAMING_SNAKE_CASE : Tuple = trainer.evaluate() trainer.log_metrics("""eval""" , __SCREAMING_SNAKE_CASE ) trainer.save_metrics("""eval""" , __SCREAMING_SNAKE_CASE ) # Write model card and (optionally) push to hub _SCREAMING_SNAKE_CASE : Union[str, Any] = { """finetuned_from""": model_args.model_name_or_path, """tasks""": """audio-classification""", """dataset""": data_args.dataset_name, """tags""": ["""audio-classification"""], } if training_args.push_to_hub: trainer.push_to_hub(**__SCREAMING_SNAKE_CASE ) else: trainer.create_model_card(**__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
635
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _snake_case ( __snake_case ): """simple docstring""" a = ["image_processor", "tokenizer"] a = "ChineseCLIPImageProcessor" a = ("BertTokenizer", "BertTokenizerFast") def __init__( self : Dict , _A : Tuple=None , _A : List[Any]=None , **_A : int): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , _A , ) _SCREAMING_SNAKE_CASE : str = kwargs.pop("""feature_extractor""") _SCREAMING_SNAKE_CASE : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""") if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""") super().__init__(_A , _A) _SCREAMING_SNAKE_CASE : Dict = self.image_processor def __call__( self : Optional[int] , _A : Optional[Any]=None , _A : Any=None , _A : Tuple=None , **_A : int): """simple docstring""" if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""") if text is not None: _SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer(_A , return_tensors=_A , **_A) if images is not None: _SCREAMING_SNAKE_CASE : List[Any] = self.image_processor(_A , return_tensors=_A , **_A) if text is not None and images is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_A) , tensor_type=_A) def _lowerCAmelCase ( self : str , *_A : Any , **_A : Any): """simple docstring""" return self.tokenizer.batch_decode(*_A , **_A) def _lowerCAmelCase ( self : Union[str, Any] , *_A : List[Any] , **_A : Any): """simple docstring""" return self.tokenizer.decode(*_A , **_A) @property def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.model_input_names _SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def _lowerCAmelCase ( self : List[str]): """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , _A , ) return self.image_processor_class
635
1
"""simple docstring""" import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart import shift_tokens_right from transformers.testing_utils import TestCasePlus, slow from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset lowerCAmelCase_ = '''bert-base-cased''' lowerCAmelCase_ = '''google/pegasus-xsum''' lowerCAmelCase_ = [''' Sam ate lunch today.''', '''Sams lunch ingredients.'''] lowerCAmelCase_ = ['''A very interesting story about what I ate for lunch.''', '''Avocado, celery, turkey, coffee'''] lowerCAmelCase_ = '''patrickvonplaten/t5-tiny-random''' lowerCAmelCase_ = '''sshleifer/bart-tiny-random''' lowerCAmelCase_ = '''sshleifer/tiny-mbart''' lowerCAmelCase_ = '''sshleifer/tiny-marian-en-de''' def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[str]: _SCREAMING_SNAKE_CASE : List[str] = """\n""".join(__SCREAMING_SNAKE_CASE ) Path(__SCREAMING_SNAKE_CASE ).open("""w""" ).writelines(__SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Dict: for split in ["train", "val", "test"]: _dump_articles(os.path.join(__SCREAMING_SNAKE_CASE , F"""{split}.source""" ) , __SCREAMING_SNAKE_CASE ) _dump_articles(os.path.join(__SCREAMING_SNAKE_CASE , F"""{split}.target""" ) , __SCREAMING_SNAKE_CASE ) return tmp_dir class _snake_case ( __snake_case ): """simple docstring""" @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def _lowerCAmelCase ( self : Optional[Any] , _A : Union[str, Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained(_A) _SCREAMING_SNAKE_CASE : int = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()) _SCREAMING_SNAKE_CASE : List[str] = max(len(tokenizer.encode(_A)) for a in ARTICLES) _SCREAMING_SNAKE_CASE : str = max(len(tokenizer.encode(_A)) for a in SUMMARIES) _SCREAMING_SNAKE_CASE : List[Any] = 4 _SCREAMING_SNAKE_CASE : Tuple = 8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = """ro_RO""", """de_DE""" # ignored for all but mbart, but never causes error. _SCREAMING_SNAKE_CASE : Optional[int] = SeqaSeqDataset( _A , data_dir=_A , type_path="""train""" , max_source_length=_A , max_target_length=_A , src_lang=_A , tgt_lang=_A , ) _SCREAMING_SNAKE_CASE : Optional[Any] = DataLoader(_A , batch_size=2 , collate_fn=train_dataset.collate_fn) for batch in dataloader: assert isinstance(_A , _A) assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_src_len # show that targets are the same len assert batch["labels"].shape[1] == max_tgt_len if tok_name != MBART_TINY: continue # check language codes in correct place _SCREAMING_SNAKE_CASE : Union[str, Any] = shift_tokens_right(batch["""labels"""] , tokenizer.pad_token_id) assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang] assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang] break # No need to test every batch @parameterized.expand([BART_TINY, BERT_BASE_CASED]) def _lowerCAmelCase ( self : List[str] , _A : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = AutoTokenizer.from_pretrained(_A) _SCREAMING_SNAKE_CASE : List[Any] = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()) _SCREAMING_SNAKE_CASE : Optional[int] = max(len(tokenizer.encode(_A)) for a in ARTICLES) _SCREAMING_SNAKE_CASE : List[Any] = max(len(tokenizer.encode(_A)) for a in SUMMARIES) _SCREAMING_SNAKE_CASE : Dict = 4 _SCREAMING_SNAKE_CASE : Dict = LegacySeqaSeqDataset( _A , data_dir=_A , type_path="""train""" , max_source_length=2_0 , max_target_length=_A , ) _SCREAMING_SNAKE_CASE : Optional[int] = DataLoader(_A , batch_size=2 , collate_fn=train_dataset.collate_fn) for batch in dataloader: assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_len_source assert 2_0 >= batch["input_ids"].shape[1] # trimmed significantly # show that targets were truncated assert batch["labels"].shape[1] == trunc_target # Truncated assert max_len_target > trunc_target # Truncated break # No need to test every batch def _lowerCAmelCase ( self : int): """simple docstring""" _SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained("""facebook/mbart-large-cc25""") _SCREAMING_SNAKE_CASE : int = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir())) _SCREAMING_SNAKE_CASE : List[str] = tmp_dir.joinpath("""train.source""").open().readlines() _SCREAMING_SNAKE_CASE : Dict = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir())) pack_data_dir(_A , _A , 1_2_8 , _A) _SCREAMING_SNAKE_CASE : Union[str, Any] = {x.name for x in tmp_dir.iterdir()} _SCREAMING_SNAKE_CASE : Optional[Any] = {x.name for x in save_dir.iterdir()} _SCREAMING_SNAKE_CASE : Tuple = save_dir.joinpath("""train.source""").open().readlines() # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.'] # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.'] assert len(_A) < len(_A) assert len(_A) == 1 assert len(packed_examples[0]) == sum(len(_A) for x in orig_examples) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason="""This test requires fairseq""") def _lowerCAmelCase ( self : Dict): """simple docstring""" if not FAIRSEQ_AVAILABLE: return _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = self._get_dataset(max_len=6_4) _SCREAMING_SNAKE_CASE : Optional[int] = 6_4 _SCREAMING_SNAKE_CASE : List[str] = ds.make_dynamic_sampler(_A , required_batch_size_multiple=_A) _SCREAMING_SNAKE_CASE : Optional[Any] = [len(_A) for x in batch_sampler] assert len(set(_A)) > 1 # it's not dynamic batch size if every batch is the same length assert sum(_A) == len(_A) # no dropped or added examples _SCREAMING_SNAKE_CASE : Any = DataLoader(_A , batch_sampler=_A , collate_fn=ds.collate_fn , num_workers=2) _SCREAMING_SNAKE_CASE : str = [] _SCREAMING_SNAKE_CASE : Optional[Any] = [] for batch in data_loader: _SCREAMING_SNAKE_CASE : Optional[Any] = batch["""input_ids"""].shape _SCREAMING_SNAKE_CASE : Tuple = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple _SCREAMING_SNAKE_CASE : Dict = np.product(batch["""input_ids"""].shape) num_src_per_batch.append(_A) if num_src_tokens > (max_tokens * 1.1): failures.append(_A) assert num_src_per_batch[0] == max(_A) if failures: raise AssertionError(f"""too many tokens in {len(_A)} batches""") def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = self._get_dataset(max_len=5_1_2) _SCREAMING_SNAKE_CASE : int = 2 _SCREAMING_SNAKE_CASE : Tuple = ds.make_sortish_sampler(_A , shuffle=_A) _SCREAMING_SNAKE_CASE : int = DataLoader(_A , batch_size=_A , collate_fn=ds.collate_fn , num_workers=2) _SCREAMING_SNAKE_CASE : Tuple = DataLoader(_A , batch_size=_A , collate_fn=ds.collate_fn , num_workers=2 , sampler=_A) _SCREAMING_SNAKE_CASE : Tuple = tokenizer.pad_token_id def count_pad_tokens(_A : Tuple , _A : Union[str, Any]="input_ids"): return [batch[k].eq(_A).sum().item() for batch in data_loader] assert sum(count_pad_tokens(_A , k="""labels""")) < sum(count_pad_tokens(_A , k="""labels""")) assert sum(count_pad_tokens(_A)) < sum(count_pad_tokens(_A)) assert len(_A) == len(_A) def _lowerCAmelCase ( self : List[str] , _A : List[Any]=1_0_0_0 , _A : List[str]=1_2_8): """simple docstring""" if os.getenv("""USE_REAL_DATA""" , _A): _SCREAMING_SNAKE_CASE : Optional[int] = """examples/seq2seq/wmt_en_ro""" _SCREAMING_SNAKE_CASE : str = max_len * 2 * 6_4 if not Path(_A).joinpath("""train.len""").exists(): save_len_file(_A , _A) else: _SCREAMING_SNAKE_CASE : Union[str, Any] = """examples/seq2seq/test_data/wmt_en_ro""" _SCREAMING_SNAKE_CASE : List[Any] = max_len * 4 save_len_file(_A , _A) _SCREAMING_SNAKE_CASE : List[Any] = AutoTokenizer.from_pretrained(_A) _SCREAMING_SNAKE_CASE : List[str] = SeqaSeqDataset( _A , data_dir=_A , type_path="""train""" , max_source_length=_A , max_target_length=_A , n_obs=_A , ) return ds, max_tokens, tokenizer def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = self._get_dataset() _SCREAMING_SNAKE_CASE : List[str] = set(DistributedSortishSampler(_A , 2_5_6 , num_replicas=2 , rank=0 , add_extra_examples=_A)) _SCREAMING_SNAKE_CASE : List[Any] = set(DistributedSortishSampler(_A , 2_5_6 , num_replicas=2 , rank=1 , add_extra_examples=_A)) assert idsa.intersection(_A) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def _lowerCAmelCase ( self : Tuple , _A : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : str = AutoTokenizer.from_pretrained(_A , use_fast=_A) if tok_name == MBART_TINY: _SCREAMING_SNAKE_CASE : str = SeqaSeqDataset( _A , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()) , type_path="""train""" , max_source_length=4 , max_target_length=8 , src_lang="""EN""" , tgt_lang="""FR""" , ) _SCREAMING_SNAKE_CASE : int = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: _SCREAMING_SNAKE_CASE : Any = SeqaSeqDataset( _A , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()) , type_path="""train""" , max_source_length=4 , max_target_length=8 , ) _SCREAMING_SNAKE_CASE : List[Any] = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(_A) == 1 if tok_name == BART_TINY else len(_A) == 0
635
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = ['''model.decoder.embed_positions.weights'''] def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Optional[int]: if "emb" in name: _SCREAMING_SNAKE_CASE : List[Any] = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: _SCREAMING_SNAKE_CASE : List[str] = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: _SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: _SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: _SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: _SCREAMING_SNAKE_CASE : int = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: _SCREAMING_SNAKE_CASE : Dict = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: _SCREAMING_SNAKE_CASE : Dict = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: _SCREAMING_SNAKE_CASE : Tuple = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: _SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: _SCREAMING_SNAKE_CASE : str = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple[Dict, Dict]: _SCREAMING_SNAKE_CASE : str = list(state_dict.keys() ) _SCREAMING_SNAKE_CASE : Tuple = {} for key in keys: _SCREAMING_SNAKE_CASE : Dict = state_dict.pop(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : int = rename_keys(__SCREAMING_SNAKE_CASE ) if "in_proj_weight" in key: # split fused qkv proj _SCREAMING_SNAKE_CASE : str = val[:hidden_size, :] _SCREAMING_SNAKE_CASE : Any = val[hidden_size : 2 * hidden_size, :] _SCREAMING_SNAKE_CASE : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: _SCREAMING_SNAKE_CASE : int = val else: _SCREAMING_SNAKE_CASE : Dict = val return state_dict, enc_dec_proj_state_dict def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> MusicgenDecoderConfig: if checkpoint == "small": # default config values _SCREAMING_SNAKE_CASE : Optional[Any] = 1_024 _SCREAMING_SNAKE_CASE : str = 24 _SCREAMING_SNAKE_CASE : Any = 16 elif checkpoint == "medium": _SCREAMING_SNAKE_CASE : Dict = 1_536 _SCREAMING_SNAKE_CASE : Union[str, Any] = 48 _SCREAMING_SNAKE_CASE : Optional[Any] = 24 elif checkpoint == "large": _SCREAMING_SNAKE_CASE : List[Any] = 2_048 _SCREAMING_SNAKE_CASE : Optional[int] = 48 _SCREAMING_SNAKE_CASE : str = 32 else: raise ValueError(F"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) _SCREAMING_SNAKE_CASE : Optional[Any] = MusicgenDecoderConfig( hidden_size=__SCREAMING_SNAKE_CASE , ffn_dim=hidden_size * 4 , num_hidden_layers=__SCREAMING_SNAKE_CASE , num_attention_heads=__SCREAMING_SNAKE_CASE , ) return config @torch.no_grad() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="cpu" )-> str: _SCREAMING_SNAKE_CASE : str = MusicGen.get_pretrained(__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[str] = decoder_config_from_checkpoint(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[Any] = fairseq_model.lm.state_dict() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = rename_state_dict( __SCREAMING_SNAKE_CASE , hidden_size=decoder_config.hidden_size ) _SCREAMING_SNAKE_CASE : Tuple = TaEncoderModel.from_pretrained("""t5-base""" ) _SCREAMING_SNAKE_CASE : List[Any] = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) _SCREAMING_SNAKE_CASE : str = MusicgenForCausalLM(__SCREAMING_SNAKE_CASE ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = decoder.load_state_dict(__SCREAMING_SNAKE_CASE , strict=__SCREAMING_SNAKE_CASE ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ValueError(F"""Missing key(s) in state_dict: {missing_keys}""" ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ValueError(F"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model _SCREAMING_SNAKE_CASE : Dict = MusicgenForConditionalGeneration(text_encoder=__SCREAMING_SNAKE_CASE , audio_encoder=__SCREAMING_SNAKE_CASE , decoder=__SCREAMING_SNAKE_CASE ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(__SCREAMING_SNAKE_CASE ) # check we can do a forward pass _SCREAMING_SNAKE_CASE : Optional[Any] = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) _SCREAMING_SNAKE_CASE : Dict = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[int] = model(input_ids=__SCREAMING_SNAKE_CASE , decoder_input_ids=__SCREAMING_SNAKE_CASE ).logits if logits.shape != (8, 1, 2_048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor _SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained("""t5-base""" ) _SCREAMING_SNAKE_CASE : List[str] = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) _SCREAMING_SNAKE_CASE : Optional[int] = MusicgenProcessor(feature_extractor=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE ) # set the appropriate bos/pad token ids _SCREAMING_SNAKE_CASE : Optional[Any] = 2_048 _SCREAMING_SNAKE_CASE : List[Any] = 2_048 # set other default generation config params _SCREAMING_SNAKE_CASE : Any = int(30 * audio_encoder.config.frame_rate ) _SCREAMING_SNAKE_CASE : Tuple = True _SCREAMING_SNAKE_CASE : int = 3.0 if pytorch_dump_folder is not None: Path(__SCREAMING_SNAKE_CASE ).mkdir(exist_ok=__SCREAMING_SNAKE_CASE ) logger.info(F"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) processor.save_pretrained(__SCREAMING_SNAKE_CASE ) if repo_id: logger.info(F"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(__SCREAMING_SNAKE_CASE ) processor.push_to_hub(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint''', default='''small''', type=str, help='''Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.''', ) parser.add_argument( '''--pytorch_dump_folder''', required=True, default=None, type=str, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) parser.add_argument( '''--device''', default='''cpu''', type=str, help='''Torch device to run the conversion, either cpu or cuda.''' ) lowerCAmelCase_ = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
635
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( __snake_case , __snake_case , unittest.TestCase ): """simple docstring""" a = StableDiffusionXLImgaImgPipeline a = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} a = PipelineTesterMixin.required_optional_params - {"latents"} a = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS a = IMAGE_TO_IMAGE_IMAGE_PARAMS a = IMAGE_TO_IMAGE_IMAGE_PARAMS def _lowerCAmelCase ( self : Dict): """simple docstring""" torch.manual_seed(0) _SCREAMING_SNAKE_CASE : Any = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , attention_head_dim=(2, 4) , use_linear_projection=_A , addition_embed_type="""text_time""" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=8_0 , cross_attention_dim=6_4 , ) _SCREAMING_SNAKE_CASE : Dict = EulerDiscreteScheduler( beta_start=0.00_085 , beta_end=0.012 , steps_offset=1 , beta_schedule="""scaled_linear""" , timestep_spacing="""leading""" , ) torch.manual_seed(0) _SCREAMING_SNAKE_CASE : Any = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0) _SCREAMING_SNAKE_CASE : Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act="""gelu""" , projection_dim=3_2 , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTextModel(_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=_A) _SCREAMING_SNAKE_CASE : int = CLIPTextModelWithProjection(_A) _SCREAMING_SNAKE_CASE : List[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=_A) _SCREAMING_SNAKE_CASE : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """text_encoder_2""": text_encoder_a, """tokenizer_2""": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def _lowerCAmelCase ( self : int , _A : Optional[int] , _A : List[str]=0): """simple docstring""" _SCREAMING_SNAKE_CASE : int = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(_A)).to(_A) _SCREAMING_SNAKE_CASE : List[Any] = image / 2 + 0.5 if str(_A).startswith("""mps"""): _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.manual_seed(_A) else: _SCREAMING_SNAKE_CASE : str = torch.Generator(device=_A).manual_seed(_A) _SCREAMING_SNAKE_CASE : int = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 5.0, """output_type""": """numpy""", """strength""": 0.75, } return inputs def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator _SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_components() _SCREAMING_SNAKE_CASE : Dict = StableDiffusionXLImgaImgPipeline(**_A) _SCREAMING_SNAKE_CASE : Optional[int] = sd_pipe.to(_A) sd_pipe.set_progress_bar_config(disable=_A) _SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(_A) _SCREAMING_SNAKE_CASE : Any = sd_pipe(**_A).images _SCREAMING_SNAKE_CASE : int = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) _SCREAMING_SNAKE_CASE : str = np.array([0.4_656, 0.4_840, 0.4_439, 0.6_698, 0.5_574, 0.4_524, 0.5_799, 0.5_943, 0.5_165]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 def _lowerCAmelCase ( self : Any): """simple docstring""" super().test_attention_slicing_forward_pass(expected_max_diff=3e-3) def _lowerCAmelCase ( self : Any): """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3) def _lowerCAmelCase ( self : Tuple): """simple docstring""" pass def _lowerCAmelCase ( self : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_components() _SCREAMING_SNAKE_CASE : List[str] = StableDiffusionXLImgaImgPipeline(**_A) _SCREAMING_SNAKE_CASE : Optional[int] = sd_pipe.to(_A) _SCREAMING_SNAKE_CASE : str = sd_pipe.to(_A) sd_pipe.set_progress_bar_config(disable=_A) # forward without prompt embeds _SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(_A) _SCREAMING_SNAKE_CASE : List[str] = 3 * ["""this is a negative prompt"""] _SCREAMING_SNAKE_CASE : str = negative_prompt _SCREAMING_SNAKE_CASE : List[Any] = 3 * [inputs["""prompt"""]] _SCREAMING_SNAKE_CASE : List[str] = sd_pipe(**_A) _SCREAMING_SNAKE_CASE : Optional[int] = output.images[0, -3:, -3:, -1] # forward with prompt embeds _SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = 3 * ["""this is a negative prompt"""] _SCREAMING_SNAKE_CASE : Tuple = 3 * [inputs.pop("""prompt""")] ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) : Dict = sd_pipe.encode_prompt(_A , negative_prompt=_A) _SCREAMING_SNAKE_CASE : Tuple = sd_pipe( **_A , prompt_embeds=_A , negative_prompt_embeds=_A , pooled_prompt_embeds=_A , negative_pooled_prompt_embeds=_A , ) _SCREAMING_SNAKE_CASE : Dict = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()).max() < 1e-4 @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : str): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowerCAmelCase ( self : Optional[Any] , _A : Optional[Any] , _A : Union[str, Any]="cpu" , _A : Dict=torch.floataa , _A : Optional[int]=0): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = torch.Generator(device=_A).manual_seed(_A) _SCREAMING_SNAKE_CASE : Optional[int] = np.random.RandomState(_A).standard_normal((1, 4, 6_4, 6_4)) _SCREAMING_SNAKE_CASE : Tuple = torch.from_numpy(_A).to(device=_A , dtype=_A) _SCREAMING_SNAKE_CASE : Optional[int] = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _lowerCAmelCase ( self : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE : int = DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""") pipe.to(_A) pipe.set_progress_bar_config(disable=_A) _SCREAMING_SNAKE_CASE : str = self.get_inputs(_A) _SCREAMING_SNAKE_CASE : Dict = pipe(**_A).images _SCREAMING_SNAKE_CASE : Tuple = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) _SCREAMING_SNAKE_CASE : Optional[int] = np.array([0.49_493, 0.47_896, 0.40_798, 0.54_214, 0.53_212, 0.48_202, 0.47_656, 0.46_329, 0.48_506]) assert np.abs(image_slice - expected_slice).max() < 7e-3
635
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''asapp/sew-tiny-100k''': '''https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json''', # See all SEW models at https://huggingface.co/models?filter=sew } class _snake_case ( __snake_case ): """simple docstring""" a = "sew" def __init__( self : List[Any] , _A : Tuple=3_2 , _A : str=7_6_8 , _A : Dict=1_2 , _A : Tuple=1_2 , _A : Optional[Any]=3_0_7_2 , _A : List[str]=2 , _A : Dict="gelu" , _A : Union[str, Any]=0.1 , _A : Optional[int]=0.1 , _A : Optional[int]=0.1 , _A : Optional[int]=0.0 , _A : str=0.1 , _A : Tuple=0.1 , _A : Optional[int]=0.02 , _A : Dict=1e-5 , _A : str="group" , _A : Tuple="gelu" , _A : Union[str, Any]=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , _A : Optional[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , _A : Any=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , _A : Tuple=False , _A : Tuple=1_2_8 , _A : int=1_6 , _A : Union[str, Any]=True , _A : Optional[Any]=0.05 , _A : List[Any]=1_0 , _A : Union[str, Any]=2 , _A : Tuple=0.0 , _A : Union[str, Any]=1_0 , _A : Optional[int]=0 , _A : Union[str, Any]="mean" , _A : Optional[int]=False , _A : List[Any]=False , _A : int=2_5_6 , _A : str=0 , _A : Optional[int]=1 , _A : List[Any]=2 , **_A : Dict , ): """simple docstring""" super().__init__(**_A , pad_token_id=_A , bos_token_id=_A , eos_token_id=_A) _SCREAMING_SNAKE_CASE : str = hidden_size _SCREAMING_SNAKE_CASE : Optional[int] = feat_extract_norm _SCREAMING_SNAKE_CASE : Optional[int] = feat_extract_activation _SCREAMING_SNAKE_CASE : Dict = list(_A) _SCREAMING_SNAKE_CASE : int = list(_A) _SCREAMING_SNAKE_CASE : int = list(_A) _SCREAMING_SNAKE_CASE : str = conv_bias _SCREAMING_SNAKE_CASE : Tuple = num_conv_pos_embeddings _SCREAMING_SNAKE_CASE : List[str] = num_conv_pos_embedding_groups _SCREAMING_SNAKE_CASE : Tuple = len(self.conv_dim) _SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers _SCREAMING_SNAKE_CASE : List[str] = intermediate_size _SCREAMING_SNAKE_CASE : str = squeeze_factor _SCREAMING_SNAKE_CASE : Dict = hidden_act _SCREAMING_SNAKE_CASE : str = num_attention_heads _SCREAMING_SNAKE_CASE : Dict = hidden_dropout _SCREAMING_SNAKE_CASE : Tuple = attention_dropout _SCREAMING_SNAKE_CASE : int = activation_dropout _SCREAMING_SNAKE_CASE : Any = feat_proj_dropout _SCREAMING_SNAKE_CASE : str = final_dropout _SCREAMING_SNAKE_CASE : Union[str, Any] = layerdrop _SCREAMING_SNAKE_CASE : Any = layer_norm_eps _SCREAMING_SNAKE_CASE : int = initializer_range _SCREAMING_SNAKE_CASE : List[Any] = vocab_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect.""" """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,""" f"""but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride)""" f"""= {len(self.conv_stride)}`, `len(config.conv_kernel) = {len(self.conv_kernel)}`.""") # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _SCREAMING_SNAKE_CASE : List[Any] = apply_spec_augment _SCREAMING_SNAKE_CASE : List[Any] = mask_time_prob _SCREAMING_SNAKE_CASE : List[str] = mask_time_length _SCREAMING_SNAKE_CASE : List[Any] = mask_time_min_masks _SCREAMING_SNAKE_CASE : List[Any] = mask_feature_prob _SCREAMING_SNAKE_CASE : int = mask_feature_length _SCREAMING_SNAKE_CASE : List[Any] = mask_feature_min_masks # ctc loss _SCREAMING_SNAKE_CASE : int = ctc_loss_reduction _SCREAMING_SNAKE_CASE : Optional[int] = ctc_zero_infinity # sequence classification _SCREAMING_SNAKE_CASE : Dict = use_weighted_layer_sum _SCREAMING_SNAKE_CASE : List[str] = classifier_proj_size @property def _lowerCAmelCase ( self : Any): """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1)
635
1
"""simple docstring""" from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> int: _SCREAMING_SNAKE_CASE : Any = [] for part_id in partition_order: _SCREAMING_SNAKE_CASE : List[str] = df.where(F"""SPARK_PARTITION_ID() = {part_id}""" ).collect() for row_idx, row in enumerate(__SCREAMING_SNAKE_CASE ): expected_row_ids_and_row_dicts.append((F"""{part_id}_{row_idx}""", row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def lowerCamelCase_()-> Tuple: _SCREAMING_SNAKE_CASE : Any = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _SCREAMING_SNAKE_CASE : Union[str, Any] = spark.range(100 ).repartition(1 ) _SCREAMING_SNAKE_CASE : Optional[int] = Spark(__SCREAMING_SNAKE_CASE ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=16 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 50 @require_not_windows @require_dill_gt_0_3_2 def lowerCamelCase_()-> List[str]: _SCREAMING_SNAKE_CASE : Union[str, Any] = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _SCREAMING_SNAKE_CASE : List[Any] = spark.range(10 ).repartition(2 ) _SCREAMING_SNAKE_CASE : List[Any] = [1, 0] _SCREAMING_SNAKE_CASE : List[str] = _generate_iterable_examples(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Reverse the partitions. _SCREAMING_SNAKE_CASE : List[str] = _get_expected_row_ids_and_row_dicts_for_partition_order(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for i, (row_id, row_dict) in enumerate(generate_fn() ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def lowerCamelCase_()-> Optional[int]: _SCREAMING_SNAKE_CASE : Union[str, Any] = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _SCREAMING_SNAKE_CASE : Union[str, Any] = spark.range(10 ).repartition(1 ) _SCREAMING_SNAKE_CASE : List[Any] = SparkExamplesIterable(__SCREAMING_SNAKE_CASE ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(__SCREAMING_SNAKE_CASE ): assert row_id == F"""0_{i}""" assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def lowerCamelCase_()-> Tuple: _SCREAMING_SNAKE_CASE : Optional[Any] = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _SCREAMING_SNAKE_CASE : int = spark.range(30 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch("""numpy.random.Generator""" ) as generator_mock: _SCREAMING_SNAKE_CASE : List[str] = lambda __SCREAMING_SNAKE_CASE : x.reverse() _SCREAMING_SNAKE_CASE : int = _get_expected_row_ids_and_row_dicts_for_partition_order(__SCREAMING_SNAKE_CASE , [2, 1, 0] ) _SCREAMING_SNAKE_CASE : Tuple = SparkExamplesIterable(__SCREAMING_SNAKE_CASE ).shuffle_data_sources(__SCREAMING_SNAKE_CASE ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def lowerCamelCase_()-> Optional[Any]: _SCREAMING_SNAKE_CASE : Optional[Any] = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _SCREAMING_SNAKE_CASE : Any = spark.range(20 ).repartition(4 ) # Partitions 0 and 2 _SCREAMING_SNAKE_CASE : List[str] = SparkExamplesIterable(__SCREAMING_SNAKE_CASE ).shard_data_sources(worker_id=0 , num_workers=2 ) assert shard_it_a.n_shards == 2 _SCREAMING_SNAKE_CASE : Optional[Any] = _get_expected_row_ids_and_row_dicts_for_partition_order(__SCREAMING_SNAKE_CASE , [0, 2] ) for i, (row_id, row_dict) in enumerate(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 _SCREAMING_SNAKE_CASE : List[Any] = SparkExamplesIterable(__SCREAMING_SNAKE_CASE ).shard_data_sources(worker_id=1 , num_workers=2 ) assert shard_it_a.n_shards == 2 _SCREAMING_SNAKE_CASE : Union[str, Any] = _get_expected_row_ids_and_row_dicts_for_partition_order(__SCREAMING_SNAKE_CASE , [1, 3] ) for i, (row_id, row_dict) in enumerate(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def lowerCamelCase_()-> Optional[int]: _SCREAMING_SNAKE_CASE : Any = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _SCREAMING_SNAKE_CASE : Optional[int] = spark.range(100 ).repartition(1 ) _SCREAMING_SNAKE_CASE : Any = Spark(__SCREAMING_SNAKE_CASE ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 100
635
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCAmelCase_ = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
635
1
"""simple docstring""" import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class _snake_case : """simple docstring""" def __init__( self : int , _A : List[Any] , _A : int , _A : int): """simple docstring""" if dst_width < 0 or dst_height < 0: raise ValueError("""Destination width/height should be > 0""") _SCREAMING_SNAKE_CASE : str = img _SCREAMING_SNAKE_CASE : Optional[Any] = img.shape[1] _SCREAMING_SNAKE_CASE : Tuple = img.shape[0] _SCREAMING_SNAKE_CASE : Any = dst_width _SCREAMING_SNAKE_CASE : Any = dst_height _SCREAMING_SNAKE_CASE : Any = self.src_w / self.dst_w _SCREAMING_SNAKE_CASE : Dict = self.src_h / self.dst_h _SCREAMING_SNAKE_CASE : Optional[Any] = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta) * 2_5_5 ) def _lowerCAmelCase ( self : Tuple): """simple docstring""" for i in range(self.dst_h): for j in range(self.dst_w): _SCREAMING_SNAKE_CASE : Any = self.img[self.get_y(_A)][self.get_x(_A)] def _lowerCAmelCase ( self : int , _A : int): """simple docstring""" return int(self.ratio_x * x) def _lowerCAmelCase ( self : str , _A : int): """simple docstring""" return int(self.ratio_y * y) if __name__ == "__main__": lowerCAmelCase_ , lowerCAmelCase_ = 800, 600 lowerCAmelCase_ = imread('''image_data/lena.jpg''', 1) lowerCAmelCase_ = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}", n.output ) waitKey(0) destroyAllWindows()
635
"""simple docstring""" import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: _SCREAMING_SNAKE_CASE : List[str] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Union[str, Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _SCREAMING_SNAKE_CASE : List[Any] = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: _SCREAMING_SNAKE_CASE : int = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : str = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : List[Any] = features.copy() if features else default_expected_features _SCREAMING_SNAKE_CASE : List[Any] = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) _SCREAMING_SNAKE_CASE : Optional[Any] = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: _SCREAMING_SNAKE_CASE : Tuple = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : int = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : Dict = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , split=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""" , [str, list] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> str: if issubclass(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = parquet_path elif issubclass(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = [parquet_path] _SCREAMING_SNAKE_CASE : Optional[Any] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Union[str, Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : str = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=("train",) )-> Union[str, Any]: assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for split in splits: _SCREAMING_SNAKE_CASE : int = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Optional[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _SCREAMING_SNAKE_CASE : Tuple = ParquetDatasetReader( {"""train""": parquet_path} , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: _SCREAMING_SNAKE_CASE : Optional[int] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : Optional[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : List[str] = features.copy() if features else default_expected_features _SCREAMING_SNAKE_CASE : str = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) _SCREAMING_SNAKE_CASE : int = ParquetDatasetReader({"""train""": parquet_path} , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Dict: if split: _SCREAMING_SNAKE_CASE : Union[str, Any] = {split: parquet_path} else: _SCREAMING_SNAKE_CASE : Optional[int] = """train""" _SCREAMING_SNAKE_CASE : Any = {"""train""": parquet_path, """test""": parquet_path} _SCREAMING_SNAKE_CASE : List[str] = tmp_path / """cache""" _SCREAMING_SNAKE_CASE : List[str] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE : Union[str, Any] = ParquetDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> List[Any]: _SCREAMING_SNAKE_CASE : List[str] = ParquetDatasetWriter(__SCREAMING_SNAKE_CASE , tmp_path / """foo.parquet""" ) assert writer.write() > 0 _SCREAMING_SNAKE_CASE : Tuple = pq.ParquetFile(tmp_path / """foo.parquet""" ) _SCREAMING_SNAKE_CASE : str = pf.read() assert dataset.data.table == output_table def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Union[str, Any]: _SCREAMING_SNAKE_CASE : Dict = str(shared_datadir / """test_image_rgb.jpg""" ) _SCREAMING_SNAKE_CASE : Optional[Any] = {"""image""": [image_path]} _SCREAMING_SNAKE_CASE : Optional[Any] = Features({"""image""": Image()} ) _SCREAMING_SNAKE_CASE : Optional[int] = Dataset.from_dict(__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Tuple = ParquetDatasetWriter(__SCREAMING_SNAKE_CASE , tmp_path / """foo.parquet""" ) assert writer.write() > 0 _SCREAMING_SNAKE_CASE : List[str] = Dataset.from_parquet(str(tmp_path / """foo.parquet""" ) ) assert dataset.features == reloaded_dataset.features _SCREAMING_SNAKE_CASE : List[Any] = ParquetDatasetReader(str(tmp_path / """foo.parquet""" ) , streaming=__SCREAMING_SNAKE_CASE ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( """feature, expected""" , [ (Features({"""foo""": Value("""int32""" )} ), None), (Features({"""image""": Image(), """foo""": Value("""int32""" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"""nested""": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> int: assert get_writer_batch_size(__SCREAMING_SNAKE_CASE ) == expected
635
1
"""simple docstring""" 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 lowerCAmelCase_ = logging.get_logger(__name__) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False )-> str: 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 : int = os.path.abspath(__SCREAMING_SNAKE_CASE ) logger.info(F"""Loading PyTorch weights from {pt_path}""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(__SCREAMING_SNAKE_CASE , map_location="""cpu""" ) logger.info(F"""PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values() ):,} parameters.""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = convert_pytorch_state_dict_to_flax(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files _SCREAMING_SNAKE_CASE : Any = convert_pytorch_sharded_state_dict_to_flax(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return flax_state_dict def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , )-> (Tuple[str], np.ndarray): def is_key_or_prefix_key_in_dict(__SCREAMING_SNAKE_CASE ) -> bool: return len(set(__SCREAMING_SNAKE_CASE ) & {key, (model_prefix,) + key} ) > 0 # layer norm _SCREAMING_SNAKE_CASE : str = pt_tuple_key[:-1] + ("""scale""",) if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(__SCREAMING_SNAKE_CASE ): return renamed_pt_tuple_key, pt_tensor # batch norm layer mean _SCREAMING_SNAKE_CASE : List[Any] = pt_tuple_key[:-1] + ("""mean""",) if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(__SCREAMING_SNAKE_CASE ): return renamed_pt_tuple_key, pt_tensor # batch norm layer var _SCREAMING_SNAKE_CASE : Optional[Any] = pt_tuple_key[:-1] + ("""var""",) if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(__SCREAMING_SNAKE_CASE ): return renamed_pt_tuple_key, pt_tensor # embedding _SCREAMING_SNAKE_CASE : List[str] = pt_tuple_key[:-1] + ("""embedding""",) if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(__SCREAMING_SNAKE_CASE ): 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(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer _SCREAMING_SNAKE_CASE : Tuple = pt_tuple_key[:-1] + ("""kernel""",) if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight _SCREAMING_SNAKE_CASE : List[str] = 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 : Any = 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 : Union[str, Any] = 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 : Optional[int] = pt_tuple_key[-2] + """_v""" if name is not None: _SCREAMING_SNAKE_CASE : Dict = pt_tuple_key[:-3] + (name,) return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: # convert pytorch tensor to numpy _SCREAMING_SNAKE_CASE : Optional[Any] = {k: v.numpy() for k, v in pt_state_dict.items()} _SCREAMING_SNAKE_CASE : str = flax_model.base_model_prefix # use params dict if the model contains batch norm layers if "params" in flax_model.params: _SCREAMING_SNAKE_CASE : str = flax_model.params["""params"""] else: _SCREAMING_SNAKE_CASE : Any = flax_model.params _SCREAMING_SNAKE_CASE : List[Any] = flatten_dict(__SCREAMING_SNAKE_CASE ) # add batch_stats keys,values to dict if "batch_stats" in flax_model.params: _SCREAMING_SNAKE_CASE : Union[str, Any] = flatten_dict(flax_model.params["""batch_stats"""] ) random_flax_state_dict.update(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Union[str, Any] = {} _SCREAMING_SNAKE_CASE : 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 : List[str] = (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 : Union[str, Any] = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: _SCREAMING_SNAKE_CASE : Union[str, Any] = pt_tuple_key[1:] # Correctly rename weight parameters _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = rename_key_and_reshape_tensor( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # add model prefix if necessary _SCREAMING_SNAKE_CASE : 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 : Tuple = (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 : List[Any] = jnp.asarray(__SCREAMING_SNAKE_CASE ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) continue # also add unexpected weight so that warning is thrown _SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.asarray(__SCREAMING_SNAKE_CASE ) else: # also add unexpected weight so that warning is thrown _SCREAMING_SNAKE_CASE : str = jnp.asarray(__SCREAMING_SNAKE_CASE ) return unflatten_dict(__SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: import torch # Load the index _SCREAMING_SNAKE_CASE : Tuple = {} for shard_file in shard_filenames: # load using msgpack utils _SCREAMING_SNAKE_CASE : Optional[int] = torch.load(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : List[str] = {k: v.numpy() for k, v in pt_state_dict.items()} _SCREAMING_SNAKE_CASE : Dict = 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 : Tuple = flax_model.params["""params"""] _SCREAMING_SNAKE_CASE : Any = flatten_dict(__SCREAMING_SNAKE_CASE ) random_flax_state_dict.update(flatten_dict(flax_model.params["""batch_stats"""] ) ) else: _SCREAMING_SNAKE_CASE : int = flax_model.params _SCREAMING_SNAKE_CASE : Dict = flatten_dict(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : 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 : List[str] = (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 : List[Any] = tuple(pt_key.split(""".""" ) ) # remove base model prefix if necessary _SCREAMING_SNAKE_CASE : List[str] = 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( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # add model prefix if necessary _SCREAMING_SNAKE_CASE : Union[str, 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 : Optional[int] = (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 : Any = jnp.asarray(__SCREAMING_SNAKE_CASE ) continue if "var" in flax_key[-1]: _SCREAMING_SNAKE_CASE : Dict = jnp.asarray(__SCREAMING_SNAKE_CASE ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) continue # also add unexpected weight so that warning is thrown _SCREAMING_SNAKE_CASE : Any = jnp.asarray(__SCREAMING_SNAKE_CASE ) else: # also add unexpected weight so that warning is thrown _SCREAMING_SNAKE_CASE : Optional[int] = jnp.asarray(__SCREAMING_SNAKE_CASE ) return unflatten_dict(__SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: _SCREAMING_SNAKE_CASE : Any = os.path.abspath(__SCREAMING_SNAKE_CASE ) logger.info(F"""Loading Flax weights from {flax_checkpoint_path}""" ) # import correct flax class _SCREAMING_SNAKE_CASE : Optional[int] = getattr(__SCREAMING_SNAKE_CASE , """Flax""" + model.__class__.__name__ ) # load flax weight dict with open(__SCREAMING_SNAKE_CASE , """rb""" ) as state_f: try: _SCREAMING_SNAKE_CASE : int = from_bytes(__SCREAMING_SNAKE_CASE , 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(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Tuple: 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 : Union[str, Any] = flatten_dict(jax.tree_util.tree_map(lambda __SCREAMING_SNAKE_CASE : x.dtype == jnp.bfloataa , __SCREAMING_SNAKE_CASE ) ).values() if any(__SCREAMING_SNAKE_CASE ): # 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 : int = jax.tree_util.tree_map( lambda __SCREAMING_SNAKE_CASE : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , __SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[int] = flatten_dict(__SCREAMING_SNAKE_CASE ) _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 : List[str] = [] _SCREAMING_SNAKE_CASE : Dict = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): _SCREAMING_SNAKE_CASE : Any = flax_key_tuple[0] == pt_model.base_model_prefix _SCREAMING_SNAKE_CASE : 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 : List[Any] = flax_key_tuple[1:] elif load_base_model_into_model_with_head and require_base_model_prefix: _SCREAMING_SNAKE_CASE : List[str] = (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(__SCREAMING_SNAKE_CASE ) not in pt_model_dict: # conv layer _SCREAMING_SNAKE_CASE : Optional[Any] = flax_key_tuple[:-1] + ("""weight""",) _SCREAMING_SNAKE_CASE : Dict = jnp.transpose(__SCREAMING_SNAKE_CASE , (3, 2, 0, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(__SCREAMING_SNAKE_CASE ) not in pt_model_dict: # linear layer _SCREAMING_SNAKE_CASE : Any = flax_key_tuple[:-1] + ("""weight""",) _SCREAMING_SNAKE_CASE : List[str] = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: _SCREAMING_SNAKE_CASE : List[str] = flax_key_tuple[:-1] + ("""weight""",) # adding batch stats from flax batch norm to pt elif "mean" in flax_key_tuple[-1]: _SCREAMING_SNAKE_CASE : int = flax_key_tuple[:-1] + ("""running_mean""",) elif "var" in flax_key_tuple[-1]: _SCREAMING_SNAKE_CASE : Optional[int] = flax_key_tuple[:-1] + ("""running_var""",) if "batch_stats" in flax_state: _SCREAMING_SNAKE_CASE : Any = """.""".join(flax_key_tuple[1:] ) # Remove the params/batch_stats header else: _SCREAMING_SNAKE_CASE : Tuple = """.""".join(__SCREAMING_SNAKE_CASE ) # We also need to look at `pt_model_dict` and see if there are keys requiring further transformation. _SCREAMING_SNAKE_CASE : Any = {} # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 for key in pt_model_dict: _SCREAMING_SNAKE_CASE : Dict = key.split(""".""" ) _SCREAMING_SNAKE_CASE : int = None if key_components[-3::2] == ["parametrizations", "original0"]: _SCREAMING_SNAKE_CASE : List[str] = key_components[-2] + """_g""" elif key_components[-3::2] == ["parametrizations", "original1"]: _SCREAMING_SNAKE_CASE : List[Any] = key_components[-2] + """_v""" if name is not None: _SCREAMING_SNAKE_CASE : Optional[int] = key_components[:-3] + [name] _SCREAMING_SNAKE_CASE : Union[str, Any] = """.""".join(__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Optional[int] = key if flax_key in special_pt_names: _SCREAMING_SNAKE_CASE : Tuple = 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 : Optional[Any] = np.asarray(__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , np.ndarray ) else flax_tensor _SCREAMING_SNAKE_CASE : str = torch.from_numpy(__SCREAMING_SNAKE_CASE ) # remove from missing keys missing_keys.remove(__SCREAMING_SNAKE_CASE ) else: # weight is not expected by PyTorch model unexpected_keys.append(__SCREAMING_SNAKE_CASE ) pt_model.load_state_dict(__SCREAMING_SNAKE_CASE ) # re-transform missing_keys to list _SCREAMING_SNAKE_CASE : Optional[int] = list(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 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(__SCREAMING_SNAKE_CASE ) > 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
635
"""simple docstring""" def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> int: if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise TypeError("""only integers accepted as input""" ) else: _SCREAMING_SNAKE_CASE : List[Any] = str(abs(__SCREAMING_SNAKE_CASE ) ) _SCREAMING_SNAKE_CASE : List[str] = [list(__SCREAMING_SNAKE_CASE ) for char in range(len(__SCREAMING_SNAKE_CASE ) )] for index in range(len(__SCREAMING_SNAKE_CASE ) ): num_transpositions[index].pop(__SCREAMING_SNAKE_CASE ) return max( int("""""".join(list(__SCREAMING_SNAKE_CASE ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('''doctest''').testmod()
635
1
"""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 from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''microsoft/resnet-50''': '''https://huggingface.co/microsoft/resnet-50/blob/main/config.json''', } class _snake_case ( __snake_case , __snake_case ): """simple docstring""" a = "resnet" a = ["basic", "bottleneck"] def __init__( self : Optional[int] , _A : List[str]=3 , _A : Dict=6_4 , _A : Dict=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , _A : str=[3, 4, 6, 3] , _A : Optional[int]="bottleneck" , _A : Optional[int]="relu" , _A : Tuple=False , _A : Tuple=None , _A : List[str]=None , **_A : Optional[Any] , ): """simple docstring""" super().__init__(**_A) if layer_type not in self.layer_types: raise ValueError(f"""layer_type={layer_type} is not one of {",".join(self.layer_types)}""") _SCREAMING_SNAKE_CASE : Any = num_channels _SCREAMING_SNAKE_CASE : int = embedding_size _SCREAMING_SNAKE_CASE : Optional[Any] = hidden_sizes _SCREAMING_SNAKE_CASE : List[Any] = depths _SCREAMING_SNAKE_CASE : str = layer_type _SCREAMING_SNAKE_CASE : List[Any] = hidden_act _SCREAMING_SNAKE_CASE : int = downsample_in_first_stage _SCREAMING_SNAKE_CASE : Union[str, Any] = ["""stem"""] + [f"""stage{idx}""" for idx in range(1 , len(_A) + 1)] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = get_aligned_output_features_output_indices( out_features=_A , out_indices=_A , stage_names=self.stage_names) class _snake_case ( __snake_case ): """simple docstring""" a = version.parse("1.11" ) @property def _lowerCAmelCase ( self : Optional[Any]): """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ]) @property def _lowerCAmelCase ( self : Tuple): """simple docstring""" return 1e-3
635
"""simple docstring""" import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers import AutoModelForCausalLM @require_torch class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : Any = -1 _SCREAMING_SNAKE_CASE : List[str] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : Dict = model.generate(_A , max_new_tokens=1_0 , do_sample=_A) _SCREAMING_SNAKE_CASE : Dict = tokenizer.decode(greedy_ids[0]) with CaptureStdout() as cs: _SCREAMING_SNAKE_CASE : Any = TextStreamer(_A) model.generate(_A , max_new_tokens=1_0 , do_sample=_A , streamer=_A) # The greedy text should be printed to stdout, except for the final "\n" in the streamer _SCREAMING_SNAKE_CASE : str = cs.out[:-1] self.assertEqual(_A , _A) def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : Any = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : List[Any] = -1 _SCREAMING_SNAKE_CASE : str = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = model.generate(_A , max_new_tokens=1_0 , do_sample=_A) _SCREAMING_SNAKE_CASE : Any = tokenizer.decode(greedy_ids[0]) _SCREAMING_SNAKE_CASE : List[Any] = TextIteratorStreamer(_A) _SCREAMING_SNAKE_CASE : Any = {"""input_ids""": input_ids, """max_new_tokens""": 1_0, """do_sample""": False, """streamer""": streamer} _SCREAMING_SNAKE_CASE : List[Any] = Thread(target=model.generate , kwargs=_A) thread.start() _SCREAMING_SNAKE_CASE : Any = """""" for new_text in streamer: streamer_text += new_text self.assertEqual(_A , _A) def _lowerCAmelCase ( self : List[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : Any = -1 _SCREAMING_SNAKE_CASE : Any = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = model.generate(_A , max_new_tokens=1_0 , do_sample=_A) _SCREAMING_SNAKE_CASE : str = greedy_ids[:, input_ids.shape[1] :] _SCREAMING_SNAKE_CASE : Dict = tokenizer.decode(new_greedy_ids[0]) with CaptureStdout() as cs: _SCREAMING_SNAKE_CASE : Any = TextStreamer(_A , skip_prompt=_A) model.generate(_A , max_new_tokens=1_0 , do_sample=_A , streamer=_A) # The greedy text should be printed to stdout, except for the final "\n" in the streamer _SCREAMING_SNAKE_CASE : Optional[int] = cs.out[:-1] self.assertEqual(_A , _A) def _lowerCAmelCase ( self : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained("""distilgpt2""") _SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForCausalLM.from_pretrained("""distilgpt2""").to(_A) _SCREAMING_SNAKE_CASE : int = -1 _SCREAMING_SNAKE_CASE : List[str] = torch.ones((1, 5) , device=_A).long() * model.config.bos_token_id with CaptureStdout() as cs: _SCREAMING_SNAKE_CASE : Optional[int] = TextStreamer(_A , skip_special_tokens=_A) model.generate(_A , max_new_tokens=1 , do_sample=_A , streamer=_A) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token _SCREAMING_SNAKE_CASE : Optional[Any] = cs.out[:-1] # Remove the final "\n" _SCREAMING_SNAKE_CASE : Tuple = tokenizer(_A , return_tensors="""pt""") self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1)) def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""") _SCREAMING_SNAKE_CASE : List[Any] = AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A) _SCREAMING_SNAKE_CASE : Tuple = -1 _SCREAMING_SNAKE_CASE : Dict = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(_A) _SCREAMING_SNAKE_CASE : int = TextIteratorStreamer(_A , timeout=0.001) _SCREAMING_SNAKE_CASE : List[Any] = {"""input_ids""": input_ids, """max_new_tokens""": 1_0, """do_sample""": False, """streamer""": streamer} _SCREAMING_SNAKE_CASE : List[str] = Thread(target=model.generate , kwargs=_A) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(_A): _SCREAMING_SNAKE_CASE : str = """""" for new_text in streamer: streamer_text += new_text
635
1
"""simple docstring""" from copy import deepcopy from typing import Optional, Union import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_tf_available, is_torch_available if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf class _snake_case ( __snake_case ): """simple docstring""" a = ["image_processor"] a = "SamImageProcessor" def __init__( self : Dict , _A : Any): """simple docstring""" super().__init__(_A) _SCREAMING_SNAKE_CASE : Tuple = self.image_processor _SCREAMING_SNAKE_CASE : Optional[int] = -1_0 _SCREAMING_SNAKE_CASE : str = self.image_processor.size["""longest_edge"""] def __call__( self : Union[str, Any] , _A : Tuple=None , _A : List[str]=None , _A : Optional[int]=None , _A : Tuple=None , _A : Optional[Union[str, TensorType]] = None , **_A : int , ): """simple docstring""" _SCREAMING_SNAKE_CASE : int = self.image_processor( _A , return_tensors=_A , **_A , ) # pop arguments that are not used in the foward but used nevertheless _SCREAMING_SNAKE_CASE : Optional[int] = encoding_image_processor["""original_sizes"""] if hasattr(_A , """numpy"""): # Checks if Torch or TF tensor _SCREAMING_SNAKE_CASE : Optional[Any] = original_sizes.numpy() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = self._check_and_preprocess_points( input_points=_A , input_labels=_A , input_boxes=_A , ) _SCREAMING_SNAKE_CASE : List[Any] = self._normalize_and_convert( _A , _A , input_points=_A , input_labels=_A , input_boxes=_A , return_tensors=_A , ) return encoding_image_processor def _lowerCAmelCase ( self : List[str] , _A : Optional[Any] , _A : Tuple , _A : Union[str, Any]=None , _A : Tuple=None , _A : int=None , _A : List[str]="pt" , ): """simple docstring""" if input_points is not None: if len(_A) != len(_A): _SCREAMING_SNAKE_CASE : List[str] = [ self._normalize_coordinates(self.target_size , _A , original_sizes[0]) for point in input_points ] else: _SCREAMING_SNAKE_CASE : List[Any] = [ self._normalize_coordinates(self.target_size , _A , _A) for point, original_size in zip(_A , _A) ] # check that all arrays have the same shape if not all(point.shape == input_points[0].shape for point in input_points): if input_labels is not None: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = self._pad_points_and_labels(_A , _A) _SCREAMING_SNAKE_CASE : List[str] = np.array(_A) if input_labels is not None: _SCREAMING_SNAKE_CASE : Any = np.array(_A) if input_boxes is not None: if len(_A) != len(_A): _SCREAMING_SNAKE_CASE : Optional[int] = [ self._normalize_coordinates(self.target_size , _A , original_sizes[0] , is_bounding_box=_A) for box in input_boxes ] else: _SCREAMING_SNAKE_CASE : List[Any] = [ self._normalize_coordinates(self.target_size , _A , _A , is_bounding_box=_A) for box, original_size in zip(_A , _A) ] _SCREAMING_SNAKE_CASE : Any = np.array(_A) if input_boxes is not None: if return_tensors == "pt": _SCREAMING_SNAKE_CASE : Optional[int] = torch.from_numpy(_A) # boxes batch size of 1 by default _SCREAMING_SNAKE_CASE : Dict = input_boxes.unsqueeze(1) if len(input_boxes.shape) != 3 else input_boxes elif return_tensors == "tf": _SCREAMING_SNAKE_CASE : List[str] = tf.convert_to_tensor(_A) # boxes batch size of 1 by default _SCREAMING_SNAKE_CASE : int = tf.expand_dims(_A , 1) if len(input_boxes.shape) != 3 else input_boxes encoding_image_processor.update({"""input_boxes""": input_boxes}) if input_points is not None: if return_tensors == "pt": _SCREAMING_SNAKE_CASE : List[str] = torch.from_numpy(_A) # point batch size of 1 by default _SCREAMING_SNAKE_CASE : str = input_points.unsqueeze(1) if len(input_points.shape) != 4 else input_points elif return_tensors == "tf": _SCREAMING_SNAKE_CASE : List[Any] = tf.convert_to_tensor(_A) # point batch size of 1 by default _SCREAMING_SNAKE_CASE : int = tf.expand_dims(_A , 1) if len(input_points.shape) != 4 else input_points encoding_image_processor.update({"""input_points""": input_points}) if input_labels is not None: if return_tensors == "pt": _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.from_numpy(_A) # point batch size of 1 by default _SCREAMING_SNAKE_CASE : Optional[int] = input_labels.unsqueeze(1) if len(input_labels.shape) != 3 else input_labels elif return_tensors == "tf": _SCREAMING_SNAKE_CASE : Tuple = tf.convert_to_tensor(_A) # point batch size of 1 by default _SCREAMING_SNAKE_CASE : Optional[Any] = tf.expand_dims(_A , 1) if len(input_labels.shape) != 3 else input_labels encoding_image_processor.update({"""input_labels""": input_labels}) return encoding_image_processor def _lowerCAmelCase ( self : List[Any] , _A : Dict , _A : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : str = max([point.shape[0] for point in input_points]) _SCREAMING_SNAKE_CASE : Any = [] for i, point in enumerate(_A): if point.shape[0] != expected_nb_points: _SCREAMING_SNAKE_CASE : Optional[int] = np.concatenate( [point, np.zeros((expected_nb_points - point.shape[0], 2)) + self.point_pad_value] , axis=0) _SCREAMING_SNAKE_CASE : Optional[Any] = np.append(input_labels[i] , [self.point_pad_value]) processed_input_points.append(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = processed_input_points return input_points, input_labels def _lowerCAmelCase ( self : Optional[int] , _A : int , _A : np.ndarray , _A : Union[str, Any] , _A : Tuple=False): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = original_size _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = self.image_processor._get_preprocess_shape(_A , longest_edge=_A) _SCREAMING_SNAKE_CASE : Dict = deepcopy(_A).astype(_A) if is_bounding_box: _SCREAMING_SNAKE_CASE : Optional[Any] = coords.reshape(-1 , 2 , 2) _SCREAMING_SNAKE_CASE : str = coords[..., 0] * (new_w / old_w) _SCREAMING_SNAKE_CASE : List[Any] = coords[..., 1] * (new_h / old_h) if is_bounding_box: _SCREAMING_SNAKE_CASE : List[str] = coords.reshape(-1 , 4) return coords def _lowerCAmelCase ( self : Union[str, Any] , _A : Dict=None , _A : Dict=None , _A : List[str]=None , ): """simple docstring""" if input_points is not None: if hasattr(_A , """numpy"""): # Checks for TF or Torch tensor _SCREAMING_SNAKE_CASE : Tuple = input_points.numpy().tolist() if not isinstance(_A , _A) or not isinstance(input_points[0] , _A): raise ValueError("""Input points must be a list of list of floating points.""") _SCREAMING_SNAKE_CASE : str = [np.array(_A) for input_point in input_points] else: _SCREAMING_SNAKE_CASE : Optional[Any] = None if input_labels is not None: if hasattr(_A , """numpy"""): _SCREAMING_SNAKE_CASE : Optional[Any] = input_labels.numpy().tolist() if not isinstance(_A , _A) or not isinstance(input_labels[0] , _A): raise ValueError("""Input labels must be a list of list integers.""") _SCREAMING_SNAKE_CASE : Optional[Any] = [np.array(_A) for label in input_labels] else: _SCREAMING_SNAKE_CASE : Optional[Any] = None if input_boxes is not None: if hasattr(_A , """numpy"""): _SCREAMING_SNAKE_CASE : Union[str, Any] = input_boxes.numpy().tolist() if ( not isinstance(_A , _A) or not isinstance(input_boxes[0] , _A) or not isinstance(input_boxes[0][0] , _A) ): raise ValueError("""Input boxes must be a list of list of list of floating points.""") _SCREAMING_SNAKE_CASE : Optional[int] = [np.array(_A).astype(np.floataa) for box in input_boxes] else: _SCREAMING_SNAKE_CASE : Any = None return input_points, input_labels, input_boxes @property def _lowerCAmelCase ( self : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : str = self.image_processor.model_input_names return list(dict.fromkeys(_A)) def _lowerCAmelCase ( self : Optional[Any] , *_A : str , **_A : Optional[int]): """simple docstring""" return self.image_processor.post_process_masks(*_A , **_A)
635
"""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 torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _snake_case ( __snake_case ): """simple docstring""" a = "facebook/bart-large-mnli" a = ( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) a = "text_classifier" a = AutoTokenizer a = AutoModelForSequenceClassification a = ["text", ["text"]] a = ["text"] def _lowerCAmelCase ( self : int): """simple docstring""" super().setup() _SCREAMING_SNAKE_CASE : Any = self.model.config _SCREAMING_SNAKE_CASE : Any = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail"""): _SCREAMING_SNAKE_CASE : List[Any] = int(_A) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""") def _lowerCAmelCase ( self : Optional[Any] , _A : Tuple , _A : List[str]): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = labels return self.pre_processor( [text] * len(_A) , [f"""This example is {label}""" for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def _lowerCAmelCase ( self : Tuple , _A : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : str = outputs.logits _SCREAMING_SNAKE_CASE : List[Any] = torch.argmax(logits[:, 2]).item() return self._labels[label_id]
635
1
"""simple docstring""" import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def lowerCamelCase_(*__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=2 )-> Dict: from .. import __version__ _SCREAMING_SNAKE_CASE : int = take_from _SCREAMING_SNAKE_CASE : Union[str, Any] = () if not isinstance(args[0] , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : int = (args,) for attribute, version_name, message in args: if version.parse(version.parse(__SCREAMING_SNAKE_CASE ).base_version ) >= version.parse(__SCREAMING_SNAKE_CASE ): raise ValueError( F"""The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'""" F""" version {__version__} is >= {version_name}""" ) _SCREAMING_SNAKE_CASE : str = None if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(__SCREAMING_SNAKE_CASE ),) _SCREAMING_SNAKE_CASE : str = F"""The `{attribute}` argument is deprecated and will be removed in version {version_name}.""" elif hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): values += (getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ),) _SCREAMING_SNAKE_CASE : Optional[int] = F"""The `{attribute}` attribute is deprecated and will be removed in version {version_name}.""" elif deprecated_kwargs is None: _SCREAMING_SNAKE_CASE : Tuple = F"""`{attribute}` is deprecated and will be removed in version {version_name}.""" if warning is not None: _SCREAMING_SNAKE_CASE : int = warning + """ """ if standard_warn else """""" warnings.warn(warning + message , __SCREAMING_SNAKE_CASE , stacklevel=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and len(__SCREAMING_SNAKE_CASE ) > 0: _SCREAMING_SNAKE_CASE : Union[str, Any] = inspect.getouterframes(inspect.currentframe() )[1] _SCREAMING_SNAKE_CASE : Dict = call_frame.filename _SCREAMING_SNAKE_CASE : Union[str, Any] = call_frame.lineno _SCREAMING_SNAKE_CASE : str = call_frame.function _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = next(iter(deprecated_kwargs.items() ) ) raise TypeError(F"""{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`""" ) if len(__SCREAMING_SNAKE_CASE ) == 0: return elif len(__SCREAMING_SNAKE_CASE ) == 1: return values[0] return values
635
"""simple docstring""" import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class _snake_case ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = AutoImageProcessor.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""") _SCREAMING_SNAKE_CASE : str = AutoModelForImageClassification.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""") model.to(_A) from datasets import load_dataset _SCREAMING_SNAKE_CASE : Any = load_dataset("""nielsr/rvlcdip-demo""") _SCREAMING_SNAKE_CASE : Any = dataset["""train"""][0]["""image"""].convert("""RGB""") _SCREAMING_SNAKE_CASE : str = image_processor(_A , return_tensors="""pt""").to(_A) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE : Any = model(**_A) _SCREAMING_SNAKE_CASE : List[Any] = outputs.logits _SCREAMING_SNAKE_CASE : List[str] = torch.Size((1, 1_6)) self.assertEqual(logits.shape , _A) _SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [-0.4_158, -0.4_092, -0.4_347] , device=_A , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , _A , atol=1e-4))
635
1
"""simple docstring""" import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Any): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights _SCREAMING_SNAKE_CASE : Any = FlaxDiffusionPipeline.from_pretrained( """hf-internal-testing/tiny-stable-diffusion-pipe""" , safety_checker=_A , cache_dir=_A) _SCREAMING_SNAKE_CASE : Tuple = [t[-1] for t in os.walk(os.path.join(_A , os.listdir(_A)[0] , """snapshots"""))] _SCREAMING_SNAKE_CASE : List[str] = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith(""".bin""") for f in files) @slow @require_flax class _snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : int): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = FlaxStableDiffusionPipeline.from_pretrained( """hf-internal-testing/tiny-stable-diffusion-pipe""" , safety_checker=_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) _SCREAMING_SNAKE_CASE : Tuple = jax.random.PRNGKey(0) _SCREAMING_SNAKE_CASE : Optional[int] = 4 _SCREAMING_SNAKE_CASE : List[Any] = jax.device_count() _SCREAMING_SNAKE_CASE : int = num_samples * [prompt] _SCREAMING_SNAKE_CASE : str = pipeline.prepare_inputs(_A) # shard inputs and rng _SCREAMING_SNAKE_CASE : int = replicate(_A) _SCREAMING_SNAKE_CASE : str = jax.random.split(_A , _A) _SCREAMING_SNAKE_CASE : List[str] = shard(_A) _SCREAMING_SNAKE_CASE : str = pipeline(_A , _A , _A , _A , jit=_A).images assert images.shape == (num_samples, 1, 6_4, 6_4, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 4.1_514_745) < 1e-3 assert np.abs(np.abs(_A , dtype=np.floataa).sum() - 49_947.875) < 5e-1 _SCREAMING_SNAKE_CASE : Union[str, Any] = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]))) assert len(_A) == num_samples def _lowerCAmelCase ( self : int): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""flax""" , safety_checker=_A) _SCREAMING_SNAKE_CASE : Any = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) _SCREAMING_SNAKE_CASE : Optional[int] = jax.random.PRNGKey(0) _SCREAMING_SNAKE_CASE : List[Any] = 5_0 _SCREAMING_SNAKE_CASE : str = jax.device_count() _SCREAMING_SNAKE_CASE : List[Any] = num_samples * [prompt] _SCREAMING_SNAKE_CASE : List[str] = pipeline.prepare_inputs(_A) # shard inputs and rng _SCREAMING_SNAKE_CASE : Dict = replicate(_A) _SCREAMING_SNAKE_CASE : Tuple = jax.random.split(_A , _A) _SCREAMING_SNAKE_CASE : List[Any] = shard(_A) _SCREAMING_SNAKE_CASE : int = pipeline(_A , _A , _A , _A , jit=_A).images assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.05_652_401)) < 1e-3 assert np.abs((np.abs(_A , dtype=np.floataa).sum() - 2_383_808.2)) < 5e-1 def _lowerCAmelCase ( self : Optional[int]): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , safety_checker=_A) _SCREAMING_SNAKE_CASE : List[Any] = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) _SCREAMING_SNAKE_CASE : Optional[int] = jax.random.PRNGKey(0) _SCREAMING_SNAKE_CASE : Dict = 5_0 _SCREAMING_SNAKE_CASE : Any = jax.device_count() _SCREAMING_SNAKE_CASE : List[Any] = num_samples * [prompt] _SCREAMING_SNAKE_CASE : Optional[Any] = pipeline.prepare_inputs(_A) # shard inputs and rng _SCREAMING_SNAKE_CASE : Optional[Any] = replicate(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = jax.random.split(_A , _A) _SCREAMING_SNAKE_CASE : str = shard(_A) _SCREAMING_SNAKE_CASE : int = pipeline(_A , _A , _A , _A , jit=_A).images assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_003_906)) < 1e-3 assert np.abs((np.abs(_A , dtype=np.floataa).sum() - 2_373_516.75)) < 5e-1 def _lowerCAmelCase ( self : Any): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa) _SCREAMING_SNAKE_CASE : List[str] = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) _SCREAMING_SNAKE_CASE : Optional[Any] = jax.random.PRNGKey(0) _SCREAMING_SNAKE_CASE : Any = 5_0 _SCREAMING_SNAKE_CASE : Dict = jax.device_count() _SCREAMING_SNAKE_CASE : int = num_samples * [prompt] _SCREAMING_SNAKE_CASE : Tuple = pipeline.prepare_inputs(_A) # shard inputs and rng _SCREAMING_SNAKE_CASE : List[str] = replicate(_A) _SCREAMING_SNAKE_CASE : Dict = jax.random.split(_A , _A) _SCREAMING_SNAKE_CASE : List[str] = shard(_A) _SCREAMING_SNAKE_CASE : Any = pipeline(_A , _A , _A , _A , jit=_A).images assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_003_906)) < 1e-3 assert np.abs((np.abs(_A , dtype=np.floataa).sum() - 2_373_516.75)) < 5e-1 def _lowerCAmelCase ( self : Tuple): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxDDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , set_alpha_to_one=_A , steps_offset=1 , ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , scheduler=_A , safety_checker=_A , ) _SCREAMING_SNAKE_CASE : List[Any] = scheduler.create_state() _SCREAMING_SNAKE_CASE : Optional[Any] = scheduler_state _SCREAMING_SNAKE_CASE : Union[str, Any] = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) _SCREAMING_SNAKE_CASE : int = jax.random.PRNGKey(0) _SCREAMING_SNAKE_CASE : Optional[int] = 5_0 _SCREAMING_SNAKE_CASE : List[Any] = jax.device_count() _SCREAMING_SNAKE_CASE : Any = num_samples * [prompt] _SCREAMING_SNAKE_CASE : Any = pipeline.prepare_inputs(_A) # shard inputs and rng _SCREAMING_SNAKE_CASE : Union[str, Any] = replicate(_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = jax.random.split(_A , _A) _SCREAMING_SNAKE_CASE : Any = shard(_A) _SCREAMING_SNAKE_CASE : Dict = pipeline(_A , _A , _A , _A , jit=_A).images assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.045_043_945)) < 1e-3 assert np.abs((np.abs(_A , dtype=np.floataa).sum() - 2_347_693.5)) < 5e-1 def _lowerCAmelCase ( self : Dict): """simple docstring""" _SCREAMING_SNAKE_CASE : List[str] = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) _SCREAMING_SNAKE_CASE : Optional[Any] = jax.device_count() _SCREAMING_SNAKE_CASE : Optional[Any] = num_samples * [prompt] _SCREAMING_SNAKE_CASE : List[Any] = jax.random.split(jax.random.PRNGKey(0) , _A) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , safety_checker=_A , ) _SCREAMING_SNAKE_CASE : Optional[int] = replicate(_A) _SCREAMING_SNAKE_CASE : Optional[int] = pipeline.prepare_inputs(_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = shard(_A) _SCREAMING_SNAKE_CASE : str = pipeline(_A , _A , _A , jit=_A).images assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3) _SCREAMING_SNAKE_CASE : int = images[2, 0, 2_5_6, 1_0:1_7, 1] # With memory efficient attention _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , safety_checker=_A , use_memory_efficient_attention=_A , ) _SCREAMING_SNAKE_CASE : Tuple = replicate(_A) _SCREAMING_SNAKE_CASE : str = pipeline.prepare_inputs(_A) _SCREAMING_SNAKE_CASE : int = shard(_A) _SCREAMING_SNAKE_CASE : Optional[Any] = pipeline(_A , _A , _A , jit=_A).images assert images_eff.shape == (num_samples, 1, 5_1_2, 5_1_2, 3) _SCREAMING_SNAKE_CASE : Union[str, Any] = images[2, 0, 2_5_6, 1_0:1_7, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice).max() < 1e-2
635
"""simple docstring""" import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class _snake_case ( __snake_case ): """simple docstring""" a = "M-CLIP" def __init__( self : Optional[Any] , _A : List[str]=1_0_2_4 , _A : Union[str, Any]=7_6_8 , **_A : Optional[Any]): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = transformerDimSize _SCREAMING_SNAKE_CASE : List[str] = imageDimSize super().__init__(**_A) class _snake_case ( __snake_case ): """simple docstring""" a = MCLIPConfig def __init__( self : Dict , _A : Optional[Any] , *_A : Any , **_A : Dict): """simple docstring""" super().__init__(_A , *_A , **_A) _SCREAMING_SNAKE_CASE : Tuple = XLMRobertaModel(_A) _SCREAMING_SNAKE_CASE : List[Any] = torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims) def _lowerCAmelCase ( self : Union[str, Any] , _A : str , _A : int): """simple docstring""" _SCREAMING_SNAKE_CASE : str = self.transformer(input_ids=_A , attention_mask=_A)[0] _SCREAMING_SNAKE_CASE : Optional[Any] = (embs * attention_mask.unsqueeze(2)).sum(dim=1) / attention_mask.sum(dim=1)[:, None] return self.LinearTransformation(_A), embs
635
1
"""simple docstring""" import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser lowerCAmelCase_ = logging.getLogger(__name__) torch.set_grad_enabled(False) lowerCAmelCase_ = '''cuda''' if torch.cuda.is_available() else '''cpu''' def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=100 , __SCREAMING_SNAKE_CASE=" " )-> List[str]: _SCREAMING_SNAKE_CASE : Optional[int] = text.split(__SCREAMING_SNAKE_CASE ) return [character.join(text[i : i + n] ).strip() for i in range(0 , len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE )] def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> dict: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = [], [] for title, text in zip(documents["""title"""] , documents["""text"""] ): if text is not None: for passage in split_text(__SCREAMING_SNAKE_CASE ): titles.append(title if title is not None else """""" ) texts.append(__SCREAMING_SNAKE_CASE ) return {"title": titles, "text": texts} def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> dict: _SCREAMING_SNAKE_CASE : str = ctx_tokenizer( documents["""title"""] , documents["""text"""] , truncation=__SCREAMING_SNAKE_CASE , padding="""longest""" , return_tensors="""pt""" )["""input_ids"""] _SCREAMING_SNAKE_CASE : List[str] = ctx_encoder(input_ids.to(device=__SCREAMING_SNAKE_CASE ) , return_dict=__SCREAMING_SNAKE_CASE ).pooler_output return {"embeddings": embeddings.detach().cpu().numpy()} def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , )-> Optional[int]: ###################################### logger.info("""Step 1 - Create the dataset""" ) ###################################### # The dataset needed for RAG must have three columns: # - title (string): title of the document # - text (string): text of a passage of the document # - embeddings (array of dimension d): DPR representation of the passage # Let's say you have documents in tab-separated csv files with columns "title" and "text" assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file" # You can load a Dataset object this way _SCREAMING_SNAKE_CASE : List[Any] = load_dataset( """csv""" , data_files=[rag_example_args.csv_path] , split="""train""" , delimiter="""\t""" , column_names=["""title""", """text"""] ) # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files # Then split the documents into passages of 100 words _SCREAMING_SNAKE_CASE : int = dataset.map(__SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE , num_proc=processing_args.num_proc ) # And compute the embeddings _SCREAMING_SNAKE_CASE : Tuple = DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : Union[str, Any] = DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ) _SCREAMING_SNAKE_CASE : Dict = Features( {"""text""": Value("""string""" ), """title""": Value("""string""" ), """embeddings""": Sequence(Value("""float32""" ) )} ) # optional, save as float32 instead of float64 to save space _SCREAMING_SNAKE_CASE : Dict = dataset.map( partial(__SCREAMING_SNAKE_CASE , ctx_encoder=__SCREAMING_SNAKE_CASE , ctx_tokenizer=__SCREAMING_SNAKE_CASE ) , batched=__SCREAMING_SNAKE_CASE , batch_size=processing_args.batch_size , features=__SCREAMING_SNAKE_CASE , ) # And finally save your dataset _SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(rag_example_args.output_dir , """my_knowledge_dataset""" ) dataset.save_to_disk(__SCREAMING_SNAKE_CASE ) # from datasets import load_from_disk # dataset = load_from_disk(passages_path) # to reload the dataset ###################################### logger.info("""Step 2 - Index the dataset""" ) ###################################### # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search _SCREAMING_SNAKE_CASE : Any = faiss.IndexHNSWFlat(index_hnsw_args.d , index_hnsw_args.m , faiss.METRIC_INNER_PRODUCT ) dataset.add_faiss_index("""embeddings""" , custom_index=__SCREAMING_SNAKE_CASE ) # And save the index _SCREAMING_SNAKE_CASE : List[str] = os.path.join(rag_example_args.output_dir , """my_knowledge_dataset_hnsw_index.faiss""" ) dataset.get_index("""embeddings""" ).save(__SCREAMING_SNAKE_CASE ) # dataset.load_faiss_index("embeddings", index_path) # to reload the index @dataclass class _snake_case : """simple docstring""" a = field( default=str(Path(__snake_case ).parent / "test_run" / "dummy-kb" / "my_knowledge_dataset.csv" ) , metadata={"help": "Path to a tab-separated csv file with columns 'title' and 'text'"} , ) a = field( default=__snake_case , metadata={"help": "Question that is passed as input to RAG. Default is 'What does Moses' rod turn into ?'."} , ) a = field( default="facebook/rag-sequence-nq" , metadata={"help": "The RAG model to use. Either 'facebook/rag-sequence-nq' or 'facebook/rag-token-nq'"} , ) a = field( default="facebook/dpr-ctx_encoder-multiset-base" , metadata={ "help": ( "The DPR context encoder model to use. Either 'facebook/dpr-ctx_encoder-single-nq-base' or" " 'facebook/dpr-ctx_encoder-multiset-base'" ) } , ) a = field( default=str(Path(__snake_case ).parent / "test_run" / "dummy-kb" ) , metadata={"help": "Path to a directory where the dataset passages and the index will be saved"} , ) @dataclass class _snake_case : """simple docstring""" a = field( default=__snake_case , metadata={ "help": "The number of processes to use to split the documents into passages. Default is single process." } , ) a = field( default=16 , metadata={ "help": "The batch size to use when computing the passages embeddings using the DPR context encoder." } , ) @dataclass class _snake_case : """simple docstring""" a = field( default=7_68 , metadata={"help": "The dimension of the embeddings to pass to the HNSW Faiss index."} , ) a = field( default=1_28 , metadata={ "help": ( "The number of bi-directional links created for every new element during the HNSW index construction." ) } , ) if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) logger.setLevel(logging.INFO) lowerCAmelCase_ = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments)) lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = parser.parse_args_into_dataclasses() with TemporaryDirectory() as tmp_dir: lowerCAmelCase_ = rag_example_args.output_dir or tmp_dir main(rag_example_args, processing_args, index_hnsw_args)
635
"""simple docstring""" from decimal import Decimal, getcontext from math import ceil, factorial def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> str: if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise TypeError("""Undefined for non-integers""" ) elif precision < 1: raise ValueError("""Undefined for non-natural numbers""" ) _SCREAMING_SNAKE_CASE : int = precision _SCREAMING_SNAKE_CASE : Dict = ceil(precision / 14 ) _SCREAMING_SNAKE_CASE : int = 426_880 * Decimal(10_005 ).sqrt() _SCREAMING_SNAKE_CASE : Union[str, Any] = 1 _SCREAMING_SNAKE_CASE : str = 13_591_409 _SCREAMING_SNAKE_CASE : Tuple = Decimal(__SCREAMING_SNAKE_CASE ) for k in range(1 , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = factorial(6 * k ) // (factorial(3 * k ) * factorial(__SCREAMING_SNAKE_CASE ) ** 3) linear_term += 545_140_134 exponential_term *= -262_537_412_640_768_000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": lowerCAmelCase_ = 50 print(F"The first {n} digits of pi is: {pi(n)}")
635
1
"""simple docstring""" from heapq import heappop, heappush import numpy as np def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , )-> tuple[float | int, list[tuple[int, int]]]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = grid.shape _SCREAMING_SNAKE_CASE : str = [-1, 1, 0, 0] _SCREAMING_SNAKE_CASE : Any = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = [(0, source)], set() _SCREAMING_SNAKE_CASE : str = np.full((rows, cols) , np.inf ) _SCREAMING_SNAKE_CASE : Dict = 0 _SCREAMING_SNAKE_CASE : List[Any] = np.empty((rows, cols) , dtype=__SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE : str = None while queue: ((_SCREAMING_SNAKE_CASE) , (_SCREAMING_SNAKE_CASE)) : Any = heappop(__SCREAMING_SNAKE_CASE ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: _SCREAMING_SNAKE_CASE : Optional[Any] = [] while (x, y) != source: path.append((x, y) ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = predecessors[x, y] path.append(__SCREAMING_SNAKE_CASE ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(__SCREAMING_SNAKE_CASE ) ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: _SCREAMING_SNAKE_CASE : Optional[Any] = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(__SCREAMING_SNAKE_CASE , (dist + 1, (nx, ny)) ) _SCREAMING_SNAKE_CASE : Any = dist + 1 _SCREAMING_SNAKE_CASE : Optional[int] = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
635
"""simple docstring""" import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Optional[int]: # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file _SCREAMING_SNAKE_CASE : Optional[int] = TapasConfig.from_json_file(__SCREAMING_SNAKE_CASE ) # set absolute/relative position embeddings parameter _SCREAMING_SNAKE_CASE : Dict = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": _SCREAMING_SNAKE_CASE : str = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "WTQ": # run_task_main.py hparams _SCREAMING_SNAKE_CASE : Optional[int] = 4 _SCREAMING_SNAKE_CASE : Any = True # hparam_utils.py hparams _SCREAMING_SNAKE_CASE : Any = 0.66_46_94 _SCREAMING_SNAKE_CASE : str = 0.20_79_51 _SCREAMING_SNAKE_CASE : str = 0.12_11_94 _SCREAMING_SNAKE_CASE : List[Any] = True _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = 0.0_35_25_13 _SCREAMING_SNAKE_CASE : Optional[Any] = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams _SCREAMING_SNAKE_CASE : int = 4 _SCREAMING_SNAKE_CASE : Tuple = False # hparam_utils.py hparams _SCREAMING_SNAKE_CASE : Any = 36.45_19 _SCREAMING_SNAKE_CASE : Union[str, Any] = 0.90_34_21 _SCREAMING_SNAKE_CASE : Optional[Any] = 2_22.0_88 _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Optional[int] = True _SCREAMING_SNAKE_CASE : Dict = 0.76_31_41 _SCREAMING_SNAKE_CASE : Union[str, Any] = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "TABFACT": _SCREAMING_SNAKE_CASE : int = TapasForSequenceClassification(config=__SCREAMING_SNAKE_CASE ) elif task == "MLM": _SCREAMING_SNAKE_CASE : int = TapasForMaskedLM(config=__SCREAMING_SNAKE_CASE ) elif task == "INTERMEDIATE_PRETRAINING": _SCREAMING_SNAKE_CASE : int = TapasModel(config=__SCREAMING_SNAKE_CASE ) else: raise ValueError(F"""Task {task} not supported.""" ) print(F"""Building PyTorch model from configuration: {config}""" ) # Load weights from tf checkpoint load_tf_weights_in_tapas(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Save pytorch-model (weights and configuration) print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) # Save tokenizer files print(F"""Save tokenizer files to {pytorch_dump_path}""" ) _SCREAMING_SNAKE_CASE : str = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + """vocab.txt""" , model_max_length=512 ) tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) print("""Used relative position embeddings:""" , model.config.reset_position_index_per_cell ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--task''', default='''SQA''', type=str, help='''Model task for which to convert a checkpoint. Defaults to SQA.''' ) parser.add_argument( '''--reset_position_index_per_cell''', default=False, action='''store_true''', help='''Whether to use relative position embeddings or not. Defaults to True.''', ) parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--tapas_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained TAPAS model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) lowerCAmelCase_ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
635
1
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
635
"""simple docstring""" from typing import Any import numpy as np def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> bool: return np.array_equal(__SCREAMING_SNAKE_CASE , matrix.conjugate().T ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )-> Any: _SCREAMING_SNAKE_CASE : Optional[int] = v.conjugate().T _SCREAMING_SNAKE_CASE : Optional[int] = v_star.dot(__SCREAMING_SNAKE_CASE ) assert isinstance(__SCREAMING_SNAKE_CASE , np.ndarray ) return (v_star_dot.dot(__SCREAMING_SNAKE_CASE )) / (v_star.dot(__SCREAMING_SNAKE_CASE )) def lowerCamelCase_()-> None: _SCREAMING_SNAKE_CASE : Optional[Any] = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) _SCREAMING_SNAKE_CASE : int = np.array([[1], [2], [3]] ) assert is_hermitian(__SCREAMING_SNAKE_CASE ), F"""{a} is not hermitian.""" print(rayleigh_quotient(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) _SCREAMING_SNAKE_CASE : int = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(__SCREAMING_SNAKE_CASE ), F"""{a} is not hermitian.""" assert rayleigh_quotient(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
635
1