code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. __A : int = 10 def A_ ( snake_case_ : int ,snake_case_ : int ,snake_case_ : list[int] ,snake_case_ : int ): '''simple docstring''' for i in range(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ): if array[i] == target: return i return -1 def A_ ( snake_case_ : list[int] ,snake_case_ : int ): '''simple docstring''' UpperCamelCase : Optional[int] = 0 UpperCamelCase : Tuple = len(SCREAMING_SNAKE_CASE_ ) while left <= right: if right - left < precision: return lin_search(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = (left + right) // 3 + 1 UpperCamelCase : Dict = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: UpperCamelCase : Union[str, Any] = one_third - 1 elif array[two_third] < target: UpperCamelCase : Any = two_third + 1 else: UpperCamelCase : Optional[Any] = one_third + 1 UpperCamelCase : Any = two_third - 1 else: return -1 def A_ ( snake_case_ : int ,snake_case_ : int ,snake_case_ : list[int] ,snake_case_ : int ): '''simple docstring''' if left < right: if right - left < precision: return lin_search(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = (left + right) // 3 + 1 UpperCamelCase : Optional[Any] = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(SCREAMING_SNAKE_CASE_ ,one_third - 1 ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) else: return rec_ternary_search(one_third + 1 ,two_third - 1 ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() __A : List[Any] = input('''Enter numbers separated by comma:\n''').strip() __A : int = [int(item.strip()) for item in user_input.split(''',''')] assert collection == sorted(collection), F"List must be ordered.\n{collection}." __A : Tuple = int(input('''Enter the number to be found in the list:\n''').strip()) __A : Any = ite_ternary_search(collection, target) __A : List[Any] = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(F'''Iterative search: {target} found at positions: {resulta}''') print(F'''Recursive search: {target} found at positions: {resulta}''') else: print('''Not found''')
363
"""simple docstring""" from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer __A : Any = logging.get_logger(__name__) __A : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A : Optional[Any] = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } __A : Any = {'''allegro/herbert-base-cased''': 514} __A : Optional[Any] = {} class lowerCamelCase ( _UpperCAmelCase ): lowercase : Dict = VOCAB_FILES_NAMES lowercase : Any = PRETRAINED_VOCAB_FILES_MAP lowercase : List[str] = PRETRAINED_INIT_CONFIGURATION lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Union[str, Any] = HerbertTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_="</s>" , **SCREAMING_SNAKE_CASE_ , ): super().__init__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = [self.cls_token_id] UpperCamelCase : str = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Tuple = [self.sep_token_id] UpperCamelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Optional[int] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
27
0
"""simple docstring""" import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy __A : List[str] = logging.getLogger(__name__) __A : Union[str, Any] = '''pytorch_model.bin''' @dataclasses.dataclass class lowerCamelCase : lowercase : str = dataclasses.field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models.'} ) lowercase : Optional[str] = dataclasses.field( default=a__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co.'} , ) @dataclasses.dataclass class lowerCamelCase : lowercase : str = dataclasses.field(metadata={'help': 'A csv or a json file containing the training data.'} ) lowercase : str = dataclasses.field(metadata={'help': 'A csv or a json file containing the data to predict on.'} ) lowercase : Optional[str] = dataclasses.field( default=a__ , metadata={'help': 'A csv or a json file containing the validation data.'} ) lowercase : Optional[str] = dataclasses.field( default=a__ , metadata={'help': 'The name of the task to train on.'} , ) lowercase : Optional[List[str]] = dataclasses.field( default=a__ , metadata={'help': 'The list of labels for the task.'} ) @dataclasses.dataclass class lowerCamelCase : lowercase : str = dataclasses.field( metadata={'help': 'The output directory where the model predictions and checkpoints will be written.'} ) lowercase : Optional[str] = dataclasses.field( default='accuracy' , metadata={'help': 'The evaluation metric used for the task.'} ) lowercase : Optional[str] = dataclasses.field( default='no' , metadata={ 'help': 'The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]' } , ) lowercase : Optional[int] = dataclasses.field( default=1_0 , metadata={'help': 'Number of evaluation calls with no improvement after which training will be stopped.'} , ) lowercase : Optional[float] = dataclasses.field( default=0.0 , metadata={ 'help': 'How much the specified evaluation metric must improve to satisfy early stopping conditions.' } , ) lowercase : Optional[bool] = dataclasses.field( default=a__ , metadata={'help': 'Whether to filter the pseudo-labeled data based on the confidence score.'} , ) lowercase : Optional[bool] = dataclasses.field( default=a__ , metadata={'help': 'Whether to filter the pseudo-labeled data based on the validation performance.'} , ) lowercase : Optional[bool] = dataclasses.field( default=a__ , metadata={'help': 'Whether to fine-tune on labeled data after pseudo training.'} , ) lowercase : Optional[float] = dataclasses.field( default=0.0 , metadata={'help': 'Confidence threshold for pseudo-labeled data filtering.'} , ) lowercase : Optional[int] = dataclasses.field( default=1_0_0 , metadata={'help': 'Number of evaluation calls with no improvement after which training will be stopped.'} , ) lowercase : Optional[int] = dataclasses.field( default=a__ , metadata={'help': 'Random seed for initialization.'} , ) def A_ ( snake_case_ : Optional[int] ,snake_case_ : Dict ,snake_case_ : Union[str, Any] ,snake_case_ : int ,snake_case_ : Tuple ,snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : int = datasets.concatenate_datasets([infer_input, infer_output] ,axis=1 ) if args.do_filter_by_confidence: UpperCamelCase : Optional[int] = dataset.filter(lambda snake_case_ : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 UpperCamelCase : List[str] = int(eval_result * len(snake_case__ ) ) print(snake_case__ ) UpperCamelCase : Union[str, Any] = dataset.sort("""probability""" ,reverse=snake_case__ ) UpperCamelCase : int = dataset.select(range(snake_case__ ) ) UpperCamelCase : Any = dataset.remove_columns(["""label""", """probability"""] ) UpperCamelCase : int = dataset.rename_column("""prediction""" ,"""label""" ) UpperCamelCase : Any = dataset.map(lambda snake_case_ : {"label": idalabel[example["label"]]} ) UpperCamelCase : List[Any] = dataset.shuffle(seed=args.seed ) UpperCamelCase : Dict = os.path.join(snake_case__ ,f'train_pseudo.{args.data_file_extension}' ) if args.data_file_extension == "csv": dataset.to_csv(snake_case__ ,index=snake_case__ ) else: dataset.to_json(snake_case__ ) def A_ ( snake_case_ : Optional[Any] ,snake_case_ : List[Any] ,snake_case_ : List[str] ,snake_case_ : Tuple ,**snake_case_ : Union[str, Any] ): '''simple docstring''' UpperCamelCase : List[str] = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,datefmt="""%m/%d/%Y %H:%M:%S""" ,level=logging.INFO ,) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() UpperCamelCase : List[str] = STModelArguments(model_name_or_path=snake_case__ ) UpperCamelCase : int = STDataArguments(train_file=snake_case__ ,infer_file=snake_case__ ) UpperCamelCase : Dict = STTrainingArguments(output_dir=snake_case__ ) UpperCamelCase : Optional[Any] = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(snake_case__ ).items(): setattr(snake_case__ ,snake_case__ ,snake_case__ ) for key, value in kwargs.items(): if hasattr(snake_case__ ,snake_case__ ): setattr(snake_case__ ,snake_case__ ,snake_case__ ) # Sanity checks UpperCamelCase : int = {} UpperCamelCase : Optional[int] = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None UpperCamelCase : int = args.train_file UpperCamelCase : Optional[Any] = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None UpperCamelCase : int = args.eval_file for key in data_files: UpperCamelCase : List[str] = data_files[key].split(""".""" )[-1] assert extension in ["csv", "json"], f'`{key}_file` should be a csv or a json file.' if args.data_file_extension is None: UpperCamelCase : List[Any] = extension else: assert extension == args.data_file_extension, f'`{key}_file` should be a {args.data_file_extension} file`.' assert ( args.eval_metric in datasets.list_metrics() ), f'{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.' # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info("""Creating the initial data directory for self-training...""" ) UpperCamelCase : Dict = f'{args.output_dir}/self-train_iter-{{}}'.format UpperCamelCase : Any = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir ,exist_ok=snake_case__ ) os.makedirs(snake_case__ ,exist_ok=snake_case__ ) accelerator.wait_for_everyone() UpperCamelCase : List[Any] = None UpperCamelCase : Any = None UpperCamelCase : Tuple = 0 UpperCamelCase : str = False # Show the progress bar UpperCamelCase : List[str] = tqdm(range(args.max_selftrain_iterations ) ,disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 ,int(args.max_selftrain_iterations ) ): UpperCamelCase : List[str] = data_dir_format(snake_case__ ) assert os.path.exists(snake_case__ ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 UpperCamelCase : List[Any] = os.path.join(snake_case__ ,"""stage-1""" ) UpperCamelCase : Optional[int] = { 'accelerator': accelerator, 'model_name_or_path': args.model_name_or_path, 'cache_dir': args.cache_dir, 'do_train': True, 'train_file': data_files['train'] if iteration == 0 else data_files['train_pseudo'], 'do_eval': True if args.eval_file is not None else False, 'eval_file': data_files['eval'], 'do_predict': True, 'infer_file': data_files['infer'], 'task_name': args.task_name, 'label_list': args.label_list, 'output_dir': current_output_dir, 'eval_metric': args.eval_metric, 'evaluation_strategy': args.evaluation_strategy, 'early_stopping_patience': args.early_stopping_patience, 'early_stopping_threshold': args.early_stopping_threshold, 'seed': args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(snake_case__ ,snake_case__ ): arguments_dict.update({key: value} ) UpperCamelCase : Any = os.path.join(snake_case__ ,"""best-checkpoint""" ,snake_case__ ) if os.path.exists(snake_case__ ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.""" ,snake_case__ ,snake_case__ ,) else: logger.info("""***** Running self-training: iteration: %d, stage: 1 *****""" ,snake_case__ ) finetune(**snake_case__ ) accelerator.wait_for_everyone() assert os.path.exists(snake_case__ ) logger.info("""Self-training job completed: iteration: %d, stage: 1.""" ,snake_case__ ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data UpperCamelCase : Tuple = os.path.join(snake_case__ ,"""best-checkpoint""" ) UpperCamelCase : str = os.path.join(snake_case__ ,"""stage-2""" ) # Update arguments_dict UpperCamelCase : str = model_path UpperCamelCase : Tuple = data_files['train'] UpperCamelCase : int = current_output_dir UpperCamelCase : Dict = os.path.join(snake_case__ ,"""best-checkpoint""" ,snake_case__ ) if os.path.exists(snake_case__ ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.""" ,snake_case__ ,snake_case__ ,) else: logger.info("""***** Running self-training: iteration: %d, stage: 2 *****""" ,snake_case__ ) finetune(**snake_case__ ) accelerator.wait_for_everyone() assert os.path.exists(snake_case__ ) logger.info("""Self-training job completed: iteration: %d, stage: 2.""" ,snake_case__ ) UpperCamelCase : int = iteration UpperCamelCase : Any = data_dir_format(iteration + 1 ) UpperCamelCase : Optional[int] = AutoConfig.from_pretrained(os.path.join(snake_case__ ,"""best-checkpoint""" ) ) UpperCamelCase : Union[str, Any] = config.idalabel UpperCamelCase : str = os.path.join(snake_case__ ,"""eval_results_best-checkpoint.json""" ) UpperCamelCase : List[Any] = os.path.join(snake_case__ ,"""test_results_best-checkpoint.json""" ) assert os.path.exists(snake_case__ ) with open(snake_case__ ,"""r""" ) as f: UpperCamelCase : Tuple = float(json.load(snake_case__ )[args.eval_metric] ) UpperCamelCase : Union[str, Any] = os.path.join(snake_case__ ,"""infer_output_best-checkpoint.csv""" ) assert os.path.exists(snake_case__ ) # Loading the dataset from local csv or json files. UpperCamelCase : Tuple = load_dataset(args.data_file_extension ,data_files={"""data""": data_files["""infer"""]} )['data'] UpperCamelCase : Optional[Any] = load_dataset("""csv""" ,data_files={"""data""": infer_output_file} )['data'] if accelerator.is_main_process: os.makedirs(snake_case__ ,exist_ok=snake_case__ ) shutil.copy(snake_case__ ,os.path.join(snake_case__ ,f'eval_results_iter-{iteration}.json' ) ) if os.path.exists(snake_case__ ): shutil.copy(snake_case__ ,os.path.join(snake_case__ ,f'test_results_iter-{iteration}.json' ) ) create_pseudo_labeled_data(snake_case__ ,snake_case__ ,snake_case__ ,snake_case__ ,snake_case__ ,snake_case__ ) accelerator.wait_for_everyone() UpperCamelCase : Tuple = os.path.join(snake_case__ ,f'train_pseudo.{args.data_file_extension}' ) if args.evaluation_strategy != IntervalStrategy.NO.value: UpperCamelCase : Optional[Any] = eval_result if best_iteration is None: UpperCamelCase : Dict = new_iteration UpperCamelCase : List[str] = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: UpperCamelCase : Tuple = new_iteration UpperCamelCase : List[Any] = new_eval_result UpperCamelCase : str = 0 else: if new_eval_result == best_eval_result: UpperCamelCase : Any = new_iteration UpperCamelCase : Tuple = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: UpperCamelCase : Tuple = True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info("""Best iteration: %d""" ,snake_case__ ) logger.info("""Best evaluation result: %s = %f""" ,args.eval_metric ,snake_case__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(snake_case__ ,f'eval_results_iter-{iteration}.json' ) ,os.path.join(snake_case__ ,"""eval_results_best-iteration.json""" ) ,) else: # Assume that the last iteration is the best logger.info("""Best iteration: %d""" ,args.max_selftrain_iterations - 1 ) logger.info("""Best evaluation result: %s = %f""" ,args.eval_metric ,snake_case__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(snake_case__ ,f'eval_results_iter-{args.max_selftrain_iterations - 1}.json' ) ,os.path.join(snake_case__ ,"""eval_results_best-iteration.json""" ) ,)
364
"""simple docstring""" import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=3.6 ): UpperCamelCase : Dict = tokenizer UpperCamelCase : Optional[Any] = tokenizer.bos_token_id UpperCamelCase : Any = dataset UpperCamelCase : List[str] = seq_length UpperCamelCase : Optional[Any] = seq_length * chars_per_token * num_of_sequences def __iter__( self ): UpperCamelCase : Dict = iter(self.dataset ) UpperCamelCase : Union[str, Any] = True while more_examples: UpperCamelCase , UpperCamelCase : Tuple = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(SCREAMING_SNAKE_CASE_ )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: UpperCamelCase : Dict = False break UpperCamelCase : str = tokenizer(SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )["""input_ids"""] UpperCamelCase : str = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , self.seq_length ): UpperCamelCase : List[str] = all_token_ids[i : i + self.seq_length] if len(SCREAMING_SNAKE_CASE_ ) == self.seq_length: yield torch.tensor(SCREAMING_SNAKE_CASE_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Dict = {"""streaming""": True} UpperCamelCase : Optional[int] = load_dataset(args.dataset_name ,split="""train""" ,**snake_case_ ) UpperCamelCase : Optional[int] = ConstantLengthDataset(snake_case_ ,snake_case_ ,seq_length=args.seq_length ) UpperCamelCase : List[Any] = DataLoader(snake_case_ ,batch_size=args.batch_size ) return eval_dataloader def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' model.eval() UpperCamelCase : Dict = [] for step, batch in enumerate(snake_case_ ): with torch.no_grad(): UpperCamelCase : List[Any] = model(snake_case_ ,labels=snake_case_ ) UpperCamelCase : Any = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(snake_case_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break UpperCamelCase : Dict = torch.mean(torch.cat(snake_case_ ) ) try: UpperCamelCase : Dict = torch.exp(snake_case_ ) except OverflowError: UpperCamelCase : Optional[int] = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator __A : List[Any] = Accelerator() # Parse configuration __A : str = HfArgumentParser(EvaluationArguments) __A : List[Any] = parser.parse_args() set_seed(args.seed) # Logging __A : Any = logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer __A : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) __A : List[Any] = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader __A : int = create_dataloader(args) # Prepare everything with our `accelerator`. __A , __A : Optional[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') __A , __A : Tuple = evaluate(args) logger.info(F'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
27
0
from __future__ import annotations __A : Optional[Any] = 1.6_0_2_1e-1_9 # units = C def A_ ( snake_case_ : float ,snake_case_ : float ,snake_case_ : float ,): '''simple docstring''' if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError("""You cannot supply more or less than 2 values""" ) elif conductivity < 0: raise ValueError("""Conductivity cannot be negative""" ) elif electron_conc < 0: raise ValueError("""Electron concentration cannot be negative""" ) elif mobility < 0: raise ValueError("""mobility cannot be negative""" ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
365
"""simple docstring""" import argparse import os import re __A : Any = '''src/transformers''' # Pattern that looks at the indentation in a line. __A : Tuple = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : List[Any] = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : List[Any] = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : Any = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : str ,snake_case_ : str="" ,snake_case_ : Any=None ,snake_case_ : Union[str, Any]=None ): '''simple docstring''' UpperCamelCase : List[Any] = 0 UpperCamelCase : Optional[int] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Tuple = ["""\n""".join(lines[:index] )] else: UpperCamelCase : Tuple = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Dict = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Optional[Any] = [lines[index + 1]] index += 1 else: UpperCamelCase : str = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : List[Any] ): '''simple docstring''' def _inner(snake_case_ : List[str] ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Tuple=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Optional[int] ): return x if key is None: UpperCamelCase : List[str] = noop # Constants are all uppercase, they go first. UpperCamelCase : List[str] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : Tuple = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : int = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Union[str, Any] = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : Any ): UpperCamelCase : Union[str, Any] = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : int = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : str = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : Optional[int] = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : int = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Tuple = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : List[Any] = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Union[str, Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : List[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : Optional[int] = keys[:-1] UpperCamelCase : Union[str, Any] = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : Any = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : int=True ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : List[str] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : int = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Dict = main_blocks[block_idx] UpperCamelCase : Dict = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : List[str] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : Optional[Any] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Optional[Any] = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Any = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : List[Any] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Optional[Any] = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Optional[Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Any = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : Union[str, Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[str] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: UpperCamelCase : Optional[int] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Optional[int] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : List[Any] = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : Union[str, Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
0
"""simple docstring""" from __future__ import annotations def A_ ( snake_case_ : Dict ,snake_case_ : Dict ,snake_case_ : Union[str, Any] ): '''simple docstring''' UpperCamelCase : Tuple = list(range(len(snake_case_ ) ) ) UpperCamelCase : Dict = [v / w for v, w in zip(snake_case_ ,snake_case_ )] index.sort(key=lambda snake_case_ : ratio[i] ,reverse=snake_case_ ) UpperCamelCase : float = 0 UpperCamelCase : list[float] = [0] * len(snake_case_ ) for i in index: if weight[i] <= capacity: UpperCamelCase : Dict = 1 max_value += value[i] capacity -= weight[i] else: UpperCamelCase : Optional[int] = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
366
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' if number < 0: raise ValueError("""number must not be negative""" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
27
0
"""simple docstring""" import contextlib import faulthandler import io import multiprocessing import os import platform import signal import tempfile def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Optional[int] ,snake_case_ : Tuple ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : Optional[int] = multiprocessing.Manager() UpperCamelCase : Optional[int] = manager.list() UpperCamelCase : Union[str, Any] = multiprocessing.Process(target=snake_case_ ,args=(check_program, result, timeout) ) p.start() p.join(timeout=timeout + 1 ) if p.is_alive(): p.kill() if not result: result.append("""timed out""" ) return { "task_id": task_id, "passed": result[0] == "passed", "result": result[0], "completion_id": completion_id, } def A_ ( snake_case_ : int ,snake_case_ : Optional[Any] ,snake_case_ : int ): '''simple docstring''' with create_tempdir(): # These system calls are needed when cleaning up tempdir. import os import shutil UpperCamelCase : Dict = shutil.rmtree UpperCamelCase : List[Any] = os.rmdir UpperCamelCase : List[str] = os.chdir # Disable functionalities that can make destructive changes to the test. reliability_guard() # Run program. try: UpperCamelCase : List[str] = {} with swallow_io(): with time_limit(snake_case_ ): exec(snake_case_ ,snake_case_ ) result.append("""passed""" ) except TimeoutException: result.append("""timed out""" ) except BaseException as e: result.append(f'failed: {e}' ) # Needed for cleaning up. UpperCamelCase : List[Any] = rmtree UpperCamelCase : Tuple = rmdir UpperCamelCase : List[Any] = chdir @contextlib.contextmanager def A_ ( snake_case_ : Dict ): '''simple docstring''' def signal_handler(snake_case_ : Optional[Any] ,snake_case_ : int ): raise TimeoutException("""Timed out!""" ) signal.setitimer(signal.ITIMER_REAL ,snake_case_ ) signal.signal(signal.SIGALRM ,snake_case_ ) try: yield finally: signal.setitimer(signal.ITIMER_REAL ,0 ) @contextlib.contextmanager def A_ ( ): '''simple docstring''' UpperCamelCase : Tuple = WriteOnlyStringIO() with contextlib.redirect_stdout(snake_case_ ): with contextlib.redirect_stderr(snake_case_ ): with redirect_stdin(snake_case_ ): yield @contextlib.contextmanager def A_ ( ): '''simple docstring''' with tempfile.TemporaryDirectory() as dirname: with chdir(snake_case_ ): yield dirname class lowerCamelCase ( UpperCamelCase__ ): pass class lowerCamelCase ( io.StringIO ): def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): raise OSError def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): raise OSError def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): raise OSError def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return False class lowerCamelCase ( contextlib._RedirectStream ): # type: ignore lowercase : Union[str, Any] = """stdin""" @contextlib.contextmanager def A_ ( snake_case_ : str ): '''simple docstring''' if root == ".": yield return UpperCamelCase : Any = os.getcwd() os.chdir(snake_case_ ) try: yield except BaseException as exc: raise exc finally: os.chdir(snake_case_ ) def A_ ( snake_case_ : Any=None ): '''simple docstring''' if maximum_memory_bytes is not None: import resource resource.setrlimit(resource.RLIMIT_AS ,(maximum_memory_bytes, maximum_memory_bytes) ) resource.setrlimit(resource.RLIMIT_DATA ,(maximum_memory_bytes, maximum_memory_bytes) ) if not platform.uname().system == "Darwin": resource.setrlimit(resource.RLIMIT_STACK ,(maximum_memory_bytes, maximum_memory_bytes) ) faulthandler.disable() import builtins UpperCamelCase : int = None UpperCamelCase : Any = None import os UpperCamelCase : Optional[Any] = """1""" UpperCamelCase : List[str] = None UpperCamelCase : Optional[Any] = None UpperCamelCase : Tuple = None UpperCamelCase : Dict = None UpperCamelCase : Any = None UpperCamelCase : List[str] = None UpperCamelCase : Dict = None UpperCamelCase : int = None UpperCamelCase : int = None UpperCamelCase : Optional[int] = None UpperCamelCase : Optional[Any] = None UpperCamelCase : Optional[Any] = None UpperCamelCase : Union[str, Any] = None UpperCamelCase : Tuple = None UpperCamelCase : Any = None UpperCamelCase : List[str] = None UpperCamelCase : int = None UpperCamelCase : Optional[Any] = None UpperCamelCase : int = None UpperCamelCase : Dict = None UpperCamelCase : Union[str, Any] = None UpperCamelCase : Any = None UpperCamelCase : Optional[int] = None UpperCamelCase : int = None UpperCamelCase : Any = None UpperCamelCase : Dict = None UpperCamelCase : Tuple = None import shutil UpperCamelCase : List[str] = None UpperCamelCase : List[str] = None UpperCamelCase : str = None import subprocess UpperCamelCase : Tuple = None # type: ignore UpperCamelCase : Optional[int] = None import sys UpperCamelCase : Union[str, Any] = None UpperCamelCase : int = None UpperCamelCase : Dict = None UpperCamelCase : Union[str, Any] = None UpperCamelCase : List[str] = None
367
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL __A : Optional[Any] = logging.get_logger(__name__) def A_ ( snake_case_ : np.ndarray ,snake_case_ : Union[int, Iterable[int]] ,snake_case_ : bool ,snake_case_ : int ): '''simple docstring''' def constraint_to_multiple_of(snake_case_ : Optional[Any] ,snake_case_ : Optional[int] ,snake_case_ : List[str]=0 ,snake_case_ : Optional[Any]=None ): UpperCamelCase : List[str] = round(val / multiple ) * multiple if max_val is not None and x > max_val: UpperCamelCase : Optional[Any] = math.floor(val / multiple ) * multiple if x < min_val: UpperCamelCase : Dict = math.ceil(val / multiple ) * multiple return x UpperCamelCase : Any = (output_size, output_size) if isinstance(snake_case_ ,snake_case_ ) else output_size UpperCamelCase , UpperCamelCase : int = get_image_size(snake_case_ ) UpperCamelCase , UpperCamelCase : Union[str, Any] = output_size # determine new height and width UpperCamelCase : List[str] = output_height / input_height UpperCamelCase : List[str] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width UpperCamelCase : int = scale_width else: # fit height UpperCamelCase : Optional[Any] = scale_height UpperCamelCase : int = constraint_to_multiple_of(scale_height * input_height ,multiple=snake_case_ ) UpperCamelCase : Union[str, Any] = constraint_to_multiple_of(scale_width * input_width ,multiple=snake_case_ ) return (new_height, new_width) class lowerCamelCase ( _UpperCAmelCase ): lowercase : str = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = size if size is not None else {"""height""": 384, """width""": 384} UpperCamelCase : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = do_resize UpperCamelCase : Union[str, Any] = size UpperCamelCase : Union[str, Any] = keep_aspect_ratio UpperCamelCase : Any = ensure_multiple_of UpperCamelCase : List[Any] = resample UpperCamelCase : str = do_rescale UpperCamelCase : Optional[Any] = rescale_factor UpperCamelCase : List[str] = do_normalize UpperCamelCase : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCamelCase : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) UpperCamelCase : Dict = get_resize_output_image_size( SCREAMING_SNAKE_CASE_ , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=SCREAMING_SNAKE_CASE_ , multiple=SCREAMING_SNAKE_CASE_ , ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize UpperCamelCase : List[Any] = size if size is not None else self.size UpperCamelCase : Dict = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio UpperCamelCase : Optional[int] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of UpperCamelCase : Tuple = resample if resample is not None else self.resample UpperCamelCase : str = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase : Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase : Any = image_mean if image_mean is not None else self.image_mean UpperCamelCase : List[Any] = image_std if image_std is not None else self.image_std UpperCamelCase : str = make_list_of_images(SCREAMING_SNAKE_CASE_ ) if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. UpperCamelCase : Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase : Union[str, Any] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase : int = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase : List[str] = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Union[str, Any] = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : str = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = target_sizes.numpy() UpperCamelCase : Dict = [] for idx in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase : List[Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : List[Any] = logits.argmax(dim=1 ) UpperCamelCase : Dict = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
27
0
"""simple docstring""" import argparse from pathlib import Path from transformers import AutoConfig, AutoTokenizer, RagConfig, RagSequenceForGeneration, RagTokenForGeneration def A_ ( snake_case_ : Optional[int] ,snake_case_ : str ,snake_case_ : Union[str, Any] ,snake_case_ : int ,snake_case_ : Any = None ,snake_case_ : Union[str, Any] = None ,snake_case_ : int = None ,): '''simple docstring''' if config_name_or_path is None: UpperCamelCase : str = 'facebook/rag-token-base' if model_type == 'rag_token' else 'facebook/rag-sequence-base' if generator_tokenizer_name_or_path is None: UpperCamelCase : int = generator_name_or_path if question_encoder_tokenizer_name_or_path is None: UpperCamelCase : int = question_encoder_name_or_path UpperCamelCase : Tuple = RagTokenForGeneration if model_type == 'rag_token' else RagSequenceForGeneration # Save model. UpperCamelCase : Dict = RagConfig.from_pretrained(lowerCAmelCase_ ) UpperCamelCase : int = AutoConfig.from_pretrained(lowerCAmelCase_ ) UpperCamelCase : Union[str, Any] = AutoConfig.from_pretrained(lowerCAmelCase_ ) UpperCamelCase : Union[str, Any] = gen_config UpperCamelCase : Tuple = question_encoder_config UpperCamelCase : List[str] = model_class.from_pretrained_question_encoder_generator( lowerCAmelCase_ ,lowerCAmelCase_ ,config=lowerCAmelCase_ ) rag_model.save_pretrained(lowerCAmelCase_ ) # Sanity check. model_class.from_pretrained(lowerCAmelCase_ ) # Save tokenizers. UpperCamelCase : Optional[Any] = AutoTokenizer.from_pretrained(lowerCAmelCase_ ) gen_tokenizer.save_pretrained(dest_dir / """generator_tokenizer/""" ) UpperCamelCase : Any = AutoTokenizer.from_pretrained(lowerCAmelCase_ ) question_encoder_tokenizer.save_pretrained(dest_dir / """question_encoder_tokenizer/""" ) if __name__ == "__main__": __A : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( '''--model_type''', choices=['''rag_sequence''', '''rag_token'''], required=True, type=str, help='''RAG model type: rag_sequence, rag_token''', ) parser.add_argument('''--dest''', type=str, required=True, help='''Path to the output checkpoint directory.''') parser.add_argument('''--generator_name_or_path''', type=str, required=True, help='''Generator model identifier''') parser.add_argument( '''--question_encoder_name_or_path''', type=str, required=True, help='''Question encoder model identifier''' ) parser.add_argument( '''--generator_tokenizer_name_or_path''', type=str, help='''Generator tokenizer identifier, if not specified, resolves to ``generator_name_or_path``''', ) parser.add_argument( '''--question_encoder_tokenizer_name_or_path''', type=str, help='''Question encoder tokenizer identifier, if not specified, resolves to ``question_encoder_name_or_path``''', ) parser.add_argument( '''--config_name_or_path''', type=str, help=( '''Identifier of the model config to use, if not provided, resolves to a base config for a given''' ''' ``model_type``''' ), ) __A : List[Any] = parser.parse_args() __A : Optional[int] = Path(args.dest) dest_dir.mkdir(exist_ok=True) consolidate( args.model_type, args.generator_name_or_path, args.question_encoder_name_or_path, dest_dir, args.config_name_or_path, args.generator_tokenizer_name_or_path, args.question_encoder_tokenizer_name_or_path, )
368
"""simple docstring""" from collections.abc import Callable def A_ ( snake_case_ : Callable[[float], float] ,snake_case_ : float ,snake_case_ : float ): '''simple docstring''' UpperCamelCase : float = a UpperCamelCase : float = b if function(snake_case_ ) == 0: # one of the a or b is a root for the function return a elif function(snake_case_ ) == 0: return b elif ( function(snake_case_ ) * function(snake_case_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("""could not find root in given interval.""" ) else: UpperCamelCase : float = start + (end - start) / 2.0 while abs(start - mid ) > 1_0**-7: # until precisely equals to 10^-7 if function(snake_case_ ) == 0: return mid elif function(snake_case_ ) * function(snake_case_ ) < 0: UpperCamelCase : Dict = mid else: UpperCamelCase : List[str] = mid UpperCamelCase : Tuple = start + (end - start) / 2.0 return mid def A_ ( snake_case_ : float ): '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
27
0
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=24 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=1000 , ): UpperCamelCase : Any = parent UpperCamelCase : Any = batch_size UpperCamelCase : List[Any] = seq_length UpperCamelCase : Optional[Any] = is_training UpperCamelCase : List[Any] = use_input_mask UpperCamelCase : List[Any] = use_token_type_ids UpperCamelCase : Union[str, Any] = use_labels UpperCamelCase : Optional[int] = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : Optional[Any] = num_hidden_layers UpperCamelCase : Optional[int] = num_attention_heads UpperCamelCase : List[Any] = intermediate_size UpperCamelCase : Dict = hidden_act UpperCamelCase : List[Any] = hidden_dropout_prob UpperCamelCase : Union[str, Any] = attention_probs_dropout_prob UpperCamelCase : str = max_position_embeddings UpperCamelCase : List[str] = type_vocab_size UpperCamelCase : Optional[Any] = type_sequence_label_size UpperCamelCase : str = initializer_range UpperCamelCase : int = num_labels UpperCamelCase : Union[str, Any] = scope UpperCamelCase : Any = range_bbox def a_ ( self ): UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Any = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # 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]: UpperCamelCase : List[str] = bbox[i, j, 3] UpperCamelCase : Union[str, Any] = bbox[i, j, 1] UpperCamelCase : int = t if bbox[i, j, 2] < bbox[i, j, 0]: UpperCamelCase : Dict = bbox[i, j, 2] UpperCamelCase : List[str] = bbox[i, j, 0] UpperCamelCase : Optional[int] = t UpperCamelCase : Optional[int] = None if self.use_input_mask: UpperCamelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCamelCase : List[Any] = None if self.use_token_type_ids: UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase : str = None UpperCamelCase : Union[str, Any] = None if self.use_labels: UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Dict = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def a_ ( self ): return LiltConfig( 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 , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = LiltModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() UpperCamelCase : Dict = model(UpperCamelCase__ , bbox=UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) UpperCamelCase : List[Any] = model(UpperCamelCase__ , bbox=UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) UpperCamelCase : Tuple = model(UpperCamelCase__ , bbox=UpperCamelCase__ ) 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 a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : List[Any] = self.num_labels UpperCamelCase : Tuple = LiltForTokenClassification(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() UpperCamelCase : str = model( UpperCamelCase__ , bbox=UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = LiltForQuestionAnswering(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() UpperCamelCase : List[str] = model( UpperCamelCase__ , bbox=UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , start_positions=UpperCamelCase__ , end_positions=UpperCamelCase__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self ): UpperCamelCase : str = self.prepare_config_and_inputs() ( UpperCamelCase ) : Optional[int] = config_and_inputs UpperCamelCase : List[Any] = { "input_ids": input_ids, "bbox": bbox, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class lowerCamelCase ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): lowercase : Any = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) lowercase : Union[str, Any] = ( { """feature-extraction""": LiltModel, """question-answering""": LiltForQuestionAnswering, """text-classification""": LiltForSequenceClassification, """token-classification""": LiltForTokenClassification, """zero-shot""": LiltForSequenceClassification, } if is_torch_available() else {} ) lowercase : Any = False lowercase : Tuple = False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return True def a_ ( self ): UpperCamelCase : Dict = LiltModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase : List[Any] = type self.model_tester.create_and_check_model(*UpperCamelCase__ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ ) @slow def a_ ( self ): for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Any = LiltModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) @require_torch @slow class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): UpperCamelCase : Union[str, Any] = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""" ).to(UpperCamelCase__ ) UpperCamelCase : Optional[int] = torch.tensor([[1, 2]] , device=UpperCamelCase__ ) UpperCamelCase : int = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=UpperCamelCase__ ) # forward pass with torch.no_grad(): UpperCamelCase : str = model(input_ids=UpperCamelCase__ , bbox=UpperCamelCase__ ) UpperCamelCase : Optional[int] = torch.Size([1, 2, 768] ) UpperCamelCase : Optional[int] = torch.tensor( [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]] , device=UpperCamelCase__ , ) self.assertTrue(outputs.last_hidden_state.shape , UpperCamelCase__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , UpperCamelCase__ , atol=1e-3 ) )
369
"""simple docstring""" import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def a_ ( self ): UpperCamelCase : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) UpperCamelCase : int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) UpperCamelCase : Dict = """xvjiarui/stable-diffusion-2-inpainting""" UpperCamelCase , UpperCamelCase : List[str] = FlaxStableDiffusionInpaintPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = """Face of a yellow cat, high resolution, sitting on a park bench""" UpperCamelCase : List[str] = jax.random.PRNGKey(0 ) UpperCamelCase : Tuple = 50 UpperCamelCase : Dict = jax.device_count() UpperCamelCase : Optional[int] = num_samples * [prompt] UpperCamelCase : int = num_samples * [init_image] UpperCamelCase : List[Any] = num_samples * [mask_image] UpperCamelCase , UpperCamelCase , UpperCamelCase : Optional[Any] = pipeline.prepare_inputs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # shard inputs and rng UpperCamelCase : Optional[int] = replicate(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = jax.random.split(SCREAMING_SNAKE_CASE_ , jax.device_count() ) UpperCamelCase : str = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = pipeline( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , jit=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = output.images.reshape(SCREAMING_SNAKE_CASE_ , 512 , 512 , 3 ) UpperCamelCase : List[Any] = images[0, 253:256, 253:256, -1] UpperCamelCase : List[Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) UpperCamelCase : Dict = jnp.array( [0.3611307, 0.37649736, 0.3757408, 0.38213953, 0.39295167, 0.3841631, 0.41554978, 0.4137475, 0.4217084] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
27
0
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Tuple = logging.get_logger(__name__) __A : List[Any] = { '''snap-research/efficientformer-l1-300''': ( '''https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json''' ), } class lowerCamelCase ( lowerCamelCase_ ): lowercase : int = '''efficientformer''' def __init__( self , SCREAMING_SNAKE_CASE_ = [3, 2, 6, 4] , SCREAMING_SNAKE_CASE_ = [48, 96, 224, 448] , SCREAMING_SNAKE_CASE_ = [True, True, True, True] , SCREAMING_SNAKE_CASE_ = 448 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 4 , SCREAMING_SNAKE_CASE_ = 7 , SCREAMING_SNAKE_CASE_ = 5 , SCREAMING_SNAKE_CASE_ = 8 , SCREAMING_SNAKE_CASE_ = 4 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 3 , SCREAMING_SNAKE_CASE_ = 3 , SCREAMING_SNAKE_CASE_ = 3 , SCREAMING_SNAKE_CASE_ = 2 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1e-5 , SCREAMING_SNAKE_CASE_ = "gelu" , SCREAMING_SNAKE_CASE_ = 0.02 , SCREAMING_SNAKE_CASE_ = 1e-12 , SCREAMING_SNAKE_CASE_ = 224 , SCREAMING_SNAKE_CASE_ = 1e-05 , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**__snake_case ) UpperCamelCase : List[Any] = hidden_act UpperCamelCase : Optional[int] = hidden_dropout_prob UpperCamelCase : List[str] = hidden_sizes UpperCamelCase : Optional[Any] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : List[str] = initializer_range UpperCamelCase : Dict = layer_norm_eps UpperCamelCase : Optional[int] = patch_size UpperCamelCase : Tuple = num_channels UpperCamelCase : Any = depths UpperCamelCase : Tuple = mlp_expansion_ratio UpperCamelCase : int = downsamples UpperCamelCase : Union[str, Any] = dim UpperCamelCase : Dict = key_dim UpperCamelCase : int = attention_ratio UpperCamelCase : Optional[Any] = resolution UpperCamelCase : Optional[int] = pool_size UpperCamelCase : Optional[Any] = downsample_patch_size UpperCamelCase : Optional[int] = downsample_stride UpperCamelCase : List[str] = downsample_pad UpperCamelCase : Optional[int] = drop_path_rate UpperCamelCase : List[Any] = num_metaad_blocks UpperCamelCase : Optional[int] = distillation UpperCamelCase : int = use_layer_scale UpperCamelCase : str = layer_scale_init_value UpperCamelCase : str = image_size UpperCamelCase : Dict = batch_norm_eps
370
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def A_ ( snake_case_ : int ): # picklable for multiprocessing '''simple docstring''' return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def A_ ( ): '''simple docstring''' with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" UpperCamelCase : Optional[Any] = [1, 2, 3] with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=2 ) with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" ,[2, -1] ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : List[Any] = [1, 2] UpperCamelCase : List[Any] = {"""a""": 1, """b""": 2} UpperCamelCase : List[str] = {"""a""": [1, 2], """b""": [3, 4]} UpperCamelCase : Tuple = {"""a""": {"""1""": 1}, """b""": 2} UpperCamelCase : Any = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} UpperCamelCase : Optional[int] = [2, 3] UpperCamelCase : List[str] = {"""a""": 2, """b""": 3} UpperCamelCase : Any = {"""a""": [2, 3], """b""": [4, 5]} UpperCamelCase : Tuple = {"""a""": {"""1""": 2}, """b""": 3} UpperCamelCase : List[str] = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa
27
0
"""simple docstring""" import socket def A_ ( ): '''simple docstring''' UpperCamelCase : List[str] = socket.socket(socket.AF_INET ,socket.SOCK_STREAM ) UpperCamelCase : str = socket.gethostname() UpperCamelCase : List[str] = 1_2_3_1_2 sock.connect((host, port) ) sock.send(b"""Hello server!""" ) with open("""Received_file""" ,"""wb""" ) as out_file: print("""File opened""" ) print("""Receiving data...""" ) while True: UpperCamelCase : Union[str, Any] = sock.recv(1_0_2_4 ) if not data: break out_file.write(snake_case_ ) print("""Successfully received the file""" ) sock.close() print("""Connection closed""" ) if __name__ == "__main__": main()
371
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="last" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=0 , ): UpperCamelCase : Union[str, Any] = parent UpperCamelCase : str = batch_size UpperCamelCase : int = seq_length UpperCamelCase : Optional[Any] = is_training UpperCamelCase : Any = use_input_lengths UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : List[Any] = use_labels UpperCamelCase : Union[str, Any] = gelu_activation UpperCamelCase : Dict = sinusoidal_embeddings UpperCamelCase : Optional[int] = causal UpperCamelCase : List[Any] = asm UpperCamelCase : int = n_langs UpperCamelCase : Optional[Any] = vocab_size UpperCamelCase : str = n_special UpperCamelCase : Dict = hidden_size UpperCamelCase : Union[str, Any] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : int = max_position_embeddings UpperCamelCase : Any = type_sequence_label_size UpperCamelCase : str = initializer_range UpperCamelCase : str = num_labels UpperCamelCase : Union[str, Any] = num_choices UpperCamelCase : List[str] = summary_type UpperCamelCase : int = use_proj UpperCamelCase : List[str] = scope UpperCamelCase : Dict = bos_token_id def a_ ( self ): UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Union[str, Any] = None if self.use_input_lengths: UpperCamelCase : str = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase : Tuple = None if self.use_token_type_ids: UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase : int = None UpperCamelCase : Dict = None UpperCamelCase : str = None if self.use_labels: UpperCamelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Dict = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : List[str] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def a_ ( self ): return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[int] = XLMModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , lengths=SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[Any] = XLMWithLMHeadModel(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : List[str] = XLMForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : int = XLMForQuestionAnswering(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , p_mask=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , ) ((UpperCamelCase) , ) : Union[str, Any] = result_with_labels.to_tuple() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , ) : Tuple = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = XLMForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : int = self.num_labels UpperCamelCase : int = XLMForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : List[Any] = self.num_choices UpperCamelCase : Tuple = XLMForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Optional[Any] = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : int = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : List[Any] = config_and_inputs UpperCamelCase : Dict = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) lowercase : List[Any] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable lowercase : Optional[Any] = ( { 'feature-extraction': XLMModel, 'fill-mask': XLMWithLMHeadModel, 'question-answering': XLMForQuestionAnsweringSimple, 'text-classification': XLMForSequenceClassification, 'text-generation': XLMWithLMHeadModel, 'token-classification': XLMForTokenClassification, 'zero-shot': XLMForSequenceClassification, } if is_torch_available() else {} ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": UpperCamelCase : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) return inputs_dict def a_ ( self ): UpperCamelCase : List[Any] = XLMModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , emb_dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_attentions in attentions] , [True] * len(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : int = min_length + idx + 1 UpperCamelCase : Tuple = min_length + idx + 1 UpperCamelCase : Any = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_hidden_states in hidden_states] , [True] * len(SCREAMING_SNAKE_CASE_ ) , ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : List[str] = min_length + idx + 1 UpperCamelCase : Optional[Any] = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) , ) pass @slow def a_ ( self ): for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : str = XLMModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Dict = XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.tensor([[14, 447]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # the president UpperCamelCase : List[Any] = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference UpperCamelCase : Optional[int] = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , SCREAMING_SNAKE_CASE_ )
27
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Optional[Any] = logging.get_logger(__name__) __A : Tuple = { '''andreasmadsen/efficient_mlm_m0.40''': ( '''https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json''' ), } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'roberta-prelayernorm' def __init__( self , SCREAMING_SNAKE_CASE_=5_0265 , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-12 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_="absolute" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = vocab_size UpperCamelCase : List[str] = hidden_size UpperCamelCase : List[Any] = num_hidden_layers UpperCamelCase : List[str] = num_attention_heads UpperCamelCase : Tuple = hidden_act UpperCamelCase : List[str] = intermediate_size UpperCamelCase : List[Any] = hidden_dropout_prob UpperCamelCase : Dict = attention_probs_dropout_prob UpperCamelCase : Union[str, Any] = max_position_embeddings UpperCamelCase : Optional[Any] = type_vocab_size UpperCamelCase : Dict = initializer_range UpperCamelCase : List[str] = layer_norm_eps UpperCamelCase : Any = position_embedding_type UpperCamelCase : List[str] = use_cache UpperCamelCase : Union[str, Any] = classifier_dropout class lowerCamelCase ( _UpperCAmelCase ): @property def a_ ( self ): if self.task == "multiple-choice": UpperCamelCase : Optional[int] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: UpperCamelCase : Any = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
350
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A : int = { '''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = [ '''GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTBigCodeForSequenceClassification''', '''GPTBigCodeForTokenClassification''', '''GPTBigCodeForCausalLM''', '''GPTBigCodeModel''', '''GPTBigCodePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A : str = logging.get_logger(__name__) __A : Union[str, Any] = { '''MIT/ast-finetuned-audioset-10-10-0.4593''': ( '''https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json''' ), } class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[str] = 'audio-spectrogram-transformer' def __init__( self , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=128 , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = hidden_size UpperCamelCase : Tuple = num_hidden_layers UpperCamelCase : List[Any] = num_attention_heads UpperCamelCase : Any = intermediate_size UpperCamelCase : Optional[int] = hidden_act UpperCamelCase : List[str] = hidden_dropout_prob UpperCamelCase : Optional[int] = attention_probs_dropout_prob UpperCamelCase : Union[str, Any] = initializer_range UpperCamelCase : Tuple = layer_norm_eps UpperCamelCase : Tuple = patch_size UpperCamelCase : Tuple = qkv_bias UpperCamelCase : Optional[Any] = frequency_stride UpperCamelCase : Dict = time_stride UpperCamelCase : Any = max_length UpperCamelCase : Any = num_mel_bins
351
"""simple docstring""" import torch from transformers import AutoModel class lowerCamelCase ( torch.nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_="sayef/fsner-bert-base-uncased" ): super(SCREAMING_SNAKE_CASE_ , self ).__init__() UpperCamelCase : int = AutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.nn.CosineSimilarity(3 , 1e-08 ) UpperCamelCase : Any = torch.nn.Softmax(dim=1 ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return self.bert(**SCREAMING_SNAKE_CASE_ ).last_hidden_state def a_ ( self , SCREAMING_SNAKE_CASE_ ): return token_embeddings.sum(2 , keepdim=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1 ): return self.softmax(T * self.cos(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = W_supports["""sizes"""].tolist() UpperCamelCase : List[str] = W_supports["""start_token_id"""].item() UpperCamelCase : List[Any] = W_supports["""end_token_id"""].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCamelCase : List[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = None UpperCamelCase : Optional[Any] = None UpperCamelCase : Tuple = W_supports["""input_ids"""] == start_token_id UpperCamelCase : Optional[Any] = W_supports["""input_ids"""] == end_token_id for i, size in enumerate(SCREAMING_SNAKE_CASE_ ): if i == 0: UpperCamelCase : int = 0 else: UpperCamelCase : Optional[int] = support_sizes[i - 1] UpperCamelCase : Tuple = S[s : s + size][start_token_masks[s : s + size]] UpperCamelCase : int = S[s : s + size][end_token_masks[s : s + size]] UpperCamelCase : Dict = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCamelCase : Tuple = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCamelCase : List[str] = torch.vstack((p_starts, p_start) ) UpperCamelCase : Optional[Any] = torch.vstack((p_ends, p_end) ) else: UpperCamelCase : Optional[int] = p_start UpperCamelCase : Tuple = p_end return p_starts, p_ends
27
0
"""simple docstring""" import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[Any] = (DDIMParallelScheduler,) lowercase : Any = (('eta', 0.0), ('num_inference_steps', 5_0)) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = { """num_train_timesteps""": 1000, """beta_start""": 0.0001, """beta_end""": 0.02, """beta_schedule""": """linear""", """clip_sample""": True, } config.update(**SCREAMING_SNAKE_CASE_ ) return config def a_ ( self , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.scheduler_classes[0] UpperCamelCase : Tuple = self.get_scheduler_config(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = 10, 0.0 UpperCamelCase : Optional[Any] = self.dummy_model() UpperCamelCase : Dict = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) for t in scheduler.timesteps: UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample return sample def a_ ( self ): for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for steps_offset in [0, 1]: self.check_over_configs(steps_offset=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.scheduler_classes[0] UpperCamelCase : Tuple = self.get_scheduler_config(steps_offset=1 ) UpperCamelCase : str = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def a_ ( self ): for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE_ , beta_end=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE_ , prediction_type=SCREAMING_SNAKE_CASE_ , sample_max_value=SCREAMING_SNAKE_CASE_ , ) def a_ ( self ): for t in [1, 10, 49]: self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = self.scheduler_classes[0] UpperCamelCase : Optional[int] = self.get_scheduler_config() UpperCamelCase : Any = scheduler_class(**SCREAMING_SNAKE_CASE_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.14771 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.32460 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.00979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1e-5 def a_ ( self ): UpperCamelCase : Dict = self.scheduler_classes[0] UpperCamelCase : str = self.get_scheduler_config() UpperCamelCase : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = 10, 0.0 scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.dummy_model() UpperCamelCase : Optional[int] = self.dummy_sample_deter UpperCamelCase : Optional[Any] = self.dummy_sample_deter + 0.1 UpperCamelCase : Any = self.dummy_sample_deter - 0.1 UpperCamelCase : Any = samplea.shape[0] UpperCamelCase : Any = torch.stack([samplea, samplea, samplea] , dim=0 ) UpperCamelCase : int = torch.arange(SCREAMING_SNAKE_CASE_ )[0:3, None].repeat(1 , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) UpperCamelCase : Optional[int] = scheduler.batch_step_no_noise(SCREAMING_SNAKE_CASE_ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 1147.7904 ) < 1e-2 assert abs(result_mean.item() - 0.4982 ) < 1e-3 def a_ ( self ): UpperCamelCase : Tuple = self.full_loop() UpperCamelCase : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : List[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 172.0067 ) < 1e-2 assert abs(result_mean.item() - 0.223967 ) < 1e-3 def a_ ( self ): UpperCamelCase : Tuple = self.full_loop(prediction_type="""v_prediction""" ) UpperCamelCase : Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Dict = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 52.5302 ) < 1e-2 assert abs(result_mean.item() - 0.0684 ) < 1e-3 def a_ ( self ): # We specify different beta, so that the first alpha is 0.99 UpperCamelCase : Union[str, Any] = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE_ , beta_start=0.01 ) UpperCamelCase : Any = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : str = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 149.8295 ) < 1e-2 assert abs(result_mean.item() - 0.1951 ) < 1e-3 def a_ ( self ): # We specify different beta, so that the first alpha is 0.99 UpperCamelCase : Optional[Any] = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE_ , beta_start=0.01 ) UpperCamelCase : Union[str, Any] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : str = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 149.0784 ) < 1e-2 assert abs(result_mean.item() - 0.1941 ) < 1e-3
352
"""simple docstring""" from typing import Any class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = data UpperCamelCase : Optional[Any] = None def __repr__( self ): return f'Node({self.data})' class lowerCamelCase : def __init__( self ): UpperCamelCase : Dict = None def __iter__( self ): UpperCamelCase : int = self.head while node: yield node.data UpperCamelCase : Union[str, Any] = node.next def __len__( self ): return sum(1 for _ in self ) def __repr__( self ): return "->".join([str(SCREAMING_SNAKE_CASE_ ) for item in self] ) def __getitem__( self , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) UpperCamelCase : List[Any] = self.head for _ in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = current.next UpperCamelCase : Optional[Any] = data def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(len(self ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(0 , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index <= len(self ): raise IndexError("""list index out of range""" ) UpperCamelCase : Optional[Any] = Node(SCREAMING_SNAKE_CASE_ ) if self.head is None: UpperCamelCase : Dict = new_node elif index == 0: UpperCamelCase : Any = self.head # link new_node to head UpperCamelCase : Any = new_node else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : str = temp.next UpperCamelCase : Any = temp.next UpperCamelCase : Optional[Any] = new_node def a_ ( self ): # print every node data print(self ) def a_ ( self ): return self.delete_nth(0 ) def a_ ( self ): # delete from tail return self.delete_nth(len(self ) - 1 ) def a_ ( self , SCREAMING_SNAKE_CASE_ = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("""List index out of range.""" ) UpperCamelCase : Union[str, Any] = self.head # default first node if index == 0: UpperCamelCase : Optional[Any] = self.head.next else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : int = temp.next UpperCamelCase : Optional[Any] = temp.next UpperCamelCase : Dict = temp.next.next return delete_node.data def a_ ( self ): return self.head is None def a_ ( self ): UpperCamelCase : Optional[Any] = None UpperCamelCase : Union[str, Any] = self.head while current: # Store the current node's next node. UpperCamelCase : Optional[int] = current.next # Make the current node's next point backwards UpperCamelCase : Optional[Any] = prev # Make the previous node be the current node UpperCamelCase : int = current # Make the current node the next node (to progress iteration) UpperCamelCase : Optional[int] = next_node # Return prev in order to put the head at the end UpperCamelCase : Optional[int] = prev def A_ ( ): '''simple docstring''' UpperCamelCase : int = LinkedList() assert linked_list.is_empty() is True assert str(snake_case_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(1_0 ): assert len(snake_case_ ) == i linked_list.insert_nth(snake_case_ ,i + 1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_1 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(1_1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(0 ,1_2 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 1_0 assert linked_list.delete_tail() == 1_1 assert len(snake_case_ ) == 9 assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_0 ) ) assert all(linked_list[i] == i + 1 for i in range(0 ,9 ) ) is True for i in range(0 ,9 ): UpperCamelCase : Optional[Any] = -i assert all(linked_list[i] == -i for i in range(0 ,9 ) ) is True linked_list.reverse() assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(-8 ,1 ) ) def A_ ( ): '''simple docstring''' UpperCamelCase : int = [ -9, 1_0_0, Node(7_7_3_4_5_1_1_2 ), """dlrow olleH""", 7, 5_5_5_5, 0, -192.55555, """Hello, world!""", 77.9, Node(1_0 ), None, None, 12.20, ] UpperCamelCase : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(snake_case_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(snake_case_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head UpperCamelCase : Dict = linked_list.delete_head() assert result == -9 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail UpperCamelCase : int = linked_list.delete_tail() assert result == 12.2 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list UpperCamelCase : Optional[Any] = linked_list.delete_nth(1_0 ) assert result is None assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("""Hello again, world!""" ) ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(snake_case_ ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(snake_case_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def A_ ( ): '''simple docstring''' from doctest import testmod testmod() UpperCamelCase : List[Any] = LinkedList() linked_list.insert_head(input("""Inserting 1st at head """ ).strip() ) linked_list.insert_head(input("""Inserting 2nd at head """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() linked_list.insert_tail(input("""\nInserting 1st at tail """ ).strip() ) linked_list.insert_tail(input("""Inserting 2nd at tail """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() print("""\nDelete head""" ) linked_list.delete_head() print("""Delete tail""" ) linked_list.delete_tail() print("""\nPrint list:""" ) linked_list.print_list() print("""\nReverse linked list""" ) linked_list.reverse() print("""\nPrint list:""" ) linked_list.print_list() print("""\nString representation of linked list:""" ) print(snake_case_ ) print("""\nReading/changing Node data using indexing:""" ) print(f'Element at Position 1: {linked_list[1]}' ) UpperCamelCase : List[Any] = input("""Enter New Value: """ ).strip() print("""New list:""" ) print(snake_case_ ) print(f'length of linked_list is : {len(snake_case_ )}' ) if __name__ == "__main__": main()
27
0
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): UpperCamelCase : List[Any] = inspect.getfile(accelerate.test_utils ) UpperCamelCase : Union[str, Any] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """external_deps""", """test_metrics.py"""] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 UpperCamelCase : Optional[Any] = test_metrics @require_cpu def a_ ( self ): debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def a_ ( self ): debug_launcher(self.test_metrics.main ) @require_single_gpu def a_ ( self ): self.test_metrics.main() @require_multi_gpu def a_ ( self ): print(f'Found {torch.cuda.device_count()} devices.' ) UpperCamelCase : Union[str, Any] = ["""torchrun""", f'--nproc_per_node={torch.cuda.device_count()}', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(SCREAMING_SNAKE_CASE_ , env=os.environ.copy() )
353
"""simple docstring""" import argparse import os import re __A : Dict = '''src/diffusers''' # Pattern that looks at the indentation in a line. __A : Union[str, Any] = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : Tuple = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Tuple = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Union[str, Any] = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Dict="" ,snake_case_ : Dict=None ,snake_case_ : Any=None ): '''simple docstring''' UpperCamelCase : Optional[int] = 0 UpperCamelCase : List[Any] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Optional[Any] = ["""\n""".join(lines[:index] )] else: UpperCamelCase : int = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Any = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Any = [lines[index + 1]] index += 1 else: UpperCamelCase : List[str] = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' def _inner(snake_case_ : Tuple ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[int]=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Dict ): return x if key is None: UpperCamelCase : int = noop # Constants are all uppercase, they go first. UpperCamelCase : List[Any] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : str = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : List[str] = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Tuple = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : int ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : List[Any] ): UpperCamelCase : Any = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : Union[str, Any] = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[str] = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : str = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : str = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Dict = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : int = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[Any] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : Optional[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[Any] = keys[:-1] UpperCamelCase : int = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Tuple ,snake_case_ : str=True ): '''simple docstring''' with open(snake_case_ ,"""r""" ) as f: UpperCamelCase : int = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : Dict = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Optional[Any] = main_blocks[block_idx] UpperCamelCase : Optional[int] = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : Union[str, Any] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : List[str] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Dict = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Union[str, Any] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : Optional[int] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Union[str, Any] = _re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Union[str, Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Optional[Any] = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : List[Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[Any] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: UpperCamelCase : str = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Any = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Union[str, Any] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : Any = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Any = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : str = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
0
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() __A : Any = logging.get_logger(__name__) __A : Any = [ ('''bert.bert''', '''visual_bert'''), ('''bert.cls''', '''cls'''), ('''bert.classifier''', '''cls'''), ('''token_type_embeddings_visual''', '''visual_token_type_embeddings'''), ('''position_embeddings_visual''', '''visual_position_embeddings'''), ('''projection''', '''visual_projection'''), ] __A : Optional[int] = [ '''nlvr2_coco_pre_trained.th''', '''nlvr2_fine_tuned.th''', '''nlvr2_pre_trained.th''', '''vcr_coco_pre_train.th''', '''vcr_fine_tune.th''', '''vcr_pre_train.th''', '''vqa_coco_pre_trained.th''', '''vqa_fine_tuned.th''', '''vqa_pre_trained.th''', ] def A_ ( snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : Optional[int] = torch.load(snake_case_ ,map_location="""cpu""" ) return sd def A_ ( snake_case_ : Optional[int] ,snake_case_ : Union[str, Any] ,snake_case_ : int=rename_keys_prefix ): '''simple docstring''' UpperCamelCase : List[Any] = OrderedDict() UpperCamelCase : Union[str, Any] = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue UpperCamelCase : List[str] = key for name_pair in rename_keys_prefix: UpperCamelCase : Dict = new_key.replace(name_pair[0] ,name_pair[1] ) UpperCamelCase : Optional[int] = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately UpperCamelCase : List[Any] = new_d["""cls.predictions.bias"""] return new_d @torch.no_grad() def A_ ( snake_case_ : Dict ,snake_case_ : int ): '''simple docstring''' assert ( checkpoint_path.split("""/""" )[-1] in ACCEPTABLE_CHECKPOINTS ), f'The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.' # Get Config if "pre" in checkpoint_path: UpperCamelCase : str = """pretraining""" if "vcr" in checkpoint_path: UpperCamelCase : Dict = {"""visual_embedding_dim""": 5_1_2} elif "vqa_advanced" in checkpoint_path: UpperCamelCase : Tuple = {"""visual_embedding_dim""": 2_0_4_8} elif "vqa" in checkpoint_path: UpperCamelCase : Dict = {"""visual_embedding_dim""": 2_0_4_8} elif "nlvr" in checkpoint_path: UpperCamelCase : Union[str, Any] = {"""visual_embedding_dim""": 1_0_2_4} else: raise NotImplementedError(f'No implementation found for `{checkpoint_path}`.' ) else: if "vcr" in checkpoint_path: UpperCamelCase : Any = {"""visual_embedding_dim""": 5_1_2} UpperCamelCase : Union[str, Any] = """multichoice""" elif "vqa_advanced" in checkpoint_path: UpperCamelCase : Tuple = {"""visual_embedding_dim""": 2_0_4_8} UpperCamelCase : int = """vqa_advanced""" elif "vqa" in checkpoint_path: UpperCamelCase : str = {"""visual_embedding_dim""": 2_0_4_8, """num_labels""": 3_1_2_9} UpperCamelCase : Optional[Any] = """vqa""" elif "nlvr" in checkpoint_path: UpperCamelCase : Tuple = { """visual_embedding_dim""": 1_0_2_4, """num_labels""": 2, } UpperCamelCase : List[str] = """nlvr""" UpperCamelCase : Any = VisualBertConfig(**snake_case_ ) # Load State Dict UpperCamelCase : Dict = load_state_dict(snake_case_ ) UpperCamelCase : Dict = get_new_dict(snake_case_ ,snake_case_ ) if model_type == "pretraining": UpperCamelCase : str = VisualBertForPreTraining(snake_case_ ) elif model_type == "vqa": UpperCamelCase : int = VisualBertForQuestionAnswering(snake_case_ ) elif model_type == "nlvr": UpperCamelCase : List[str] = VisualBertForVisualReasoning(snake_case_ ) elif model_type == "multichoice": UpperCamelCase : List[str] = VisualBertForMultipleChoice(snake_case_ ) model.load_state_dict(snake_case_ ) # Save Checkpoints Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) model.save_pretrained(snake_case_ ) if __name__ == "__main__": __A : int = argparse.ArgumentParser() # Required parameters parser.add_argument('''orig_checkpoint_path''', type=str, help='''A path to .th on local filesystem.''') parser.add_argument('''pytorch_dump_folder_path''', type=str, help='''Path to the output PyTorch model.''') __A : Dict = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
354
"""simple docstring""" def A_ ( snake_case_ : list[int] ): '''simple docstring''' if not numbers: return 0 if not isinstance(snake_case_ ,(list, tuple) ) or not all( isinstance(snake_case_ ,snake_case_ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) UpperCamelCase : int = numbers[0] for i in range(1 ,len(snake_case_ ) ): # update the maximum and minimum subarray products UpperCamelCase : List[str] = numbers[i] if number < 0: UpperCamelCase , UpperCamelCase : Optional[int] = min_till_now, max_till_now UpperCamelCase : Dict = max(snake_case_ ,max_till_now * number ) UpperCamelCase : Union[str, Any] = min(snake_case_ ,min_till_now * number ) # update the maximum product found till now UpperCamelCase : Union[str, Any] = max(snake_case_ ,snake_case_ ) return max_prod
27
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging __A : Any = logging.get_logger(__name__) __A : int = '''▁''' __A : str = {'''vocab_file''': '''sentencepiece.bpe.model'''} __A : Dict = { '''vocab_file''': { '''facebook/mbart-large-en-ro''': ( '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model''' ), '''facebook/mbart-large-cc25''': ( '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model''' ), } } __A : Dict = { '''facebook/mbart-large-en-ro''': 1024, '''facebook/mbart-large-cc25''': 1024, } # fmt: off __A : Optional[int] = ['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN'''] class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[Any] = VOCAB_FILES_NAMES lowercase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : List[str] = PRETRAINED_VOCAB_FILES_MAP lowercase : Any = ['input_ids', 'attention_mask'] lowercase : List[int] = [] lowercase : List[int] = [] def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ): # Mask token behave like a normal word, i.e. include the space before it UpperCamelCase : int = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token UpperCamelCase : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , src_lang=SCREAMING_SNAKE_CASE_ , tgt_lang=SCREAMING_SNAKE_CASE_ , additional_special_tokens=SCREAMING_SNAKE_CASE_ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : str = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token UpperCamelCase : int = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab UpperCamelCase : str = 1 UpperCamelCase : List[str] = len(self.sp_model ) UpperCamelCase : List[str] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(SCREAMING_SNAKE_CASE_ ) } UpperCamelCase : Dict = {v: k for k, v in self.lang_code_to_id.items()} UpperCamelCase : Union[str, Any] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) UpperCamelCase : int = {v: k for k, v in self.fairseq_tokens_to_ids.items()} UpperCamelCase : Tuple = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) UpperCamelCase : List[Any] = src_lang if src_lang is not None else """en_XX""" UpperCamelCase : str = self.lang_code_to_id[self._src_lang] UpperCamelCase : Union[str, Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ): UpperCamelCase : str = self.__dict__.copy() UpperCamelCase : List[Any] = None UpperCamelCase : int = self.sp_model.serialized_model_proto() return state def __setstate__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): UpperCamelCase : Any = {} UpperCamelCase : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def a_ ( self ): return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def a_ ( self ): return self._src_lang @src_lang.setter def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = [1] * len(self.prefix_tokens ) UpperCamelCase : Union[str, Any] = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(SCREAMING_SNAKE_CASE_ )) + suffix_ones return prefix_ones + ([0] * len(SCREAMING_SNAKE_CASE_ )) + ([0] * len(SCREAMING_SNAKE_CASE_ )) + suffix_ones def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Optional[int] = [self.sep_token_id] UpperCamelCase : Tuple = [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 a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) UpperCamelCase : Any = src_lang UpperCamelCase : Union[str, Any] = self(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tgt_lang_id return inputs def a_ ( self ): UpperCamelCase : Union[str, Any] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.sp_model.encode(SCREAMING_SNAKE_CASE_ , out_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] UpperCamelCase : List[str] = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE_ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def a_ ( self , SCREAMING_SNAKE_CASE_ ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = """""".join(SCREAMING_SNAKE_CASE_ ).replace(SCREAMING_SNAKE_CASE_ , """ """ ).strip() return out_string def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return UpperCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE_ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE_ , """wb""" ) as fi: UpperCamelCase : Dict = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE_ ) return (out_vocab_file,) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = "en_XX" , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "ro_RO" , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : str = src_lang UpperCamelCase : Optional[int] = tgt_lang return super().prepare_seqaseq_batch(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self ): return self.set_src_lang_special_tokens(self.src_lang ) def a_ ( self ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.lang_code_to_id[src_lang] UpperCamelCase : Dict = [] UpperCamelCase : List[Any] = [self.eos_token_id, self.cur_lang_code] def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.lang_code_to_id[lang] UpperCamelCase : Union[str, Any] = [] UpperCamelCase : List[str] = [self.eos_token_id, self.cur_lang_code]
355
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Any = AudioLDMPipeline lowercase : Union[str, Any] = TEXT_TO_AUDIO_PARAMS lowercase : List[str] = TEXT_TO_AUDIO_BATCH_PARAMS lowercase : Tuple = frozenset( [ 'num_inference_steps', 'num_waveforms_per_prompt', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=(32, 64) , class_embed_type="""simple_projection""" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[Any] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , ) torch.manual_seed(0 ) UpperCamelCase : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCamelCase : int = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) UpperCamelCase : Optional[int] = ClapTextModelWithProjection(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta""" , model_max_length=77 ) UpperCamelCase : Tuple = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """vocoder""": vocoder, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Any = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """prompt""": """A hammer hitting a wooden surface""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, } return inputs def a_ ( self ): UpperCamelCase : str = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Any = self.get_dummy_components() UpperCamelCase : int = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Tuple = audio[:10] UpperCamelCase : Dict = np.array( [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[str] = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Optional[int] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) UpperCamelCase : Tuple = prompt_embeds # forward UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : List[str] = self.get_dummy_components() UpperCamelCase : List[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * ["""this is a negative prompt"""] UpperCamelCase : List[Any] = negative_prompt UpperCamelCase : str = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : str = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] UpperCamelCase : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[Any] = [] for p in [prompt, negative_prompt]: UpperCamelCase : int = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Union[str, Any] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = text_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) embeds.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Tuple = embeds # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Optional[int] = self.get_dummy_components() UpperCamelCase : List[str] = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = """egg cracking""" UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Union[str, Any] = audio[:10] UpperCamelCase : Dict = np.array( [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Union[str, Any] = self.get_dummy_components() UpperCamelCase : Tuple = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = """A hammer hitting a wooden surface""" # test num_waveforms_per_prompt=1 (default) UpperCamelCase : List[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts UpperCamelCase : Dict = 2 UpperCamelCase : List[str] = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt UpperCamelCase : List[str] = 2 UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts UpperCamelCase : Any = 2 UpperCamelCase : str = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = audioldm_pipe.vocoder.config.sampling_rate UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe(audio_length_in_s=0.016 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.016 UpperCamelCase : Optional[Any] = audioldm_pipe(audio_length_in_s=0.032 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.032 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Optional[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = ["""hey"""] UpperCamelCase : Dict = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : str = output.audios.shape assert audio_shape == (1, 256) UpperCamelCase : Optional[Any] = audioldm_pipe.vocoder.config config.model_in_dim *= 2 UpperCamelCase : str = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : List[str] = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def a_ ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self._test_inference_batch_single_identical(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def a_ ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @slow class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="cpu" , SCREAMING_SNAKE_CASE_=torch.floataa , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : str = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = np.random.RandomState(SCREAMING_SNAKE_CASE_ ).standard_normal((1, 8, 128, 16) ) UpperCamelCase : int = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = { """prompt""": """A hammer hitting a wooden surface""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 2.5, } return inputs def a_ ( self ): UpperCamelCase : Optional[int] = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = 25 UpperCamelCase : Optional[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[7_7230:7_7240] UpperCamelCase : Optional[Any] = np.array( [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] ) UpperCamelCase : Any = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def a_ ( self ): UpperCamelCase : Any = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : Any = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) UpperCamelCase : str = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[2_7780:2_7790] UpperCamelCase : Tuple = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] ) UpperCamelCase : Tuple = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
27
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Any = KandinskyImgaImgPipeline lowercase : Tuple = ['prompt', 'image_embeds', 'negative_image_embeds', 'image'] lowercase : str = [ 'prompt', 'negative_prompt', 'image_embeds', 'negative_image_embeds', 'image', ] lowercase : Union[str, Any] = [ 'generator', 'height', 'width', 'strength', 'guidance_scale', 'negative_prompt', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] lowercase : Dict = False @property def a_ ( self ): return 32 @property def a_ ( self ): return 32 @property def a_ ( self ): return self.time_input_dim @property def a_ ( self ): return self.time_input_dim * 4 @property def a_ ( self ): return 100 @property def a_ ( self ): UpperCamelCase : List[str] = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" ) return tokenizer @property def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Optional[Any] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) UpperCamelCase : int = MultilingualCLIP(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = text_encoder.eval() return text_encoder @property def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : List[Any] = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """text_image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """text_image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } UpperCamelCase : Optional[int] = UNetaDConditionModel(**SCREAMING_SNAKE_CASE_ ) return model @property def a_ ( self ): return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Any = VQModel(**self.dummy_movq_kwargs ) return model def a_ ( self ): UpperCamelCase : Optional[int] = self.dummy_text_encoder UpperCamelCase : Optional[int] = self.dummy_tokenizer UpperCamelCase : Union[str, Any] = self.dummy_unet UpperCamelCase : Optional[Any] = self.dummy_movq UpperCamelCase : List[str] = { """num_train_timesteps""": 1000, """beta_schedule""": """linear""", """beta_start""": 0.00085, """beta_end""": 0.012, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } UpperCamelCase : Optional[Any] = DDIMScheduler(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = { """text_encoder""": text_encoder, """tokenizer""": tokenizer, """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : Any = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(SCREAMING_SNAKE_CASE_ ) # create init_image UpperCamelCase : Dict = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCamelCase : Optional[int] = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE_ ) ).convert("""RGB""" ).resize((256, 256) ) if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : int = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : int = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """prompt""": """horse""", """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def a_ ( self ): UpperCamelCase : Tuple = """cpu""" UpperCamelCase : Dict = self.get_dummy_components() UpperCamelCase : Optional[int] = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Optional[Any] = output.images UpperCamelCase : int = pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) , return_dict=SCREAMING_SNAKE_CASE_ , )[0] UpperCamelCase : Tuple = image[0, -3:, -3:, -1] UpperCamelCase : str = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCamelCase : Dict = np.array( [0.61474943, 0.6073539, 0.43308544, 0.5928269, 0.47493595, 0.46755973, 0.4613838, 0.45368797, 0.50119233] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f' expected_slice {expected_slice}, but got {image_slice.flatten()}' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}' @slow @require_torch_gpu class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self ): UpperCamelCase : List[str] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_img2img_frog.npy""" ) UpperCamelCase : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) UpperCamelCase : List[Any] = """A red cartoon frog, 4k""" UpperCamelCase : List[Any] = KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = KandinskyImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1""" , torch_dtype=torch.floataa ) UpperCamelCase : List[str] = pipeline.to(SCREAMING_SNAKE_CASE_ ) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCamelCase : Optional[int] = pipe_prior( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() UpperCamelCase : Optional[int] = pipeline( SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , image_embeds=SCREAMING_SNAKE_CASE_ , negative_image_embeds=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type="""np""" , ) UpperCamelCase : str = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
356
"""simple docstring""" import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def A_ ( snake_case_ : Dataset ,snake_case_ : Dict[str, str] ): '''simple docstring''' UpperCamelCase : List[str] = args.log_outputs UpperCamelCase : Tuple = """_""".join(args.dataset.split("""/""" ) + [args.config, args.split] ) # load metric UpperCamelCase : List[Any] = load_metric("""wer""" ) UpperCamelCase : Any = load_metric("""cer""" ) # compute metrics UpperCamelCase : str = wer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) UpperCamelCase : Dict = cer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) # print & log results UpperCamelCase : Optional[int] = f'WER: {wer_result}\nCER: {cer_result}' print(snake_case_ ) with open(f'{dataset_id}_eval_results.txt' ,"""w""" ) as f: f.write(snake_case_ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: UpperCamelCase : Optional[Any] = f'log_{dataset_id}_predictions.txt' UpperCamelCase : str = f'log_{dataset_id}_targets.txt' with open(snake_case_ ,"""w""" ) as p, open(snake_case_ ,"""w""" ) as t: # mapping function to write output def write_to_file(snake_case_ : Union[str, Any] ,snake_case_ : Tuple ): p.write(f'{i}' + """\n""" ) p.write(batch["""prediction"""] + """\n""" ) t.write(f'{i}' + """\n""" ) t.write(batch["""target"""] + """\n""" ) result.map(snake_case_ ,with_indices=snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Dict = """[,?.!\-\;\:\"“%‘”�—’…–]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training UpperCamelCase : str = re.sub(snake_case_ ,"""""" ,text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! UpperCamelCase : List[str] = ["""\n\n""", """\n""", """ """, """ """] for t in token_sequences_to_ignore: UpperCamelCase : Tuple = """ """.join(text.split(snake_case_ ) ) return text def A_ ( snake_case_ : str ): '''simple docstring''' # load dataset UpperCamelCase : Union[str, Any] = load_dataset(args.dataset ,args.config ,split=args.split ,use_auth_token=snake_case_ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor UpperCamelCase : List[Any] = AutoFeatureExtractor.from_pretrained(args.model_id ) UpperCamelCase : Dict = feature_extractor.sampling_rate # resample audio UpperCamelCase : Optional[Any] = dataset.cast_column("""audio""" ,Audio(sampling_rate=snake_case_ ) ) # load eval pipeline if args.device is None: UpperCamelCase : int = 0 if torch.cuda.is_available() else -1 UpperCamelCase : Union[str, Any] = pipeline("""automatic-speech-recognition""" ,model=args.model_id ,device=args.device ) # map function to decode audio def map_to_pred(snake_case_ : Union[str, Any] ): UpperCamelCase : List[Any] = asr( batch["""audio"""]["""array"""] ,chunk_length_s=args.chunk_length_s ,stride_length_s=args.stride_length_s ) UpperCamelCase : Union[str, Any] = prediction["""text"""] UpperCamelCase : Optional[Any] = normalize_text(batch["""sentence"""] ) return batch # run inference on all examples UpperCamelCase : Any = dataset.map(snake_case_ ,remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(snake_case_ ,snake_case_ ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() parser.add_argument( '''--model_id''', type=str, required=True, help='''Model identifier. Should be loadable with 🤗 Transformers''' ) parser.add_argument( '''--dataset''', type=str, required=True, help='''Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets''', ) parser.add_argument( '''--config''', type=str, required=True, help='''Config of the dataset. *E.g.* `\'en\'` for Common Voice''' ) parser.add_argument('''--split''', type=str, required=True, help='''Split of the dataset. *E.g.* `\'test\'`''') parser.add_argument( '''--chunk_length_s''', type=float, default=None, help='''Chunk length in seconds. Defaults to 5 seconds.''' ) parser.add_argument( '''--stride_length_s''', type=float, default=None, help='''Stride of the audio chunks. Defaults to 1 second.''' ) parser.add_argument( '''--log_outputs''', action='''store_true''', help='''If defined, write outputs to log file for analysis.''' ) parser.add_argument( '''--device''', type=int, default=None, help='''The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.''', ) __A : Optional[Any] = parser.parse_args() main(args)
27
0
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer __A : int = ['''gpt2'''] __A : List[str] = '''gpt2''' if is_tf_available(): class lowerCamelCase ( tf.Module ): def __init__( self , SCREAMING_SNAKE_CASE_ ): super().__init__() UpperCamelCase : List[str] = tokenizer UpperCamelCase : Union[str, Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = TFGPTaLMHeadModel.from_config(SCREAMING_SNAKE_CASE_ ) @tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name="""text""" ),) ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = self.tokenizer(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = tokenized["""input_ids"""].to_tensor() UpperCamelCase : List[str] = tf.cast(input_ids_dense > 0 , tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) UpperCamelCase : int = self.model(input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""logits"""] return outputs @require_tf @require_keras_nlp class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().setUp() UpperCamelCase : Union[str, Any] = [GPTaTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) for checkpoint in (TOKENIZER_CHECKPOINTS)] UpperCamelCase : Optional[Any] = [TFGPTaTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) UpperCamelCase : Dict = [ """This is a straightforward English test sentence.""", """This one has some weird characters\rto\nsee\r\nif those\u00E9break things.""", """Now we're going to add some Chinese: 一 二 三 一二三""", """And some much more rare Chinese: 齉 堃 齉堃""", """Je vais aussi écrire en français pour tester les accents""", """Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ""", ] UpperCamelCase : Dict = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def a_ ( self ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in self.test_sentences: UpperCamelCase : Dict = tokenizer([test_inputs] , return_tensors="""tf""" ) UpperCamelCase : Any = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors UpperCamelCase : List[Any] = python_outputs[key].numpy() UpperCamelCase : Dict = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(SCREAMING_SNAKE_CASE_ , tf.intaa ) == tf_outputs_values ) ) @slow def a_ ( self ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase : str = tf.function(SCREAMING_SNAKE_CASE_ ) for test_inputs in self.test_sentences: UpperCamelCase : int = tf.constant(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = compiled_tokenizer(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = tf_tokenizer(SCREAMING_SNAKE_CASE_ ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def a_ ( self ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase : Optional[Any] = ModelToSave(tokenizer=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = tf.convert_to_tensor([self.test_sentences[0]] ) UpperCamelCase : Union[str, Any] = model.serving(SCREAMING_SNAKE_CASE_ ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: UpperCamelCase : Any = Path(SCREAMING_SNAKE_CASE_ ) / """saved.model""" tf.saved_model.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , signatures={"""serving_default""": model.serving} ) UpperCamelCase : Optional[Any] = tf.saved_model.load(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = loaded_model.signatures["""serving_default"""](SCREAMING_SNAKE_CASE_ )["""output_0"""] # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertTrue(tf.reduce_all(out == loaded_output ) ) @slow def a_ ( self ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase : int = tf.convert_to_tensor([self.test_sentences[0]] ) UpperCamelCase : int = tf_tokenizer(SCREAMING_SNAKE_CASE_ ) # Build model with some sample inputs UpperCamelCase : Tuple = tf_tokenizer.get_config() UpperCamelCase : Tuple = TFGPTaTokenizer.from_config(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model_from_config(SCREAMING_SNAKE_CASE_ ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def a_ ( self ): for tf_tokenizer in self.tf_tokenizers: # for the test to run UpperCamelCase : int = 12_3123 for max_length in [3, 5, 1024]: UpperCamelCase : Optional[int] = tf.convert_to_tensor([self.test_sentences[0]] ) UpperCamelCase : str = tf_tokenizer(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = out["""input_ids"""].numpy().shape[1] assert out_length == max_length
357
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'EncodecFeatureExtractor' lowercase : List[Any] = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.feature_extractor UpperCamelCase : Any = False def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True ): return self.tokenizer.get_decoder_prompt_ids(task=SCREAMING_SNAKE_CASE_ , language=SCREAMING_SNAKE_CASE_ , no_timestamps=SCREAMING_SNAKE_CASE_ ) def __call__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = kwargs.pop("""sampling_rate""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Any = args[0] UpperCamelCase : str = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if text is not None: UpperCamelCase : Optional[int] = self.tokenizer(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is not None: UpperCamelCase : str = self.feature_extractor(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is None: return inputs elif text is None: return audio_inputs else: UpperCamelCase : int = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: UpperCamelCase : Optional[Any] = audio_inputs["""padding_mask"""] return inputs def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = kwargs.pop("""padding_mask""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Optional[int] = args[0] UpperCamelCase : Any = args[1:] if audio_values is not None: return self._decode_audio(SCREAMING_SNAKE_CASE_ , padding_mask=SCREAMING_SNAKE_CASE_ ) else: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = to_numpy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase : int = audio_values.shape if padding_mask is None: return list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = to_numpy(SCREAMING_SNAKE_CASE_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) UpperCamelCase : List[str] = seq_len - padding_mask.shape[-1] UpperCamelCase : Optional[int] = 1 - self.feature_extractor.padding_value UpperCamelCase : Any = np.pad(SCREAMING_SNAKE_CASE_ , ((0, 0), (0, difference)) , """constant""" , constant_values=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audio_values.tolist() for i in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] UpperCamelCase : Optional[Any] = sliced_audio.reshape(SCREAMING_SNAKE_CASE_ , -1 ) return audio_values
27
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor __A : List[Any] = logging.get_logger(__name__) class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): warnings.warn( """The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use DeiTImageProcessor instead.""" , SCREAMING_SNAKE_CASE_ , ) super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
358
"""simple docstring""" import requests from bsa import BeautifulSoup def A_ ( snake_case_ : str = "https://www.worldometers.info/coronavirus" ): '''simple docstring''' UpperCamelCase : Any = BeautifulSoup(requests.get(snake_case_ ).text ,"""html.parser""" ) UpperCamelCase : Optional[int] = soup.findAll("""h1""" ) UpperCamelCase : List[Any] = soup.findAll("""div""" ,{"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" ,{"""class""": """panel-title"""} ) values += soup.findAll("""div""" ,{"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(snake_case_ ,snake_case_ )} if __name__ == "__main__": print('''\033[1m''' + '''COVID-19 Status of the World''' + '''\033[0m\n''') for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
27
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : Optional[int] = { '''google/mobilenet_v2_1.4_224''': '''https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json''', '''google/mobilenet_v2_1.0_224''': '''https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json''', '''google/mobilenet_v2_0.75_160''': '''https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json''', '''google/mobilenet_v2_0.35_96''': '''https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json''', # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2 } class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[Any] = 'mobilenet_v2' def __init__( self , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=224 , SCREAMING_SNAKE_CASE_=1.0 , SCREAMING_SNAKE_CASE_=8 , SCREAMING_SNAKE_CASE_=8 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="relu6" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0.8 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.001 , SCREAMING_SNAKE_CASE_=255 , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) if depth_multiplier <= 0: raise ValueError("""depth_multiplier must be greater than zero.""" ) UpperCamelCase : Dict = num_channels UpperCamelCase : str = image_size UpperCamelCase : List[str] = depth_multiplier UpperCamelCase : Dict = depth_divisible_by UpperCamelCase : int = min_depth UpperCamelCase : Optional[int] = expand_ratio UpperCamelCase : Any = output_stride UpperCamelCase : Tuple = first_layer_is_expansion UpperCamelCase : Optional[Any] = finegrained_output UpperCamelCase : Dict = hidden_act UpperCamelCase : Dict = tf_padding UpperCamelCase : List[Any] = classifier_dropout_prob UpperCamelCase : str = initializer_range UpperCamelCase : Optional[int] = layer_norm_eps UpperCamelCase : Tuple = semantic_loss_ignore_index class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[Any] = version.parse('1.11' ) @property def a_ ( self ): return OrderedDict([("""pixel_values""", {0: """batch"""})] ) @property def a_ ( self ): if self.task == "image-classification": return OrderedDict([("""logits""", {0: """batch"""})] ) else: return OrderedDict([("""last_hidden_state""", {0: """batch"""}), ("""pooler_output""", {0: """batch"""})] ) @property def a_ ( self ): return 1e-4
359
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=1 , ): UpperCamelCase : Tuple = parent UpperCamelCase : Optional[int] = batch_size UpperCamelCase : Optional[Any] = seq_length UpperCamelCase : int = is_training UpperCamelCase : Union[str, Any] = use_input_mask UpperCamelCase : Union[str, Any] = use_token_type_ids UpperCamelCase : Dict = use_labels UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : Tuple = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : int = intermediate_size UpperCamelCase : str = hidden_act UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Optional[Any] = type_vocab_size UpperCamelCase : int = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : Dict = num_labels UpperCamelCase : Tuple = num_choices UpperCamelCase : Optional[int] = scope UpperCamelCase : List[Any] = q_groups UpperCamelCase : Tuple = k_groups UpperCamelCase : Any = v_groups UpperCamelCase : List[str] = post_attention_groups UpperCamelCase : Tuple = intermediate_groups UpperCamelCase : int = output_groups def a_ ( self ): UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Tuple = None if self.use_input_mask: UpperCamelCase : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Optional[int] = None UpperCamelCase : List[Any] = None UpperCamelCase : Dict = None if self.use_labels: UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self ): return SqueezeBertConfig( embedding_size=self.hidden_size , vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = SqueezeBertModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = SqueezeBertForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = SqueezeBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : str = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.num_labels UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.num_labels UpperCamelCase : str = SqueezeBertForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = self.num_choices UpperCamelCase : Tuple = SqueezeBertForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = config_and_inputs UpperCamelCase : Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) lowercase : Dict = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) lowercase : Dict = False lowercase : str = True lowercase : str = False def a_ ( self ): UpperCamelCase : Any = SqueezeBertModelTester(self ) UpperCamelCase : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Optional[Any] = SqueezeBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_sentencepiece @require_tokenizers @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification.from_pretrained("""squeezebert/squeezebert-mnli""" ) UpperCamelCase : Dict = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]] ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[Any] = torch.Size((1, 3) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
27
0
"""simple docstring""" import fcntl import os import socket import torch import torch.distributed as dist def A_ ( *snake_case_ : Optional[int] ): '''simple docstring''' with open(snake_case_ ,"""r""" ) as fh: fcntl.flock(snake_case_ ,fcntl.LOCK_EX ) try: print(*snake_case_ ) finally: fcntl.flock(snake_case_ ,fcntl.LOCK_UN ) __A : Optional[Any] = int(os.environ['''LOCAL_RANK''']) torch.cuda.set_device(local_rank) __A : Optional[int] = torch.device('''cuda''', local_rank) __A : List[str] = socket.gethostname() __A : Optional[Any] = F'''[{hostname}-{local_rank}]''' try: # test distributed dist.init_process_group('''nccl''') dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank __A : List[Any] = dist.get_rank() __A : List[str] = dist.get_world_size() printflock(F'''{gpu} is OK (global rank: {rank}/{world_size})''') dist.barrier() if rank == 0: printflock(F'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''') except Exception: printflock(F'''{gpu} is broken''') raise
360
"""simple docstring""" from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class lowerCamelCase ( nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 88 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "geglu" , SCREAMING_SNAKE_CASE_ = None , ): super().__init__() UpperCamelCase : int = nn.ModuleList( [ TransformeraDModel( num_attention_heads=SCREAMING_SNAKE_CASE_ , attention_head_dim=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , dropout=SCREAMING_SNAKE_CASE_ , norm_num_groups=SCREAMING_SNAKE_CASE_ , cross_attention_dim=SCREAMING_SNAKE_CASE_ , attention_bias=SCREAMING_SNAKE_CASE_ , sample_size=SCREAMING_SNAKE_CASE_ , num_vector_embeds=SCREAMING_SNAKE_CASE_ , activation_fn=SCREAMING_SNAKE_CASE_ , num_embeds_ada_norm=SCREAMING_SNAKE_CASE_ , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference UpperCamelCase : Optional[Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` UpperCamelCase : List[Any] = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` UpperCamelCase : int = [1, 0] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = True , ): UpperCamelCase : Dict = hidden_states UpperCamelCase : Optional[Any] = [] UpperCamelCase : List[Any] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens UpperCamelCase : Optional[int] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] UpperCamelCase : str = self.transformer_index_for_condition[i] UpperCamelCase : Any = self.transformers[transformer_index]( SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , timestep=SCREAMING_SNAKE_CASE_ , cross_attention_kwargs=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] UpperCamelCase : Any = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) UpperCamelCase : List[str] = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=SCREAMING_SNAKE_CASE_ )
27
0
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def A_ ( snake_case_ : Optional[int] ,snake_case_ : Optional[int] ,snake_case_ : List[Any]=[] ): '''simple docstring''' UpperCamelCase : List[str] = size[0] - overlap_pixels * 2 UpperCamelCase : Optional[Any] = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels UpperCamelCase : List[Any] = np.ones((size_y, size_x) ,dtype=np.uinta ) * 2_5_5 UpperCamelCase : Any = np.pad(snake_case_ ,mode="""linear_ramp""" ,pad_width=snake_case_ ,end_values=0 ) if "l" in remove_borders: UpperCamelCase : int = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: UpperCamelCase : List[str] = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: UpperCamelCase : Union[str, Any] = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: UpperCamelCase : List[str] = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def A_ ( snake_case_ : Tuple ,snake_case_ : Any ,snake_case_ : Optional[Any] ): '''simple docstring''' return max(snake_case_ ,min(snake_case_ ,snake_case_ ) ) def A_ ( snake_case_ : [int] ,snake_case_ : [int] ,snake_case_ : [int] ): '''simple docstring''' return ( clamp(rect[0] ,min[0] ,max[0] ), clamp(rect[1] ,min[1] ,max[1] ), clamp(rect[2] ,min[0] ,max[0] ), clamp(rect[3] ,min[1] ,max[1] ), ) def A_ ( snake_case_ : [int] ,snake_case_ : int ,snake_case_ : [int] ): '''simple docstring''' UpperCamelCase : int = list(snake_case_ ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap UpperCamelCase : List[str] = clamp_rect(snake_case_ ,[0, 0] ,[image_size[0], image_size[1]] ) return rect def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[int] ,snake_case_ : Tuple ,snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : int = Image.new("""RGB""" ,(tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) ,Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) ,(0, 0) ,) result.paste(snake_case_ ,(original_slice, 0) ) return result def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : List[str] = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) UpperCamelCase : int = tile.crop(snake_case_ ) return tile def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Any ): '''simple docstring''' UpperCamelCase : Union[str, Any] = n % d return n - divisor class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 350 , ): super().__init__( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , low_res_scheduler=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , max_noise_level=SCREAMING_SNAKE_CASE_ , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): torch.manual_seed(0 ) UpperCamelCase : Dict = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) UpperCamelCase : Optional[int] = add_overlap_rect(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , image.size ) UpperCamelCase : Optional[int] = image.crop(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] UpperCamelCase : int = translated_slice_x - (original_image_slice / 2) UpperCamelCase : List[str] = max(0 , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = squeeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = to_input.size UpperCamelCase : List[Any] = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) UpperCamelCase : Optional[int] = super(SCREAMING_SNAKE_CASE_ , self ).__call__(image=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).images[0] UpperCamelCase : Optional[Any] = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) UpperCamelCase : int = unsqueeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) UpperCamelCase : List[Any] = [] if x == 0: remove_borders.append("""l""" ) elif crop_rect[2] == image.size[0]: remove_borders.append("""r""" ) if y == 0: remove_borders.append("""t""" ) elif crop_rect[3] == image.size[1]: remove_borders.append("""b""" ) UpperCamelCase : Optional[Any] = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=SCREAMING_SNAKE_CASE_ ) , mode="""L""" , ) final_image.paste( SCREAMING_SNAKE_CASE_ , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 75 , SCREAMING_SNAKE_CASE_ = 9.0 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 128 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 32 , ): UpperCamelCase : int = Image.new("""RGB""" , (image.size[0] * 4, image.size[1] * 4) ) UpperCamelCase : Optional[Any] = math.ceil(image.size[0] / tile_size ) UpperCamelCase : Optional[int] = math.ceil(image.size[1] / tile_size ) UpperCamelCase : Tuple = tcx * tcy UpperCamelCase : Optional[Any] = 0 for y in range(SCREAMING_SNAKE_CASE_ ): for x in range(SCREAMING_SNAKE_CASE_ ): self._process_tile( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prompt=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , noise_level=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , ) current_count += 1 if callback is not None: callback({"""progress""": current_count / total_tile_count, """image""": final_image} ) return final_image def A_ ( ): '''simple docstring''' UpperCamelCase : int = """stabilityai/stable-diffusion-x4-upscaler""" UpperCamelCase : Union[str, Any] = StableDiffusionTiledUpscalePipeline.from_pretrained(snake_case_ ,revision="""fp16""" ,torch_dtype=torch.floataa ) UpperCamelCase : Any = pipe.to("""cuda""" ) UpperCamelCase : List[Any] = Image.open("""../../docs/source/imgs/diffusers_library.jpg""" ) def callback(snake_case_ : Any ): print(f'progress: {obj["progress"]:.4f}' ) obj["image"].save("""diffusers_library_progress.jpg""" ) UpperCamelCase : Optional[int] = pipe(image=snake_case_ ,prompt="""Black font, white background, vector""" ,noise_level=4_0 ,callback=snake_case_ ) final_image.save("""diffusers_library.jpg""" ) if __name__ == "__main__": main()
361
"""simple docstring""" import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : Optional[int] = { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json''', } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[int] = 'mvp' lowercase : Optional[Any] = ['past_key_values'] lowercase : Union[str, Any] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , SCREAMING_SNAKE_CASE_=5_0267 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=100 , SCREAMING_SNAKE_CASE_=800 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Dict = max_position_embeddings UpperCamelCase : Optional[int] = d_model UpperCamelCase : Optional[Any] = encoder_ffn_dim UpperCamelCase : Any = encoder_layers UpperCamelCase : List[Any] = encoder_attention_heads UpperCamelCase : Optional[Any] = decoder_ffn_dim UpperCamelCase : Optional[int] = decoder_layers UpperCamelCase : Dict = decoder_attention_heads UpperCamelCase : List[str] = dropout UpperCamelCase : List[str] = attention_dropout UpperCamelCase : List[Any] = activation_dropout UpperCamelCase : Dict = activation_function UpperCamelCase : List[str] = init_std UpperCamelCase : int = encoder_layerdrop UpperCamelCase : Dict = decoder_layerdrop UpperCamelCase : Any = classifier_dropout UpperCamelCase : Tuple = use_cache UpperCamelCase : Dict = encoder_layers UpperCamelCase : Tuple = scale_embedding # scale factor will be sqrt(d_model) if True UpperCamelCase : Optional[Any] = use_prompt UpperCamelCase : Any = prompt_length UpperCamelCase : List[Any] = prompt_mid_dim super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , forced_eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated""" , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = self.bos_token_id warnings.warn( f'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ' """The config can simply be saved and uploaded again to be fixed.""" )
27
0
"""simple docstring""" from ...processing_utils import ProcessorMixin class lowerCamelCase ( _UpperCAmelCase ): lowercase : int = 'WhisperFeatureExtractor' lowercase : Dict = 'WhisperTokenizer' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.feature_extractor UpperCamelCase : Optional[Any] = False def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True ): return self.tokenizer.get_decoder_prompt_ids(task=SCREAMING_SNAKE_CASE_ , language=SCREAMING_SNAKE_CASE_ , no_timestamps=SCREAMING_SNAKE_CASE_ ) def __call__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = kwargs.pop("""sampling_rate""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Optional[Any] = args[0] UpperCamelCase : Dict = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if audio is not None: UpperCamelCase : Tuple = self.feature_extractor(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if text is not None: UpperCamelCase : Dict = self.tokenizer(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if text is None: return inputs elif audio is None: return encodings else: UpperCamelCase : Optional[Any] = encodings["""input_ids"""] return inputs def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="np" ): return self.tokenizer.get_prompt_ids(SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ )
362
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __A : Optional[Any] = 16 __A : str = 32 def A_ ( snake_case_ : Accelerator ,snake_case_ : int = 1_6 ): '''simple docstring''' UpperCamelCase : Tuple = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCamelCase : Optional[int] = load_dataset("""glue""" ,"""mrpc""" ) def tokenize_function(snake_case_ : List[Any] ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase : Union[str, Any] = tokenizer(examples["""sentence1"""] ,examples["""sentence2"""] ,truncation=snake_case_ ,max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase : Optional[Any] = datasets.map( snake_case_ ,batched=snake_case_ ,remove_columns=["""idx""", """sentence1""", """sentence2"""] ,) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase : str = tokenized_datasets.rename_column("""label""" ,"""labels""" ) def collate_fn(snake_case_ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase : Optional[Any] = 1_6 elif accelerator.mixed_precision != "no": UpperCamelCase : Any = 8 else: UpperCamelCase : Optional[Any] = None return tokenizer.pad( snake_case_ ,padding="""longest""" ,max_length=snake_case_ ,pad_to_multiple_of=snake_case_ ,return_tensors="""pt""" ,) # Instantiate dataloaders. UpperCamelCase : str = DataLoader( tokenized_datasets["""train"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) UpperCamelCase : Dict = DataLoader( tokenized_datasets["""validation"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders __A : int = mocked_dataloaders # noqa: F811 def A_ ( snake_case_ : Tuple ,snake_case_ : Dict ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" ,snake_case_ ) == "1": UpperCamelCase : Union[str, Any] = 2 # New Code # UpperCamelCase : Dict = int(args.gradient_accumulation_steps ) UpperCamelCase : List[Any] = int(args.local_sgd_steps ) # Initialize accelerator UpperCamelCase : str = Accelerator( cpu=args.cpu ,mixed_precision=args.mixed_precision ,gradient_accumulation_steps=snake_case_ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase : Union[str, Any] = config["""lr"""] UpperCamelCase : int = int(config["""num_epochs"""] ) UpperCamelCase : int = int(config["""seed"""] ) UpperCamelCase : List[Any] = int(config["""batch_size"""] ) UpperCamelCase : Optional[int] = evaluate.load("""glue""" ,"""mrpc""" ) set_seed(snake_case_ ) UpperCamelCase , UpperCamelCase : Dict = get_dataloaders(snake_case_ ,snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase : Optional[int] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" ,return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase : Tuple = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase : List[Any] = AdamW(params=model.parameters() ,lr=snake_case_ ) # Instantiate scheduler UpperCamelCase : str = get_linear_schedule_with_warmup( optimizer=snake_case_ ,num_warmup_steps=1_0_0 ,num_training_steps=(len(snake_case_ ) * num_epochs) ,) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Any = accelerator.prepare( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() with LocalSGD( accelerator=snake_case_ ,model=snake_case_ ,local_sgd_steps=snake_case_ ,enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(snake_case_ ): UpperCamelCase : Optional[Any] = model(**snake_case_ ) UpperCamelCase : Optional[int] = output.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase : Any = model(**snake_case_ ) UpperCamelCase : Tuple = outputs.logits.argmax(dim=-1 ) UpperCamelCase , UpperCamelCase : int = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case_ ,references=snake_case_ ,) UpperCamelCase : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' ,snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" ,type=snake_case_ ,default=snake_case_ ,choices=["""no""", """fp16""", """bf16""", """fp8"""] ,help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" ,) # New Code # parser.add_argument( """--gradient_accumulation_steps""" ,type=snake_case_ ,default=1 ,help="""The number of minibatches to be ran before gradients are accumulated.""" ,) parser.add_argument( """--local_sgd_steps""" ,type=snake_case_ ,default=8 ,help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" ,action="""store_true""" ,help="""If passed, will train on the CPU.""" ) UpperCamelCase : Dict = parser.parse_args() UpperCamelCase : List[Any] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(snake_case_ ,snake_case_ ) if __name__ == "__main__": main()
27
0
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __A : int = logging.get_logger(__name__) __A : Dict = { '''BAAI/AltCLIP''': '''https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json''', # See all AltCLIP models at https://huggingface.co/models?filter=altclip } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[int] = 'altclip_text_model' def __init__( self , SCREAMING_SNAKE_CASE_=25_0002 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=24 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=514 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-05 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_="absolute" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=768 , **SCREAMING_SNAKE_CASE_ , ): super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = vocab_size UpperCamelCase : Tuple = hidden_size UpperCamelCase : Optional[Any] = num_hidden_layers UpperCamelCase : Tuple = num_attention_heads UpperCamelCase : Dict = hidden_act UpperCamelCase : Dict = intermediate_size UpperCamelCase : str = hidden_dropout_prob UpperCamelCase : Optional[int] = attention_probs_dropout_prob UpperCamelCase : Optional[int] = max_position_embeddings UpperCamelCase : str = type_vocab_size UpperCamelCase : List[Any] = initializer_range UpperCamelCase : str = initializer_factor UpperCamelCase : Optional[int] = layer_norm_eps UpperCamelCase : Any = position_embedding_type UpperCamelCase : Union[str, Any] = use_cache UpperCamelCase : List[str] = project_dim class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[Any] = 'altclip_vision_model' def __init__( self , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=224 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_="quick_gelu" , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1.0 , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = hidden_size UpperCamelCase : str = intermediate_size UpperCamelCase : Union[str, Any] = projection_dim UpperCamelCase : List[Any] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : str = num_channels UpperCamelCase : List[str] = patch_size UpperCamelCase : List[str] = image_size UpperCamelCase : Optional[int] = initializer_range UpperCamelCase : Optional[int] = initializer_factor UpperCamelCase : List[Any] = attention_dropout UpperCamelCase : Union[str, Any] = layer_norm_eps UpperCamelCase : Dict = hidden_act @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = cls.get_config_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # get the vision config dict if we are loading from AltCLIPConfig if config_dict.get("""model_type""" ) == "altclip": UpperCamelCase : int = 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(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) class lowerCamelCase ( _UpperCAmelCase ): lowercase : int = 'altclip' lowercase : str = True def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=2.6592 , **SCREAMING_SNAKE_CASE_ ): # If `_config_dict` exist, we use them for the backward compatibility. # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot # of confusion!). UpperCamelCase : Dict = kwargs.pop("""text_config_dict""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = kwargs.pop("""vision_config_dict""" , SCREAMING_SNAKE_CASE_ ) super().__init__(**SCREAMING_SNAKE_CASE_ ) # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`. if text_config_dict is not None: if text_config is None: UpperCamelCase : List[str] = {} # This is the complete result when using `text_config_dict`. UpperCamelCase : int = AltCLIPTextConfig(**SCREAMING_SNAKE_CASE_ ).to_dict() # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different. for key, value in _text_config_dict.items(): if key in text_config and value != text_config[key] and key not in ["transformers_version"]: # If specified in `text_config_dict` if key in text_config_dict: UpperCamelCase : List[Any] = ( f'`{key}` is found in both `text_config_dict` and `text_config` but with different values. ' f'The value `text_config_dict["{key}"]` will be used instead.' ) # If inferred from default argument values (just to be super careful) else: UpperCamelCase : Any = ( f'`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The ' f'value `text_config["{key}"]` will be overriden.' ) logger.warning(SCREAMING_SNAKE_CASE_ ) # Update all values in `text_config` with the ones in `_text_config_dict`. text_config.update(_text_config_dict ) if vision_config_dict is not None: if vision_config is None: UpperCamelCase : List[str] = {} # This is the complete result when using `vision_config_dict`. UpperCamelCase : Dict = AltCLIPVisionConfig(**SCREAMING_SNAKE_CASE_ ).to_dict() # convert keys to string instead of integer if "id2label" in _vision_config_dict: UpperCamelCase : List[Any] = { str(SCREAMING_SNAKE_CASE_ ): value for key, value in _vision_config_dict["""id2label"""].items() } # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different. for key, value in _vision_config_dict.items(): if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]: # If specified in `vision_config_dict` if key in vision_config_dict: UpperCamelCase : int = ( f'`{key}` is found in both `vision_config_dict` and `vision_config` but with different ' f'values. The value `vision_config_dict["{key}"]` will be used instead.' ) # If inferred from default argument values (just to be super careful) else: UpperCamelCase : List[Any] = ( f'`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. ' f'The value `vision_config["{key}"]` will be overriden.' ) logger.warning(SCREAMING_SNAKE_CASE_ ) # Update all values in `vision_config` with the ones in `_vision_config_dict`. vision_config.update(_vision_config_dict ) if text_config is None: UpperCamelCase : int = {} logger.info("""`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.""" ) if vision_config is None: UpperCamelCase : str = {} logger.info("""`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.""" ) UpperCamelCase : str = AltCLIPTextConfig(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = AltCLIPVisionConfig(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = projection_dim UpperCamelCase : Union[str, Any] = logit_scale_init_value UpperCamelCase : Union[str, Any] = 1.0 @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Union[str, Any] = copy.deepcopy(self.__dict__ ) UpperCamelCase : Dict = self.text_config.to_dict() UpperCamelCase : Union[str, Any] = self.vision_config.to_dict() UpperCamelCase : Any = self.__class__.model_type return output
363
"""simple docstring""" from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer __A : Any = logging.get_logger(__name__) __A : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A : Optional[Any] = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } __A : Any = {'''allegro/herbert-base-cased''': 514} __A : Optional[Any] = {} class lowerCamelCase ( _UpperCAmelCase ): lowercase : Dict = VOCAB_FILES_NAMES lowercase : Any = PRETRAINED_VOCAB_FILES_MAP lowercase : List[str] = PRETRAINED_INIT_CONFIGURATION lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Union[str, Any] = HerbertTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_="</s>" , **SCREAMING_SNAKE_CASE_ , ): super().__init__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = [self.cls_token_id] UpperCamelCase : str = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Tuple = [self.sep_token_id] UpperCamelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Optional[int] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
27
0
"""simple docstring""" import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class lowerCamelCase ( _UpperCAmelCase ): def a_ ( self ): UpperCamelCase : Optional[int] = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def a_ ( self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def a_ ( self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""bool""" ) , type=Value("""int64""" ) ) ) def a_ ( self ): UpperCamelCase : Tuple = pa.array(TypedSequence([1, 2, 3] , type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def a_ ( self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase : int = pa.array(TypedSequence(["""foo""", """bar"""] , type=Value("""int64""" ) ) ) def a_ ( self ): UpperCamelCase : Dict = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def a_ ( self ): UpperCamelCase : List[str] = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=Value("""int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) def a_ ( self ): UpperCamelCase : List[Any] = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def a_ ( self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase : Tuple = pa.array(TypedSequence(["""foo""", """bar"""] , type=ArrayaD((1, 3) , """int64""" ) ) ) def a_ ( self ): UpperCamelCase : List[str] = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def a_ ( self ): UpperCamelCase : int = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def a_ ( self ): import PIL.Image UpperCamelCase : List[str] = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( """datasets.arrow_writer.cast_to_python_objects""" , side_effect=SCREAMING_SNAKE_CASE_ ) as mock_cast_to_python_objects: UpperCamelCase : Optional[int] = pa.array(TypedSequence([{"""path""": None, """bytes""": b"""image_bytes"""}, pil_image] , type=Image() ) ) UpperCamelCase : Tuple = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("""optimize_list_casting""" , SCREAMING_SNAKE_CASE_ ) self.assertFalse(kwargs["""optimize_list_casting"""] ) def A_ ( snake_case_ : Any ,snake_case_ : int ): '''simple docstring''' UpperCamelCase : str = pa.BufferReader(snake_case_ ) if isinstance(snake_case_ ,pa.Buffer ) else pa.memory_map(snake_case_ ) UpperCamelCase : List[Any] = pa.ipc.open_stream(snake_case_ ) UpperCamelCase : pa.Table = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("""writer_batch_size""" ,[None, 1, 1_0] ) @pytest.mark.parametrize( """fields""" ,[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def A_ ( snake_case_ : int ,snake_case_ : Any ): '''simple docstring''' UpperCamelCase : Optional[Any] = pa.BufferOutputStream() UpperCamelCase : str = pa.schema(snake_case_ ) if fields else None with ArrowWriter(stream=snake_case_ ,schema=snake_case_ ,writer_batch_size=snake_case_ ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase : Optional[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase : Union[str, Any] = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(snake_case_ ,metadata=writer._schema.metadata ) _check_output(output.getvalue() ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def A_ ( ): '''simple docstring''' UpperCamelCase : Any = pa.BufferOutputStream() UpperCamelCase : str = Features({"""labels""": ClassLabel(names=["""neg""", """pos"""] )} ) with ArrowWriter(stream=snake_case_ ,features=snake_case_ ) as writer: writer.write({"""labels""": 0} ) writer.write({"""labels""": 1} ) UpperCamelCase : Any = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata UpperCamelCase : Tuple = pa.BufferReader(output.getvalue() ) UpperCamelCase : Union[str, Any] = pa.ipc.open_stream(snake_case_ ) UpperCamelCase : pa.Table = f.read_all() UpperCamelCase : List[Any] = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(snake_case_ ) @pytest.mark.parametrize("""writer_batch_size""" ,[None, 1, 1_0] ) def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' UpperCamelCase : List[Any] = pa.BufferOutputStream() with ArrowWriter( stream=snake_case_ ,writer_batch_size=snake_case_ ,hash_salt="""split_name""" ,check_duplicates=snake_case_ ,) as writer: with pytest.raises(snake_case_ ): writer.write({"""col_1""": """foo""", """col_2""": 1} ,key=[1, 2] ) UpperCamelCase : int = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" ,[None, 2, 1_0] ) def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' UpperCamelCase : Optional[int] = pa.BufferOutputStream() with ArrowWriter( stream=snake_case_ ,writer_batch_size=snake_case_ ,hash_salt="""split_name""" ,check_duplicates=snake_case_ ,) as writer: with pytest.raises(snake_case_ ): writer.write({"""col_1""": """foo""", """col_2""": 1} ,key=1_0 ) writer.write({"""col_1""": """bar""", """col_2""": 2} ,key=1_0 ) UpperCamelCase : Any = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" ,[None, 2, 1_0] ) def A_ ( snake_case_ : Any ): '''simple docstring''' UpperCamelCase : List[Any] = pa.BufferOutputStream() with ArrowWriter( stream=snake_case_ ,writer_batch_size=snake_case_ ,hash_salt="""split_name""" ,check_duplicates=snake_case_ ,) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ,key=1 ) writer.write({"""col_1""": """bar""", """col_2""": 2} ,key=2 ) UpperCamelCase : Dict = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" ,[None, 1, 1_0] ) @pytest.mark.parametrize( """fields""" ,[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def A_ ( snake_case_ : Optional[int] ,snake_case_ : int ): '''simple docstring''' UpperCamelCase : Any = pa.BufferOutputStream() UpperCamelCase : Optional[Any] = pa.schema(snake_case_ ) if fields else None with ArrowWriter(stream=snake_case_ ,schema=snake_case_ ,writer_batch_size=snake_case_ ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) writer.write_batch({"""col_1""": [], """col_2""": []} ) UpperCamelCase : Dict = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase : str = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(snake_case_ ,metadata=writer._schema.metadata ) _check_output(output.getvalue() ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" ,[None, 1, 1_0] ) @pytest.mark.parametrize( """fields""" ,[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def A_ ( snake_case_ : Any ,snake_case_ : Optional[Any] ): '''simple docstring''' UpperCamelCase : Any = pa.BufferOutputStream() UpperCamelCase : Dict = pa.schema(snake_case_ ) if fields else None with ArrowWriter(stream=snake_case_ ,schema=snake_case_ ,writer_batch_size=snake_case_ ) as writer: writer.write_table(pa.Table.from_pydict({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) ) UpperCamelCase : int = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase : Union[str, Any] = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(snake_case_ ,metadata=writer._schema.metadata ) _check_output(output.getvalue() ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" ,[None, 1, 1_0] ) @pytest.mark.parametrize( """fields""" ,[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Optional[Any] ): '''simple docstring''' UpperCamelCase : Tuple = pa.BufferOutputStream() UpperCamelCase : Tuple = pa.schema(snake_case_ ) if fields else None with ArrowWriter(stream=snake_case_ ,schema=snake_case_ ,writer_batch_size=snake_case_ ) as writer: writer.write_row(pa.Table.from_pydict({"""col_1""": ["""foo"""], """col_2""": [1]} ) ) writer.write_row(pa.Table.from_pydict({"""col_1""": ["""bar"""], """col_2""": [2]} ) ) UpperCamelCase : Union[str, Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase : List[Any] = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(snake_case_ ,metadata=writer._schema.metadata ) _check_output(output.getvalue() ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def A_ ( ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase : List[Any] = {"""col_1""": pa.string(), """col_2""": pa.intaa()} UpperCamelCase : Any = os.path.join(snake_case_ ,"""test.arrow""" ) with ArrowWriter(path=snake_case_ ,schema=pa.schema(snake_case_ ) ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) UpperCamelCase : List[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(snake_case_ ,metadata=writer._schema.metadata ) _check_output(snake_case_ ,1 ) def A_ ( snake_case_ : Dict ): '''simple docstring''' if pa.types.is_list(snake_case_ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def A_ ( snake_case_ : Optional[int] ,snake_case_ : Dict ): '''simple docstring''' if isinstance(lst[0] ,snake_case_ ): change_first_primitive_element_in_list(lst[0] ,snake_case_ ) else: UpperCamelCase : List[Any] = value @pytest.mark.parametrize("""optimized_int_type, expected_dtype""" ,[(None, pa.intaa()), (Value("""int32""" ), pa.intaa())] ) @pytest.mark.parametrize("""sequence""" ,[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def A_ ( snake_case_ : Tuple ,snake_case_ : List[Any] ,snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Optional[Any] = pa.array(TypedSequence(snake_case_ ,optimized_int_type=snake_case_ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( """col, expected_dtype""" ,[ ("""attention_mask""", pa.inta()), ("""special_tokens_mask""", pa.inta()), ("""token_type_ids""", pa.inta()), ("""input_ids""", pa.intaa()), ("""other""", pa.intaa()), ] ,) @pytest.mark.parametrize("""sequence""" ,[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Union[str, Any] ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : str = pa.array(OptimizedTypedSequence(snake_case_ ,col=snake_case_ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications UpperCamelCase : str = copy.deepcopy(snake_case_ ) UpperCamelCase : Tuple = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(snake_case_ ,snake_case_ ) UpperCamelCase : int = pa.array(OptimizedTypedSequence(snake_case_ ,col=snake_case_ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("""raise_exception""" ,[False, True] ) def A_ ( snake_case_ : Dict ,snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : Tuple = str(tmp_path / """dataset-train.arrow""" ) try: with ArrowWriter(path=snake_case_ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : Dict = """mock://dataset-train.arrow""" with ArrowWriter(path=snake_case_ ,storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs ,type(snake_case_ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase : int = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : Union[str, Any] = pa.BufferOutputStream() with ParquetWriter(stream=snake_case_ ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase : List[str] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 UpperCamelCase : List[str] = pa.BufferReader(output.getvalue() ) UpperCamelCase : pa.Table = pq.read_table(snake_case_ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("""embed_local_files""" ,[False, True] ) def A_ ( snake_case_ : str ,snake_case_ : List[Any] ): '''simple docstring''' import PIL.Image UpperCamelCase : Optional[Any] = str(tmp_path / """test_image_rgb.jpg""" ) PIL.Image.fromarray(np.zeros((5, 5) ,dtype=np.uinta ) ).save(snake_case_ ,format="""png""" ) UpperCamelCase : List[str] = pa.BufferOutputStream() with ParquetWriter( stream=snake_case_ ,features=Features({"""image""": Image()} ) ,embed_local_files=snake_case_ ) as writer: writer.write({"""image""": image_path} ) writer.finalize() UpperCamelCase : Union[str, Any] = pa.BufferReader(output.getvalue() ) UpperCamelCase : pa.Table = pq.read_table(snake_case_ ) UpperCamelCase : Any = pa_table.to_pydict() if embed_local_files: assert isinstance(out["""image"""][0]["""path"""] ,snake_case_ ) with open(snake_case_ ,"""rb""" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def A_ ( ): '''simple docstring''' UpperCamelCase : int = pa.schema([pa.field("""col_1""" ,pa.string() ,nullable=snake_case_ )] ) UpperCamelCase : Dict = pa.BufferOutputStream() with ArrowWriter(stream=snake_case_ ) as writer: writer._build_writer(inferred_schema=snake_case_ ) assert writer._schema == pa.schema([pa.field("""col_1""" ,pa.string() )] )
364
"""simple docstring""" import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=3.6 ): UpperCamelCase : Dict = tokenizer UpperCamelCase : Optional[Any] = tokenizer.bos_token_id UpperCamelCase : Any = dataset UpperCamelCase : List[str] = seq_length UpperCamelCase : Optional[Any] = seq_length * chars_per_token * num_of_sequences def __iter__( self ): UpperCamelCase : Dict = iter(self.dataset ) UpperCamelCase : Union[str, Any] = True while more_examples: UpperCamelCase , UpperCamelCase : Tuple = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(SCREAMING_SNAKE_CASE_ )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: UpperCamelCase : Dict = False break UpperCamelCase : str = tokenizer(SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )["""input_ids"""] UpperCamelCase : str = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , self.seq_length ): UpperCamelCase : List[str] = all_token_ids[i : i + self.seq_length] if len(SCREAMING_SNAKE_CASE_ ) == self.seq_length: yield torch.tensor(SCREAMING_SNAKE_CASE_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Dict = {"""streaming""": True} UpperCamelCase : Optional[int] = load_dataset(args.dataset_name ,split="""train""" ,**snake_case_ ) UpperCamelCase : Optional[int] = ConstantLengthDataset(snake_case_ ,snake_case_ ,seq_length=args.seq_length ) UpperCamelCase : List[Any] = DataLoader(snake_case_ ,batch_size=args.batch_size ) return eval_dataloader def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' model.eval() UpperCamelCase : Dict = [] for step, batch in enumerate(snake_case_ ): with torch.no_grad(): UpperCamelCase : List[Any] = model(snake_case_ ,labels=snake_case_ ) UpperCamelCase : Any = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(snake_case_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break UpperCamelCase : Dict = torch.mean(torch.cat(snake_case_ ) ) try: UpperCamelCase : Dict = torch.exp(snake_case_ ) except OverflowError: UpperCamelCase : Optional[int] = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator __A : List[Any] = Accelerator() # Parse configuration __A : str = HfArgumentParser(EvaluationArguments) __A : List[Any] = parser.parse_args() set_seed(args.seed) # Logging __A : Any = logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer __A : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) __A : List[Any] = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader __A : int = create_dataloader(args) # Prepare everything with our `accelerator`. __A , __A : Optional[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') __A , __A : Tuple = evaluate(args) logger.info(F'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
27
0
import os import jsonlines import numpy as np from tqdm import tqdm __A : Optional[Any] = 2048 __A : List[Any] = 4096 __A : str = 42 __A : Optional[int] = os.environ.pop('''PROCESS_TRAIN''', '''false''') __A : List[Any] = {'''null''': 0, '''short''': 1, '''long''': 2, '''yes''': 3, '''no''': 4} def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' def choose_first(snake_case_ : Dict ,snake_case_ : str=False ): assert isinstance(snake_case_ ,snake_case_ ) if len(snake_case_ ) == 1: UpperCamelCase : Union[str, Any] = answer[0] return {k: [answer[k]] for k in answer} if is_long_answer else answer for a in answer: if is_long_answer: UpperCamelCase : Optional[Any] = {k: [a[k]] for k in a} if len(a["""start_token"""] ) > 0: break return a UpperCamelCase : str = {"""id""": example["""id"""]} UpperCamelCase : List[str] = example["""annotations"""] UpperCamelCase : Dict = annotation["""yes_no_answer"""] if 0 in yes_no_answer or 1 in yes_no_answer: UpperCamelCase : Optional[int] = ["""yes"""] if 1 in yes_no_answer else ["""no"""] UpperCamelCase : Optional[int] = [] UpperCamelCase : Optional[Any] = [] UpperCamelCase : Tuple = ["""<cls>"""] else: UpperCamelCase : int = ["""short"""] UpperCamelCase : Union[str, Any] = choose_first(annotation["""short_answers"""] ) if len(out["""start_token"""] ) == 0: # answer will be long if short is not available UpperCamelCase : List[str] = ["""long"""] UpperCamelCase : List[str] = choose_first(annotation["""long_answer"""] ,is_long_answer=snake_case_ ) UpperCamelCase : str = [] answer.update(snake_case_ ) # disregard some samples if len(answer["""start_token"""] ) > 1 or answer["start_token"] == answer["end_token"]: UpperCamelCase : str = True else: UpperCamelCase : List[Any] = False UpperCamelCase : Any = ["""start_token""", """end_token""", """start_byte""", """end_byte""", """text"""] if not all(isinstance(answer[k] ,snake_case_ ) for k in cols ): raise ValueError("""Issue in ID""" ,example["""id"""] ) return answer def A_ ( snake_case_ : Any ,snake_case_ : Optional[Any]=False ): '''simple docstring''' UpperCamelCase : List[str] = _get_single_answer(snake_case_ ) # bytes are of no use del answer["start_byte"] del answer["end_byte"] # handle yes_no answers explicitly if answer["category"][0] in ["yes", "no"]: # category is list with one element UpperCamelCase : Optional[int] = example["""document"""]["""tokens"""] UpperCamelCase : List[Any] = [] for i in range(len(doc["""token"""] ) ): if not doc["is_html"][i]: context.append(doc["""token"""][i] ) return { "context": " ".join(snake_case_ ), "answer": { "start_token": -1_0_0, # ignore index in cross-entropy "end_token": -1_0_0, # ignore index in cross-entropy "category": answer["category"], "span": answer["category"], # extra }, } # later, help in removing all no answers if answer["start_token"] == [-1]: return { "context": "None", "answer": { "start_token": -1, "end_token": -1, "category": "null", "span": "None", # extra }, } # handling normal samples UpperCamelCase : str = ["""start_token""", """end_token"""] answer.update({k: answer[k][0] if len(answer[k] ) > 0 else answer[k] for k in cols} ) # e.g. [10] == 10 UpperCamelCase : Dict = example["""document"""]["""tokens"""] UpperCamelCase : List[str] = answer["""start_token"""] UpperCamelCase : Optional[int] = answer["""end_token"""] UpperCamelCase : Optional[Any] = [] for i in range(len(doc["""token"""] ) ): if not doc["is_html"][i]: context.append(doc["""token"""][i] ) else: if answer["start_token"] > i: start_token -= 1 if answer["end_token"] > i: end_token -= 1 UpperCamelCase : Optional[Any] = """ """.join(context[start_token:end_token] ) # checking above code if assertion: UpperCamelCase : Optional[Any] = doc["""is_html"""][answer["""start_token"""] : answer["""end_token"""]] UpperCamelCase : Dict = doc["""token"""][answer["""start_token"""] : answer["""end_token"""]] UpperCamelCase : Optional[Any] = """ """.join([old[i] for i in range(len(snake_case_ ) ) if not is_html[i]] ) if new != old: print("""ID:""" ,example["""id"""] ) print("""New:""" ,snake_case_ ,end="""\n""" ) print("""Old:""" ,snake_case_ ,end="""\n\n""" ) return { "context": " ".join(snake_case_ ), "answer": { "start_token": start_token, "end_token": end_token - 1, # this makes it inclusive "category": answer["category"], # either long or short "span": new, # extra }, } def A_ ( snake_case_ : Dict ,snake_case_ : Optional[Any] ,snake_case_ : Tuple=2_0_4_8 ,snake_case_ : str=4_0_9_6 ,snake_case_ : Optional[int]=True ): '''simple docstring''' UpperCamelCase : List[Any] = get_context_and_ans(snake_case_ ,assertion=snake_case_ ) UpperCamelCase : Optional[Any] = out["""answer"""] # later, removing these samples if answer["start_token"] == -1: return { "example_id": example["id"], "input_ids": [[-1]], "labels": { "start_token": [-1], "end_token": [-1], "category": ["null"], }, } UpperCamelCase : Optional[Any] = tokenizer(example["""question"""]["""text"""] ,out["""context"""] ).input_ids UpperCamelCase : Dict = input_ids.index(tokenizer.sep_token_id ) + 1 # return yes/no if answer["category"][0] in ["yes", "no"]: # category is list with one element UpperCamelCase : List[Any] = [] UpperCamelCase : List[str] = [] UpperCamelCase : Optional[Any] = input_ids[:q_len] UpperCamelCase : List[str] = range(snake_case_ ,len(snake_case_ ) ,max_length - doc_stride ) for i in doc_start_indices: UpperCamelCase : str = i + max_length - q_len UpperCamelCase : Optional[Any] = input_ids[i:end_index] inputs.append(q_indices + slice ) category.append(answer["""category"""][0] ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": [-1_0_0] * len(snake_case_ ), "end_token": [-1_0_0] * len(snake_case_ ), "category": category, }, } UpperCamelCase : int = out["""context"""].split() UpperCamelCase : Tuple = splitted_context[answer["""end_token"""]] UpperCamelCase : List[Any] = len( tokenizer( """ """.join(splitted_context[: answer["""start_token"""]] ) ,add_special_tokens=snake_case_ ,).input_ids ) UpperCamelCase : List[str] = len( tokenizer(""" """.join(splitted_context[: answer["""end_token"""]] ) ,add_special_tokens=snake_case_ ).input_ids ) answer["start_token"] += q_len answer["end_token"] += q_len # fixing end token UpperCamelCase : Any = len(tokenizer(snake_case_ ,add_special_tokens=snake_case_ ).input_ids ) if num_sub_tokens > 1: answer["end_token"] += num_sub_tokens - 1 UpperCamelCase : Tuple = input_ids[answer["""start_token"""] : answer["""end_token"""] + 1] # right & left are inclusive UpperCamelCase : Any = answer["""start_token"""] UpperCamelCase : Optional[Any] = answer["""end_token"""] if assertion: UpperCamelCase : str = tokenizer.decode(snake_case_ ) if answer["span"] != new: print("""ISSUE IN TOKENIZATION""" ) print("""OLD:""" ,answer["""span"""] ) print("""NEW:""" ,snake_case_ ,end="""\n\n""" ) if len(snake_case_ ) <= max_length: return { "example_id": example["id"], "input_ids": [input_ids], "labels": { "start_token": [answer["start_token"]], "end_token": [answer["end_token"]], "category": answer["category"], }, } UpperCamelCase : Tuple = input_ids[:q_len] UpperCamelCase : Union[str, Any] = range(snake_case_ ,len(snake_case_ ) ,max_length - doc_stride ) UpperCamelCase : Any = [] UpperCamelCase : str = [] UpperCamelCase : Optional[int] = [] UpperCamelCase : Tuple = [] # null, yes, no, long, short for i in doc_start_indices: UpperCamelCase : Tuple = i + max_length - q_len UpperCamelCase : Optional[Any] = input_ids[i:end_index] inputs.append(q_indices + slice ) assert len(inputs[-1] ) <= max_length, "Issue in truncating length" if start_token >= i and end_token <= end_index - 1: UpperCamelCase : Any = start_token - i + q_len UpperCamelCase : Any = end_token - i + q_len answers_category.append(answer["""category"""][0] ) # ["short"] -> "short" else: UpperCamelCase : Optional[Any] = -1_0_0 UpperCamelCase : List[Any] = -1_0_0 answers_category.append("""null""" ) UpperCamelCase : Optional[int] = inputs[-1][start_token : end_token + 1] answers_start_token.append(snake_case_ ) answers_end_token.append(snake_case_ ) if assertion: if new != old and new != [tokenizer.cls_token_id]: print("""ISSUE in strided for ID:""" ,example["""id"""] ) print("""New:""" ,tokenizer.decode(snake_case_ ) ) print("""Old:""" ,tokenizer.decode(snake_case_ ) ,end="""\n\n""" ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": answers_start_token, "end_token": answers_end_token, "category": answers_category, }, } def A_ ( snake_case_ : Optional[Any] ,snake_case_ : List[str] ,snake_case_ : str=2_0_4_8 ,snake_case_ : List[Any]=4_0_9_6 ,snake_case_ : Any=False ): '''simple docstring''' UpperCamelCase : Optional[Any] = get_strided_contexts_and_ans( snake_case_ ,snake_case_ ,doc_stride=snake_case_ ,max_length=snake_case_ ,assertion=snake_case_ ,) return example def A_ ( snake_case_ : Optional[int] ,snake_case_ : Optional[int] ): '''simple docstring''' with jsonlines.open(snake_case_ ,"""a""" ) as writer: for example in tqdm(snake_case_ ,total=len(snake_case_ ) ,desc="""Saving samples ... """ ): UpperCamelCase : int = example["""labels"""] for ids, start, end, cat in zip( example["""input_ids"""] ,labels["""start_token"""] ,labels["""end_token"""] ,labels["""category"""] ,): if start == -1 and end == -1: continue # leave waste samples with no answer if cat == "null" and np.random.rand() < 0.6: continue # removing 50 % samples writer.write( { """input_ids""": ids, """start_token""": start, """end_token""": end, """category""": CATEGORY_MAPPING[cat], } ) if __name__ == "__main__": from datasets import load_dataset from transformers import BigBirdTokenizer __A : Union[str, Any] = load_dataset('''natural_questions''') __A : List[str] = BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''') __A : Dict = data['''train''' if PROCESS_TRAIN == '''true''' else '''validation'''] __A : Tuple = { '''tokenizer''': tokenizer, '''doc_stride''': DOC_STRIDE, '''max_length''': MAX_LENGTH, '''assertion''': False, } __A : List[Any] = data.map(prepare_inputs, fn_kwargs=fn_kwargs) __A : int = data.remove_columns(['''annotations''', '''document''', '''id''', '''question''']) print(data) np.random.seed(SEED) __A : Union[str, Any] = '''nq-training.jsonl''' if PROCESS_TRAIN == '''true''' else '''nq-validation.jsonl''' save_to_disk(data, file_name=cache_file_name)
365
"""simple docstring""" import argparse import os import re __A : Any = '''src/transformers''' # Pattern that looks at the indentation in a line. __A : Tuple = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : List[Any] = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : List[Any] = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : Any = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : str ,snake_case_ : str="" ,snake_case_ : Any=None ,snake_case_ : Union[str, Any]=None ): '''simple docstring''' UpperCamelCase : List[Any] = 0 UpperCamelCase : Optional[int] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Tuple = ["""\n""".join(lines[:index] )] else: UpperCamelCase : Tuple = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Dict = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Optional[Any] = [lines[index + 1]] index += 1 else: UpperCamelCase : str = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : List[Any] ): '''simple docstring''' def _inner(snake_case_ : List[str] ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Tuple=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Optional[int] ): return x if key is None: UpperCamelCase : List[str] = noop # Constants are all uppercase, they go first. UpperCamelCase : List[str] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : Tuple = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : int = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Union[str, Any] = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : Any ): UpperCamelCase : Union[str, Any] = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : int = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : str = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : Optional[int] = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : int = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Tuple = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : List[Any] = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Union[str, Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : List[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : Optional[int] = keys[:-1] UpperCamelCase : Union[str, Any] = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : Any = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : int=True ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : List[str] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : int = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Dict = main_blocks[block_idx] UpperCamelCase : Dict = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : List[str] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : Optional[Any] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Optional[Any] = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Any = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : List[Any] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Optional[Any] = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Optional[Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Any = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : Union[str, Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[str] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: UpperCamelCase : Optional[int] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Optional[int] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : List[Any] = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : Union[str, Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
0
"""simple docstring""" import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py __A : List[Any] = '''.''' if __name__ == "__main__": __A : str = os.path.join(REPO_PATH, '''utils/documentation_tests.txt''') __A : Dict = [] __A : Union[str, Any] = [] with open(doctest_file_path) as fp: for line in fp: __A : int = line.strip() __A : List[str] = os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: __A : Tuple = '''\n'''.join(non_existent_paths) raise ValueError(F'''`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}''') if all_paths != sorted(all_paths): raise ValueError('''Files in `utils/documentation_tests.txt` are not in alphabetical order.''')
366
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' if number < 0: raise ValueError("""number must not be negative""" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
27
0
"""simple docstring""" import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging __A : Tuple = logging.get_logger(__name__) class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ ): super().__init__() UpperCamelCase : Optional[int] = nn.ModuleList(SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 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_ = False , SCREAMING_SNAKE_CASE_ = True , ): for i, (image, scale, controlnet) in enumerate(zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.nets ) ): UpperCamelCase : str = controlnet( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) # merge samples if i == 0: UpperCamelCase : List[str] = down_samples, mid_sample else: UpperCamelCase : int = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , ): UpperCamelCase : Dict = 0 UpperCamelCase : Any = save_directory for controlnet in self.nets: controlnet.save_pretrained( SCREAMING_SNAKE_CASE_ , is_main_process=SCREAMING_SNAKE_CASE_ , save_function=SCREAMING_SNAKE_CASE_ , safe_serialization=SCREAMING_SNAKE_CASE_ , variant=SCREAMING_SNAKE_CASE_ , ) idx += 1 UpperCamelCase : str = model_path_to_save + f'_{idx}' @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = 0 UpperCamelCase : Optional[int] = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... UpperCamelCase : Tuple = pretrained_model_path while os.path.isdir(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = ControlNetModel.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) controlnets.append(SCREAMING_SNAKE_CASE_ ) idx += 1 UpperCamelCase : Tuple = pretrained_model_path + f'_{idx}' logger.info(f'{len(SCREAMING_SNAKE_CASE_ )} controlnets loaded from {pretrained_model_path}.' ) if len(SCREAMING_SNAKE_CASE_ ) == 0: raise ValueError( f'No ControlNets found under {os.path.dirname(SCREAMING_SNAKE_CASE_ )}. Expected at least {pretrained_model_path + "_0"}.' ) return cls(SCREAMING_SNAKE_CASE_ )
367
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL __A : Optional[Any] = logging.get_logger(__name__) def A_ ( snake_case_ : np.ndarray ,snake_case_ : Union[int, Iterable[int]] ,snake_case_ : bool ,snake_case_ : int ): '''simple docstring''' def constraint_to_multiple_of(snake_case_ : Optional[Any] ,snake_case_ : Optional[int] ,snake_case_ : List[str]=0 ,snake_case_ : Optional[Any]=None ): UpperCamelCase : List[str] = round(val / multiple ) * multiple if max_val is not None and x > max_val: UpperCamelCase : Optional[Any] = math.floor(val / multiple ) * multiple if x < min_val: UpperCamelCase : Dict = math.ceil(val / multiple ) * multiple return x UpperCamelCase : Any = (output_size, output_size) if isinstance(snake_case_ ,snake_case_ ) else output_size UpperCamelCase , UpperCamelCase : int = get_image_size(snake_case_ ) UpperCamelCase , UpperCamelCase : Union[str, Any] = output_size # determine new height and width UpperCamelCase : List[str] = output_height / input_height UpperCamelCase : List[str] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width UpperCamelCase : int = scale_width else: # fit height UpperCamelCase : Optional[Any] = scale_height UpperCamelCase : int = constraint_to_multiple_of(scale_height * input_height ,multiple=snake_case_ ) UpperCamelCase : Union[str, Any] = constraint_to_multiple_of(scale_width * input_width ,multiple=snake_case_ ) return (new_height, new_width) class lowerCamelCase ( _UpperCAmelCase ): lowercase : str = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = size if size is not None else {"""height""": 384, """width""": 384} UpperCamelCase : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = do_resize UpperCamelCase : Union[str, Any] = size UpperCamelCase : Union[str, Any] = keep_aspect_ratio UpperCamelCase : Any = ensure_multiple_of UpperCamelCase : List[Any] = resample UpperCamelCase : str = do_rescale UpperCamelCase : Optional[Any] = rescale_factor UpperCamelCase : List[str] = do_normalize UpperCamelCase : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCamelCase : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) UpperCamelCase : Dict = get_resize_output_image_size( SCREAMING_SNAKE_CASE_ , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=SCREAMING_SNAKE_CASE_ , multiple=SCREAMING_SNAKE_CASE_ , ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize UpperCamelCase : List[Any] = size if size is not None else self.size UpperCamelCase : Dict = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio UpperCamelCase : Optional[int] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of UpperCamelCase : Tuple = resample if resample is not None else self.resample UpperCamelCase : str = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase : Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase : Any = image_mean if image_mean is not None else self.image_mean UpperCamelCase : List[Any] = image_std if image_std is not None else self.image_std UpperCamelCase : str = make_list_of_images(SCREAMING_SNAKE_CASE_ ) if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. UpperCamelCase : Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase : Union[str, Any] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase : int = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase : List[str] = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Union[str, Any] = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : str = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = target_sizes.numpy() UpperCamelCase : Dict = [] for idx in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase : List[Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : List[Any] = logits.argmax(dim=1 ) UpperCamelCase : Dict = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
27
0
"""simple docstring""" from importlib import import_module from .logging import get_logger __A : str = get_logger(__name__) class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): UpperCamelCase : str = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("""__""" ): setattr(self , SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : List[Any] = module._original_module if isinstance(SCREAMING_SNAKE_CASE_ , _PatchedModuleObj ) else module class lowerCamelCase : lowercase : Any = [] def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): UpperCamelCase : Dict = obj UpperCamelCase : Any = target UpperCamelCase : Any = new UpperCamelCase : Optional[Any] = target.split(""".""" )[0] UpperCamelCase : int = {} UpperCamelCase : List[str] = attrs or [] def __enter__( self ): UpperCamelCase : int = self.target.split(""".""" ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(SCREAMING_SNAKE_CASE_ ) ): try: UpperCamelCase : int = import_module(""".""".join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): UpperCamelCase : Tuple = getattr(self.obj , SCREAMING_SNAKE_CASE_ ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(SCREAMING_SNAKE_CASE_ , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): UpperCamelCase : Optional[Any] = obj_attr # patch at top level setattr(self.obj , SCREAMING_SNAKE_CASE_ , _PatchedModuleObj(SCREAMING_SNAKE_CASE_ , attrs=self.attrs ) ) UpperCamelCase : Optional[Any] = getattr(self.obj , SCREAMING_SNAKE_CASE_ ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , _PatchedModuleObj(getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , attrs=self.attrs ) ) UpperCamelCase : Any = getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # finally set the target attribute setattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: UpperCamelCase : Union[str, Any] = getattr(import_module(""".""".join(SCREAMING_SNAKE_CASE_ ) ) , SCREAMING_SNAKE_CASE_ ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , SCREAMING_SNAKE_CASE_ ) is attr_value: UpperCamelCase : Union[str, Any] = getattr(self.obj , SCREAMING_SNAKE_CASE_ ) setattr(self.obj , SCREAMING_SNAKE_CASE_ , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" UpperCamelCase : str = globals()["""__builtins__"""][target_attr] setattr(self.obj , SCREAMING_SNAKE_CASE_ , self.new ) else: raise RuntimeError(f'Tried to patch attribute {target_attr} instead of a submodule.' ) def __exit__( self , *SCREAMING_SNAKE_CASE_ ): for attr in list(self.original ): setattr(self.obj , SCREAMING_SNAKE_CASE_ , self.original.pop(SCREAMING_SNAKE_CASE_ ) ) def a_ ( self ): self.__enter__() self._active_patches.append(self ) def a_ ( self ): try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
368
"""simple docstring""" from collections.abc import Callable def A_ ( snake_case_ : Callable[[float], float] ,snake_case_ : float ,snake_case_ : float ): '''simple docstring''' UpperCamelCase : float = a UpperCamelCase : float = b if function(snake_case_ ) == 0: # one of the a or b is a root for the function return a elif function(snake_case_ ) == 0: return b elif ( function(snake_case_ ) * function(snake_case_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("""could not find root in given interval.""" ) else: UpperCamelCase : float = start + (end - start) / 2.0 while abs(start - mid ) > 1_0**-7: # until precisely equals to 10^-7 if function(snake_case_ ) == 0: return mid elif function(snake_case_ ) * function(snake_case_ ) < 0: UpperCamelCase : Dict = mid else: UpperCamelCase : List[str] = mid UpperCamelCase : Tuple = start + (end - start) / 2.0 return mid def A_ ( snake_case_ : float ): '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
27
0
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch __A : Optional[Any] = random.Random() def A_ ( snake_case_ : str ,snake_case_ : List[str]=1.0 ,snake_case_ : Any=None ,snake_case_ : Optional[Any]=None ): '''simple docstring''' if rng is None: UpperCamelCase : Any = global_rng UpperCamelCase : int = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class lowerCamelCase ( unittest.TestCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=400 , SCREAMING_SNAKE_CASE_=2000 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=1_6000 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=80 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_="hann_window" , SCREAMING_SNAKE_CASE_=80 , SCREAMING_SNAKE_CASE_=7600 , SCREAMING_SNAKE_CASE_=1e-10 , SCREAMING_SNAKE_CASE_=True , ): UpperCamelCase : List[Any] = parent UpperCamelCase : Any = batch_size UpperCamelCase : List[Any] = min_seq_length UpperCamelCase : List[str] = max_seq_length UpperCamelCase : Union[str, Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCamelCase : Tuple = feature_size UpperCamelCase : int = padding_value UpperCamelCase : Dict = sampling_rate UpperCamelCase : Tuple = do_normalize UpperCamelCase : List[Any] = num_mel_bins UpperCamelCase : Dict = hop_length UpperCamelCase : Optional[Any] = win_length UpperCamelCase : Union[str, Any] = win_function UpperCamelCase : Optional[int] = fmin UpperCamelCase : str = fmax UpperCamelCase : Optional[int] = mel_floor UpperCamelCase : Any = return_attention_mask def a_ ( self ): return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def a_ ( self , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False ): def _flatten(SCREAMING_SNAKE_CASE_ ): return list(itertools.chain(*SCREAMING_SNAKE_CASE_ ) ) if equal_length: UpperCamelCase : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size UpperCamelCase : Any = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: UpperCamelCase : Tuple = [np.asarray(SCREAMING_SNAKE_CASE_ ) for x in speech_inputs] return speech_inputs def a_ ( self , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False ): if equal_length: UpperCamelCase : List[str] = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size UpperCamelCase : List[Any] = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: UpperCamelCase : Tuple = [np.asarray(SCREAMING_SNAKE_CASE_ ) for x in speech_inputs] return speech_inputs @require_torch class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : List[Any] = SpeechTaFeatureExtractor def a_ ( self ): UpperCamelCase : Optional[Any] = SpeechTaFeatureExtractionTester(self ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.assertTrue(np.all(np.mean(SCREAMING_SNAKE_CASE_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(SCREAMING_SNAKE_CASE_ , axis=0 ) - 1 ) < 1e-3 ) ) def a_ ( self ): # Tests that all call wrap to encode_plus and batch_encode_plus UpperCamelCase : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCamelCase : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : Optional[int] = [np.asarray(SCREAMING_SNAKE_CASE_ ) for speech_input in speech_inputs] # Test not batched input UpperCamelCase : Optional[Any] = feat_extract(speech_inputs[0] , return_tensors="""np""" ).input_values UpperCamelCase : Dict = feat_extract(np_speech_inputs[0] , return_tensors="""np""" ).input_values self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) # Test batched UpperCamelCase : Optional[Any] = feat_extract(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ).input_values UpperCamelCase : Dict = feat_extract(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) def a_ ( self ): UpperCamelCase : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : Any = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : List[Any] = ["""longest""", """max_length""", """do_not_pad"""] UpperCamelCase : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = feat_extract(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ) UpperCamelCase : Dict = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def a_ ( self ): UpperCamelCase : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : Optional[Any] = range(800 , 1400 , 200 ) UpperCamelCase : Any = [floats_list((1, x) )[0] for x in lengths] UpperCamelCase : int = ["""longest""", """max_length""", """do_not_pad"""] UpperCamelCase : str = [None, 1600, None] for max_length, padding in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = feat_extract(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def a_ ( self ): UpperCamelCase : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : Union[str, Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : str = feat_extract( SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=1000 , padding="""max_length""" , return_tensors="""np""" ) UpperCamelCase : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def a_ ( self ): UpperCamelCase : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : int = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : str = feat_extract( SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=1000 , padding="""longest""" , return_tensors="""np""" ) UpperCamelCase : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) UpperCamelCase : Any = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : Dict = feat_extract( SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=2000 , padding="""longest""" , return_tensors="""np""" ) UpperCamelCase : Any = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def a_ ( self ): UpperCamelCase : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : Dict = np.random.rand(100 ).astype(np.floataa ) UpperCamelCase : Any = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCamelCase : Any = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) UpperCamelCase : int = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def a_ ( self ): # Tests that all call wrap to encode_plus and batch_encode_plus UpperCamelCase : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCamelCase : Any = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : Tuple = [np.asarray(SCREAMING_SNAKE_CASE_ ) for speech_input in speech_inputs] # Test feature size UpperCamelCase : Optional[Any] = feature_extractor(audio_target=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input UpperCamelCase : List[str] = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_values UpperCamelCase : List[str] = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_values self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) # Test batched UpperCamelCase : int = feature_extractor(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ).input_values UpperCamelCase : Tuple = feature_extractor(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. UpperCamelCase : Optional[Any] = [floats_list((1, x) )[0] for x in (800, 800, 800)] UpperCamelCase : int = np.asarray(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = feature_extractor(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ).input_values UpperCamelCase : List[str] = feature_extractor(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) def a_ ( self ): UpperCamelCase : Dict = self.feat_extract_tester.prepare_inputs_for_target() UpperCamelCase : Any = self.feature_extraction_class(**self.feat_extract_dict ) UpperCamelCase : List[str] = feat_extract.model_input_names[0] UpperCamelCase : Optional[int] = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(SCREAMING_SNAKE_CASE_ ) == len(SCREAMING_SNAKE_CASE_ ) for x, y in zip(SCREAMING_SNAKE_CASE_ , processed_features[input_name] ) ) ) UpperCamelCase : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = BatchFeature({input_name: speech_inputs} , tensor_type="""np""" ) UpperCamelCase : str = processed_features[input_name] if len(batch_features_input.shape ) < 3: UpperCamelCase : Union[str, Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def a_ ( self ): UpperCamelCase : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) UpperCamelCase : List[Any] = feat_extract.model_input_names[0] UpperCamelCase : Any = BatchFeature({input_name: speech_inputs} , tensor_type="""pt""" ) UpperCamelCase : Dict = processed_features[input_name] if len(batch_features_input.shape ) < 3: UpperCamelCase : str = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def a_ ( self ): UpperCamelCase : Any = self.feature_extraction_class(**self.feat_extract_dict ) UpperCamelCase : int = self.feat_extract_tester.prepare_inputs_for_target() UpperCamelCase : str = feat_extract.model_input_names[0] UpperCamelCase : str = BatchFeature({input_name: speech_inputs} ) UpperCamelCase : Optional[int] = feat_extract.num_mel_bins # hack! UpperCamelCase : int = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding="""longest""" , return_tensors="""np""" )[input_name] UpperCamelCase : Dict = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding="""longest""" , return_tensors="""pt""" )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def a_ ( self ): UpperCamelCase : List[Any] = self.feat_extract_dict UpperCamelCase : List[Any] = True UpperCamelCase : Optional[Any] = self.feature_extraction_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() UpperCamelCase : str = [len(SCREAMING_SNAKE_CASE_ ) for x in speech_inputs] UpperCamelCase : str = feat_extract.model_input_names[0] UpperCamelCase : List[Any] = BatchFeature({input_name: speech_inputs} ) UpperCamelCase : Tuple = feat_extract.num_mel_bins # hack! UpperCamelCase : Optional[int] = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding="""longest""" , return_tensors="""np""" ) self.assertIn("""attention_mask""" , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.feat_extract_dict UpperCamelCase : Union[str, Any] = True UpperCamelCase : List[str] = self.feature_extraction_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = self.feat_extract_tester.prepare_inputs_for_target() UpperCamelCase : Any = [len(SCREAMING_SNAKE_CASE_ ) for x in speech_inputs] UpperCamelCase : int = feat_extract.model_input_names[0] UpperCamelCase : Any = BatchFeature({input_name: speech_inputs} ) UpperCamelCase : str = min(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = feat_extract.num_mel_bins # hack! UpperCamelCase : Optional[Any] = feat_extract.pad( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ) self.assertIn("""attention_mask""" , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): from datasets import load_dataset UpperCamelCase : List[str] = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech UpperCamelCase : Union[str, Any] = ds.sort("""id""" ).select(range(SCREAMING_SNAKE_CASE_ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def a_ ( self ): # fmt: off UpperCamelCase : int = torch.tensor( [2.3804e-03, 2.0752e-03, 1.9836e-03, 2.1057e-03, 1.6174e-03, 3.0518e-04, 9.1553e-05, 3.3569e-04, 9.7656e-04, 1.8311e-03, 2.0142e-03, 2.1057e-03, 1.7395e-03, 4.5776e-04, -3.9673e-04, 4.5776e-04, 1.0071e-03, 9.1553e-05, 4.8828e-04, 1.1597e-03, 7.3242e-04, 9.4604e-04, 1.8005e-03, 1.8311e-03, 8.8501e-04, 4.2725e-04, 4.8828e-04, 7.3242e-04, 1.0986e-03, 2.1057e-03] ) # fmt: on UpperCamelCase : List[Any] = self._load_datasamples(1 ) UpperCamelCase : int = SpeechTaFeatureExtractor() UpperCamelCase : str = feature_extractor(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , SCREAMING_SNAKE_CASE_ , atol=1e-6 ) ) def a_ ( self ): # fmt: off UpperCamelCase : Dict = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on UpperCamelCase : Tuple = self._load_datasamples(1 ) UpperCamelCase : Optional[Any] = SpeechTaFeatureExtractor() UpperCamelCase : Optional[int] = feature_extractor(audio_target=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
369
"""simple docstring""" import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def a_ ( self ): UpperCamelCase : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) UpperCamelCase : int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) UpperCamelCase : Dict = """xvjiarui/stable-diffusion-2-inpainting""" UpperCamelCase , UpperCamelCase : List[str] = FlaxStableDiffusionInpaintPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = """Face of a yellow cat, high resolution, sitting on a park bench""" UpperCamelCase : List[str] = jax.random.PRNGKey(0 ) UpperCamelCase : Tuple = 50 UpperCamelCase : Dict = jax.device_count() UpperCamelCase : Optional[int] = num_samples * [prompt] UpperCamelCase : int = num_samples * [init_image] UpperCamelCase : List[Any] = num_samples * [mask_image] UpperCamelCase , UpperCamelCase , UpperCamelCase : Optional[Any] = pipeline.prepare_inputs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # shard inputs and rng UpperCamelCase : Optional[int] = replicate(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = jax.random.split(SCREAMING_SNAKE_CASE_ , jax.device_count() ) UpperCamelCase : str = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = pipeline( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , jit=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = output.images.reshape(SCREAMING_SNAKE_CASE_ , 512 , 512 , 3 ) UpperCamelCase : List[Any] = images[0, 253:256, 253:256, -1] UpperCamelCase : List[Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) UpperCamelCase : Dict = jnp.array( [0.3611307, 0.37649736, 0.3757408, 0.38213953, 0.39295167, 0.3841631, 0.41554978, 0.4137475, 0.4217084] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
27
0
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[List[np.ndarray], torch.FloatTensor] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
370
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def A_ ( snake_case_ : int ): # picklable for multiprocessing '''simple docstring''' return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def A_ ( ): '''simple docstring''' with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" UpperCamelCase : Optional[Any] = [1, 2, 3] with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=2 ) with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" ,[2, -1] ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : List[Any] = [1, 2] UpperCamelCase : List[Any] = {"""a""": 1, """b""": 2} UpperCamelCase : List[str] = {"""a""": [1, 2], """b""": [3, 4]} UpperCamelCase : Tuple = {"""a""": {"""1""": 1}, """b""": 2} UpperCamelCase : Any = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} UpperCamelCase : Optional[int] = [2, 3] UpperCamelCase : List[str] = {"""a""": 2, """b""": 3} UpperCamelCase : Any = {"""a""": [2, 3], """b""": [4, 5]} UpperCamelCase : Tuple = {"""a""": {"""1""": 2}, """b""": 3} UpperCamelCase : List[str] = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa
27
0
"""simple docstring""" import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import AcceleratorState, PartialState from ..utils import ( gather, is_bnb_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_mps_available, is_safetensors_available, is_tensorboard_available, is_torch_version, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Dict=False ): '''simple docstring''' try: UpperCamelCase : Optional[int] = os.environ[key] except KeyError: # KEY isn't set, default to `default`. UpperCamelCase : Any = default else: # KEY is set, convert it to True or False. try: UpperCamelCase : str = strtobool(snake_case_ ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f'If set, {key} must be yes or no.' ) return _value __A : int = parse_flag_from_env('''RUN_SLOW''', default=False) def A_ ( snake_case_ : Tuple ): '''simple docstring''' return unittest.skip("""Test was skipped""" )(snake_case_ ) def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' return unittest.skipUnless(_run_slow_tests ,"""test is slow""" )(snake_case_ ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' return unittest.skipUnless(not torch.cuda.is_available() ,"""test requires only a CPU""" )(snake_case_ ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' return unittest.skipUnless(torch.cuda.is_available() ,"""test requires a GPU""" )(snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' return unittest.skipUnless(is_xpu_available() ,"""test requires a XPU""" )(snake_case_ ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' return unittest.skipUnless(is_mps_available() ,"""test requires a `mps` backend support in `torch`""" )(snake_case_ ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' return unittest.skipUnless( is_transformers_available() and is_datasets_available() ,"""test requires the Hugging Face suite""" )(snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' return unittest.skipUnless(is_bnb_available() ,"""test requires the bitsandbytes library""" )(snake_case_ ) def A_ ( snake_case_ : Any ): '''simple docstring''' return unittest.skipUnless(is_tpu_available() ,"""test requires TPU""" )(snake_case_ ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() == 1 ,"""test requires a GPU""" )(snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() == 1 ,"""test requires a XPU""" )(snake_case_ ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() > 1 ,"""test requires multiple GPUs""" )(snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() > 1 ,"""test requires multiple XPUs""" )(snake_case_ ) def A_ ( snake_case_ : Dict ): '''simple docstring''' return unittest.skipUnless(is_safetensors_available() ,"""test requires safetensors""" )(snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' return unittest.skipUnless(is_deepspeed_available() ,"""test requires DeepSpeed""" )(snake_case_ ) def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' return unittest.skipUnless(is_torch_version(""">=""" ,"""1.12.0""" ) ,"""test requires torch version >= 1.12.0""" )(snake_case_ ) def A_ ( snake_case_ : Tuple=None ,snake_case_ : List[str]=None ): '''simple docstring''' if test_case is None: return partial(snake_case_ ,version=snake_case_ ) return unittest.skipUnless(is_torch_version(""">=""" ,snake_case_ ) ,f'test requires torch version >= {version}' )(snake_case_ ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' return unittest.skipUnless(is_tensorboard_available() ,"""test requires Tensorboard""" )(snake_case_ ) def A_ ( snake_case_ : Union[str, Any] ): '''simple docstring''' return unittest.skipUnless(is_wandb_available() ,"""test requires wandb""" )(snake_case_ ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' return unittest.skipUnless(is_comet_ml_available() ,"""test requires comet_ml""" )(snake_case_ ) __A : int = ( any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available() ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' return unittest.skipUnless( _atleast_one_tracker_available ,"""test requires at least one tracker to be available and for `comet_ml` to not be installed""" ,)(snake_case_ ) class lowerCamelCase ( unittest.TestCase ): lowercase : Optional[Any] = True @classmethod def a_ ( cls ): UpperCamelCase : Optional[Any] = tempfile.mkdtemp() @classmethod def a_ ( cls ): if os.path.exists(cls.tmpdir ): shutil.rmtree(cls.tmpdir ) def a_ ( self ): if self.clear_on_setup: for path in Path(self.tmpdir ).glob("""**/*""" ): if path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(SCREAMING_SNAKE_CASE_ ) class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() # Reset the state of the AcceleratorState singleton. AcceleratorState._reset_state() PartialState._reset_state() class lowerCamelCase ( unittest.TestCase ): def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = mocks if isinstance(SCREAMING_SNAKE_CASE_ , (tuple, list) ) else [mocks] for m in self.mocks: m.start() self.addCleanup(m.stop ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : List[str] = AcceleratorState() UpperCamelCase : Dict = tensor[None].clone().to(state.device ) UpperCamelCase : Optional[Any] = gather(snake_case_ ).cpu() UpperCamelCase : Tuple = tensor[0].cpu() for i in range(tensors.shape[0] ): if not torch.equal(tensors[i] ,snake_case_ ): return False return True class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = returncode UpperCamelCase : List[str] = stdout UpperCamelCase : Union[str, Any] = stderr async def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : List[str] ): '''simple docstring''' while True: UpperCamelCase : Any = await stream.readline() if line: callback(snake_case_ ) else: break async def A_ ( snake_case_ : List[str] ,snake_case_ : Tuple=None ,snake_case_ : int=None ,snake_case_ : str=None ,snake_case_ : Dict=False ,snake_case_ : List[str]=False ): '''simple docstring''' if echo: print("""\nRunning: """ ,""" """.join(snake_case_ ) ) UpperCamelCase : Any = await asyncio.create_subprocess_exec( cmd[0] ,*cmd[1:] ,stdin=snake_case_ ,stdout=asyncio.subprocess.PIPE ,stderr=asyncio.subprocess.PIPE ,env=snake_case_ ,) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) UpperCamelCase : List[Any] = [] UpperCamelCase : List[str] = [] def tee(snake_case_ : List[Any] ,snake_case_ : Tuple ,snake_case_ : int ,snake_case_ : str="" ): UpperCamelCase : Tuple = line.decode("""utf-8""" ).rstrip() sink.append(snake_case_ ) if not quiet: print(snake_case_ ,snake_case_ ,file=snake_case_ ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ asyncio.create_task(_read_stream(p.stdout ,lambda snake_case_ : tee(snake_case_ ,snake_case_ ,sys.stdout ,label="""stdout:""" ) ) ), asyncio.create_task(_read_stream(p.stderr ,lambda snake_case_ : tee(snake_case_ ,snake_case_ ,sys.stderr ,label="""stderr:""" ) ) ), ] ,timeout=snake_case_ ,) return _RunOutput(await p.wait() ,snake_case_ ,snake_case_ ) def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Optional[Any]=None ,snake_case_ : Dict=None ,snake_case_ : Any=1_8_0 ,snake_case_ : List[str]=False ,snake_case_ : Optional[Any]=True ): '''simple docstring''' UpperCamelCase : List[str] = asyncio.get_event_loop() UpperCamelCase : Dict = loop.run_until_complete( _stream_subprocess(snake_case_ ,env=snake_case_ ,stdin=snake_case_ ,timeout=snake_case_ ,quiet=snake_case_ ,echo=snake_case_ ) ) UpperCamelCase : int = """ """.join(snake_case_ ) if result.returncode > 0: UpperCamelCase : List[Any] = """\n""".join(result.stderr ) raise RuntimeError( f'\'{cmd_str}\' failed with returncode {result.returncode}\n\n' f'The combined stderr from workers follows:\n{stderr}' ) return result class lowerCamelCase ( _UpperCAmelCase ): pass def A_ ( snake_case_ : List[str] ,snake_case_ : Optional[int]=False ): '''simple docstring''' try: UpperCamelCase : Dict = subprocess.check_output(snake_case_ ,stderr=subprocess.STDOUT ) if return_stdout: if hasattr(snake_case_ ,"""decode""" ): UpperCamelCase : Optional[Any] = output.decode("""utf-8""" ) return output except subprocess.CalledProcessError as e: raise SubprocessCallException( f'Command `{" ".join(snake_case_ )}` failed with the following error:\n\n{e.output.decode()}' ) from e
371
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="last" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=0 , ): UpperCamelCase : Union[str, Any] = parent UpperCamelCase : str = batch_size UpperCamelCase : int = seq_length UpperCamelCase : Optional[Any] = is_training UpperCamelCase : Any = use_input_lengths UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : List[Any] = use_labels UpperCamelCase : Union[str, Any] = gelu_activation UpperCamelCase : Dict = sinusoidal_embeddings UpperCamelCase : Optional[int] = causal UpperCamelCase : List[Any] = asm UpperCamelCase : int = n_langs UpperCamelCase : Optional[Any] = vocab_size UpperCamelCase : str = n_special UpperCamelCase : Dict = hidden_size UpperCamelCase : Union[str, Any] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : int = max_position_embeddings UpperCamelCase : Any = type_sequence_label_size UpperCamelCase : str = initializer_range UpperCamelCase : str = num_labels UpperCamelCase : Union[str, Any] = num_choices UpperCamelCase : List[str] = summary_type UpperCamelCase : int = use_proj UpperCamelCase : List[str] = scope UpperCamelCase : Dict = bos_token_id def a_ ( self ): UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Union[str, Any] = None if self.use_input_lengths: UpperCamelCase : str = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase : Tuple = None if self.use_token_type_ids: UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase : int = None UpperCamelCase : Dict = None UpperCamelCase : str = None if self.use_labels: UpperCamelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Dict = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : List[str] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def a_ ( self ): return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[int] = XLMModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , lengths=SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[Any] = XLMWithLMHeadModel(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : List[str] = XLMForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : int = XLMForQuestionAnswering(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , p_mask=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , ) ((UpperCamelCase) , ) : Union[str, Any] = result_with_labels.to_tuple() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , ) : Tuple = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = XLMForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : int = self.num_labels UpperCamelCase : int = XLMForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : List[Any] = self.num_choices UpperCamelCase : Tuple = XLMForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Optional[Any] = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : int = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : List[Any] = config_and_inputs UpperCamelCase : Dict = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) lowercase : List[Any] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable lowercase : Optional[Any] = ( { 'feature-extraction': XLMModel, 'fill-mask': XLMWithLMHeadModel, 'question-answering': XLMForQuestionAnsweringSimple, 'text-classification': XLMForSequenceClassification, 'text-generation': XLMWithLMHeadModel, 'token-classification': XLMForTokenClassification, 'zero-shot': XLMForSequenceClassification, } if is_torch_available() else {} ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": UpperCamelCase : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) return inputs_dict def a_ ( self ): UpperCamelCase : List[Any] = XLMModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , emb_dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_attentions in attentions] , [True] * len(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : int = min_length + idx + 1 UpperCamelCase : Tuple = min_length + idx + 1 UpperCamelCase : Any = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_hidden_states in hidden_states] , [True] * len(SCREAMING_SNAKE_CASE_ ) , ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : List[str] = min_length + idx + 1 UpperCamelCase : Optional[Any] = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) , ) pass @slow def a_ ( self ): for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : str = XLMModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Dict = XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.tensor([[14, 447]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # the president UpperCamelCase : List[Any] = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference UpperCamelCase : Optional[int] = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , SCREAMING_SNAKE_CASE_ )
27
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A : Dict = { '''configuration_pix2struct''': [ '''PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Pix2StructConfig''', '''Pix2StructTextConfig''', '''Pix2StructVisionConfig''', ], '''processing_pix2struct''': ['''Pix2StructProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = ['''Pix2StructImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = [ '''PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Pix2StructPreTrainedModel''', '''Pix2StructForConditionalGeneration''', '''Pix2StructVisionModel''', '''Pix2StructTextModel''', ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys __A : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
350
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A : int = { '''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = [ '''GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTBigCodeForSequenceClassification''', '''GPTBigCodeForTokenClassification''', '''GPTBigCodeForCausalLM''', '''GPTBigCodeModel''', '''GPTBigCodePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Any = logging.get_logger(__name__) __A : Tuple = { '''distilbert-base-uncased''': '''https://huggingface.co/distilbert-base-uncased/resolve/main/config.json''', '''distilbert-base-uncased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json''' ), '''distilbert-base-cased''': '''https://huggingface.co/distilbert-base-cased/resolve/main/config.json''', '''distilbert-base-cased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json''' ), '''distilbert-base-german-cased''': '''https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json''', '''distilbert-base-multilingual-cased''': ( '''https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json''' ), '''distilbert-base-uncased-finetuned-sst-2-english''': ( '''https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json''' ), } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Dict = 'distilbert' lowercase : str = { 'hidden_size': 'dim', 'num_attention_heads': 'n_heads', 'num_hidden_layers': 'n_layers', } def __init__( self , SCREAMING_SNAKE_CASE_=3_0522 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=4 * 768 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.2 , SCREAMING_SNAKE_CASE_=0 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : List[Any] = vocab_size UpperCamelCase : Optional[Any] = max_position_embeddings UpperCamelCase : List[str] = sinusoidal_pos_embds UpperCamelCase : str = n_layers UpperCamelCase : int = n_heads UpperCamelCase : int = dim UpperCamelCase : List[str] = hidden_dim UpperCamelCase : Optional[int] = dropout UpperCamelCase : int = attention_dropout UpperCamelCase : Dict = activation UpperCamelCase : Any = initializer_range UpperCamelCase : int = qa_dropout UpperCamelCase : Optional[int] = seq_classif_dropout super().__init__(**SCREAMING_SNAKE_CASE_ , pad_token_id=SCREAMING_SNAKE_CASE_ ) class lowerCamelCase ( _UpperCAmelCase ): @property def a_ ( self ): if self.task == "multiple-choice": UpperCamelCase : Tuple = {0: """batch""", 1: """choice""", 2: """sequence"""} else: UpperCamelCase : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
351
"""simple docstring""" import torch from transformers import AutoModel class lowerCamelCase ( torch.nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_="sayef/fsner-bert-base-uncased" ): super(SCREAMING_SNAKE_CASE_ , self ).__init__() UpperCamelCase : int = AutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.nn.CosineSimilarity(3 , 1e-08 ) UpperCamelCase : Any = torch.nn.Softmax(dim=1 ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return self.bert(**SCREAMING_SNAKE_CASE_ ).last_hidden_state def a_ ( self , SCREAMING_SNAKE_CASE_ ): return token_embeddings.sum(2 , keepdim=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1 ): return self.softmax(T * self.cos(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = W_supports["""sizes"""].tolist() UpperCamelCase : List[str] = W_supports["""start_token_id"""].item() UpperCamelCase : List[Any] = W_supports["""end_token_id"""].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCamelCase : List[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = None UpperCamelCase : Optional[Any] = None UpperCamelCase : Tuple = W_supports["""input_ids"""] == start_token_id UpperCamelCase : Optional[Any] = W_supports["""input_ids"""] == end_token_id for i, size in enumerate(SCREAMING_SNAKE_CASE_ ): if i == 0: UpperCamelCase : int = 0 else: UpperCamelCase : Optional[int] = support_sizes[i - 1] UpperCamelCase : Tuple = S[s : s + size][start_token_masks[s : s + size]] UpperCamelCase : int = S[s : s + size][end_token_masks[s : s + size]] UpperCamelCase : Dict = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCamelCase : Tuple = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCamelCase : List[str] = torch.vstack((p_starts, p_start) ) UpperCamelCase : Optional[Any] = torch.vstack((p_ends, p_end) ) else: UpperCamelCase : Optional[int] = p_start UpperCamelCase : Tuple = p_end return p_starts, p_ends
27
0
"""simple docstring""" def A_ ( snake_case_ : List[Any] ,snake_case_ : Any ,snake_case_ : Optional[Any] ,snake_case_ : Dict=None ): '''simple docstring''' UpperCamelCase : str = (path or []) + [u] for v in graph[u]: if visited_edge[u][v] is False: UpperCamelCase : Any = True, True UpperCamelCase : Optional[Any] = dfs(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) return path def A_ ( snake_case_ : List[Any] ,snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : int = 0 UpperCamelCase : Any = -1 for i in range(snake_case_ ): if i not in graph.keys(): continue if len(graph[i] ) % 2 == 1: odd_degree_nodes += 1 UpperCamelCase : int = i if odd_degree_nodes == 0: return 1, odd_node if odd_degree_nodes == 2: return 2, odd_node return 3, odd_node def A_ ( snake_case_ : int ,snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : int = [[False for _ in range(max_node + 1 )] for _ in range(max_node + 1 )] UpperCamelCase : int = check_circuit_or_path(snake_case_ ,snake_case_ ) if check == 3: print("""graph is not Eulerian""" ) print("""no path""" ) return UpperCamelCase : str = 1 if check == 2: UpperCamelCase : Optional[Any] = odd_node print("""graph has a Euler path""" ) if check == 1: print("""graph has a Euler cycle""" ) UpperCamelCase : Tuple = dfs(snake_case_ ,snake_case_ ,snake_case_ ) print(snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : Optional[int] = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]} UpperCamelCase : int = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]} UpperCamelCase : Union[str, Any] = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]} UpperCamelCase : List[Any] = {1: [2, 3], 2: [1, 3], 3: [1, 2]} UpperCamelCase : int = { 1: [], 2: [] # all degree is zero } UpperCamelCase : Any = 1_0 check_euler(snake_case_ ,snake_case_ ) check_euler(snake_case_ ,snake_case_ ) check_euler(snake_case_ ,snake_case_ ) check_euler(snake_case_ ,snake_case_ ) check_euler(snake_case_ ,snake_case_ ) if __name__ == "__main__": main()
352
"""simple docstring""" from typing import Any class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = data UpperCamelCase : Optional[Any] = None def __repr__( self ): return f'Node({self.data})' class lowerCamelCase : def __init__( self ): UpperCamelCase : Dict = None def __iter__( self ): UpperCamelCase : int = self.head while node: yield node.data UpperCamelCase : Union[str, Any] = node.next def __len__( self ): return sum(1 for _ in self ) def __repr__( self ): return "->".join([str(SCREAMING_SNAKE_CASE_ ) for item in self] ) def __getitem__( self , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) UpperCamelCase : List[Any] = self.head for _ in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = current.next UpperCamelCase : Optional[Any] = data def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(len(self ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(0 , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index <= len(self ): raise IndexError("""list index out of range""" ) UpperCamelCase : Optional[Any] = Node(SCREAMING_SNAKE_CASE_ ) if self.head is None: UpperCamelCase : Dict = new_node elif index == 0: UpperCamelCase : Any = self.head # link new_node to head UpperCamelCase : Any = new_node else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : str = temp.next UpperCamelCase : Any = temp.next UpperCamelCase : Optional[Any] = new_node def a_ ( self ): # print every node data print(self ) def a_ ( self ): return self.delete_nth(0 ) def a_ ( self ): # delete from tail return self.delete_nth(len(self ) - 1 ) def a_ ( self , SCREAMING_SNAKE_CASE_ = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("""List index out of range.""" ) UpperCamelCase : Union[str, Any] = self.head # default first node if index == 0: UpperCamelCase : Optional[Any] = self.head.next else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : int = temp.next UpperCamelCase : Optional[Any] = temp.next UpperCamelCase : Dict = temp.next.next return delete_node.data def a_ ( self ): return self.head is None def a_ ( self ): UpperCamelCase : Optional[Any] = None UpperCamelCase : Union[str, Any] = self.head while current: # Store the current node's next node. UpperCamelCase : Optional[int] = current.next # Make the current node's next point backwards UpperCamelCase : Optional[Any] = prev # Make the previous node be the current node UpperCamelCase : int = current # Make the current node the next node (to progress iteration) UpperCamelCase : Optional[int] = next_node # Return prev in order to put the head at the end UpperCamelCase : Optional[int] = prev def A_ ( ): '''simple docstring''' UpperCamelCase : int = LinkedList() assert linked_list.is_empty() is True assert str(snake_case_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(1_0 ): assert len(snake_case_ ) == i linked_list.insert_nth(snake_case_ ,i + 1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_1 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(1_1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(0 ,1_2 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 1_0 assert linked_list.delete_tail() == 1_1 assert len(snake_case_ ) == 9 assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_0 ) ) assert all(linked_list[i] == i + 1 for i in range(0 ,9 ) ) is True for i in range(0 ,9 ): UpperCamelCase : Optional[Any] = -i assert all(linked_list[i] == -i for i in range(0 ,9 ) ) is True linked_list.reverse() assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(-8 ,1 ) ) def A_ ( ): '''simple docstring''' UpperCamelCase : int = [ -9, 1_0_0, Node(7_7_3_4_5_1_1_2 ), """dlrow olleH""", 7, 5_5_5_5, 0, -192.55555, """Hello, world!""", 77.9, Node(1_0 ), None, None, 12.20, ] UpperCamelCase : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(snake_case_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(snake_case_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head UpperCamelCase : Dict = linked_list.delete_head() assert result == -9 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail UpperCamelCase : int = linked_list.delete_tail() assert result == 12.2 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list UpperCamelCase : Optional[Any] = linked_list.delete_nth(1_0 ) assert result is None assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("""Hello again, world!""" ) ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(snake_case_ ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(snake_case_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def A_ ( ): '''simple docstring''' from doctest import testmod testmod() UpperCamelCase : List[Any] = LinkedList() linked_list.insert_head(input("""Inserting 1st at head """ ).strip() ) linked_list.insert_head(input("""Inserting 2nd at head """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() linked_list.insert_tail(input("""\nInserting 1st at tail """ ).strip() ) linked_list.insert_tail(input("""Inserting 2nd at tail """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() print("""\nDelete head""" ) linked_list.delete_head() print("""Delete tail""" ) linked_list.delete_tail() print("""\nPrint list:""" ) linked_list.print_list() print("""\nReverse linked list""" ) linked_list.reverse() print("""\nPrint list:""" ) linked_list.print_list() print("""\nString representation of linked list:""" ) print(snake_case_ ) print("""\nReading/changing Node data using indexing:""" ) print(f'Element at Position 1: {linked_list[1]}' ) UpperCamelCase : List[Any] = input("""Enter New Value: """ ).strip() print("""New list:""" ) print(snake_case_ ) print(f'length of linked_list is : {len(snake_case_ )}' ) if __name__ == "__main__": main()
27
0
"""simple docstring""" import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets __A : Optional[int] = datasets.logging.get_logger(__name__) __A : Tuple = '''\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh}, booktitle={ACL}, year={2020}, url={https://arxiv.org/abs/2004.04696} } ''' __A : Dict = '''\ BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018) and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune it for your specific application (the latter is expected to perform better). See the project\'s README at https://github.com/google-research/bleurt#readme for more information. ''' __A : Any = ''' BLEURT score. Args: `predictions` (list of str): prediction/candidate sentences `references` (list of str): reference sentences `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None. Returns: \'scores\': List of scores. Examples: >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> bleurt = datasets.load_metric("bleurt") >>> results = bleurt.compute(predictions=predictions, references=references) >>> print([round(v, 2) for v in results["scores"]]) [1.03, 1.04] ''' __A : List[str] = { '''bleurt-tiny-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip''', '''bleurt-tiny-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip''', '''bleurt-base-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip''', '''bleurt-base-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip''', '''bleurt-large-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip''', '''bleurt-large-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip''', '''BLEURT-20-D3''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip''', '''BLEURT-20-D6''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip''', '''BLEURT-20-D12''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip''', '''BLEURT-20''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip''', } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase ( datasets.Metric ): def a_ ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://github.com/google-research/bleurt""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/google-research/bleurt"""] , reference_urls=["""https://github.com/google-research/bleurt""", """https://arxiv.org/abs/2004.04696"""] , ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): # check that config name specifies a valid BLEURT model if self.config_name == "default": logger.warning( """Using default BLEURT-Base checkpoint for sequence maximum length 128. """ """You can use a bigger model for better results with e.g.: datasets.load_metric('bleurt', 'bleurt-large-512').""" ) UpperCamelCase : Dict = """bleurt-base-128""" if self.config_name.lower() in CHECKPOINT_URLS: UpperCamelCase : int = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: UpperCamelCase : Tuple = self.config_name.upper() else: raise KeyError( f'{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}' ) # download the model checkpoint specified by self.config_name and set up the scorer UpperCamelCase : Any = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) UpperCamelCase : Optional[int] = score.BleurtScorer(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = self.scorer.score(references=SCREAMING_SNAKE_CASE_ , candidates=SCREAMING_SNAKE_CASE_ ) return {"scores": scores}
353
"""simple docstring""" import argparse import os import re __A : Dict = '''src/diffusers''' # Pattern that looks at the indentation in a line. __A : Union[str, Any] = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : Tuple = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Tuple = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Union[str, Any] = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Dict="" ,snake_case_ : Dict=None ,snake_case_ : Any=None ): '''simple docstring''' UpperCamelCase : Optional[int] = 0 UpperCamelCase : List[Any] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Optional[Any] = ["""\n""".join(lines[:index] )] else: UpperCamelCase : int = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Any = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Any = [lines[index + 1]] index += 1 else: UpperCamelCase : List[str] = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' def _inner(snake_case_ : Tuple ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[int]=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Dict ): return x if key is None: UpperCamelCase : int = noop # Constants are all uppercase, they go first. UpperCamelCase : List[Any] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : str = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : List[str] = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Tuple = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : int ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : List[Any] ): UpperCamelCase : Any = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : Union[str, Any] = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[str] = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : str = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : str = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Dict = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : int = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[Any] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : Optional[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[Any] = keys[:-1] UpperCamelCase : int = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Tuple ,snake_case_ : str=True ): '''simple docstring''' with open(snake_case_ ,"""r""" ) as f: UpperCamelCase : int = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : Dict = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Optional[Any] = main_blocks[block_idx] UpperCamelCase : Optional[int] = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : Union[str, Any] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : List[str] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Dict = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Union[str, Any] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : Optional[int] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Union[str, Any] = _re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Union[str, Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Optional[Any] = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : List[Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[Any] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: UpperCamelCase : str = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Any = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Union[str, Any] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : Any = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Any = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : str = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
0
"""simple docstring""" from typing import List, Optional, Union import numpy as np from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging __A : Dict = logging.get_logger(__name__) class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = ['input_values', 'padding_mask'] def __init__( self , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 2_4000 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(feature_size=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , padding_value=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = chunk_length_s UpperCamelCase : List[Any] = overlap @property def a_ ( self ): if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def a_ ( self ): if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided audio input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) if padding and truncation: raise ValueError("""Both padding and truncation were set. Make sure you only set one.""" ) elif padding is None: # by default let's pad the inputs UpperCamelCase : Optional[int] = True UpperCamelCase : Union[str, Any] = bool( isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and (isinstance(raw_audio[0] , (np.ndarray, tuple, list) )) ) if is_batched: UpperCamelCase : List[Any] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ).T for audio in raw_audio] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): UpperCamelCase : Optional[int] = np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) elif isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and raw_audio.dtype is np.dtype(np.floataa ): UpperCamelCase : Any = raw_audio.astype(np.floataa ) # always return batch if not is_batched: UpperCamelCase : Any = [np.asarray(SCREAMING_SNAKE_CASE_ ).T] # verify inputs are valid for idx, example in enumerate(SCREAMING_SNAKE_CASE_ ): if example.ndim > 2: raise ValueError(f'Expected input shape (channels, length) but got shape {example.shape}' ) if self.feature_size == 1 and example.ndim != 1: raise ValueError(f'Expected mono audio but example has {example.shape[-1]} channels' ) if self.feature_size == 2 and example.shape[-1] != 2: raise ValueError(f'Expected stereo audio but example has {example.shape[-1]} channels' ) UpperCamelCase : List[Any] = None UpperCamelCase : Dict = BatchFeature({"""input_values""": raw_audio} ) if self.chunk_stride is not None and self.chunk_length is not None and max_length is None: if truncation: UpperCamelCase : Tuple = min(array.shape[0] for array in raw_audio ) UpperCamelCase : List[str] = int(np.floor(max_length / self.chunk_stride ) ) UpperCamelCase : str = (nb_step - 1) * self.chunk_stride + self.chunk_length elif padding: UpperCamelCase : int = max(array.shape[0] for array in raw_audio ) UpperCamelCase : str = int(np.ceil(max_length / self.chunk_stride ) ) UpperCamelCase : Optional[int] = (nb_step - 1) * self.chunk_stride + self.chunk_length UpperCamelCase : int = """max_length""" else: UpperCamelCase : List[str] = input_values # normal padding on batch if padded_inputs is None: UpperCamelCase : List[Any] = self.pad( SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ) if padding: UpperCamelCase : int = padded_inputs.pop("""attention_mask""" ) UpperCamelCase : Optional[Any] = [] for example in padded_inputs.pop("""input_values""" ): if self.feature_size == 1: UpperCamelCase : Union[str, Any] = example[..., None] input_values.append(example.T ) UpperCamelCase : Dict = input_values if return_tensors is not None: UpperCamelCase : Any = padded_inputs.convert_to_tensors(SCREAMING_SNAKE_CASE_ ) return padded_inputs
354
"""simple docstring""" def A_ ( snake_case_ : list[int] ): '''simple docstring''' if not numbers: return 0 if not isinstance(snake_case_ ,(list, tuple) ) or not all( isinstance(snake_case_ ,snake_case_ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) UpperCamelCase : int = numbers[0] for i in range(1 ,len(snake_case_ ) ): # update the maximum and minimum subarray products UpperCamelCase : List[str] = numbers[i] if number < 0: UpperCamelCase , UpperCamelCase : Optional[int] = min_till_now, max_till_now UpperCamelCase : Dict = max(snake_case_ ,max_till_now * number ) UpperCamelCase : Union[str, Any] = min(snake_case_ ,min_till_now * number ) # update the maximum product found till now UpperCamelCase : Union[str, Any] = max(snake_case_ ,snake_case_ ) return max_prod
27
0
"""simple docstring""" import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging __A : int = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , ) def a_ ( self , SCREAMING_SNAKE_CASE_ = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase : Union[str, Any] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = len(SCREAMING_SNAKE_CASE_ ) else: raise ValueError(f'`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE_ )}' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f'`height` and `width` have to be divisible by 8 but are {height} and {width}.' ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or callback_steps <= 0) ): raise ValueError( f'`callback_steps` has to be a positive integer but is {callback_steps} of type' f' {type(SCREAMING_SNAKE_CASE_ )}.' ) # get prompt text embeddings UpperCamelCase : Optional[Any] = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) UpperCamelCase : Optional[Any] = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: UpperCamelCase : Tuple = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) 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}' ) UpperCamelCase : str = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: UpperCamelCase : Union[str, Any] = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method UpperCamelCase : Optional[Any] = text_embeddings.shape UpperCamelCase : Optional[Any] = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase : Optional[Any] = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. UpperCamelCase : Dict = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: UpperCamelCase : List[str] if negative_prompt is None: UpperCamelCase : Any = [""""""] elif type(SCREAMING_SNAKE_CASE_ ) is not type(SCREAMING_SNAKE_CASE_ ): raise TypeError( f'`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE_ )} !=' f' {type(SCREAMING_SNAKE_CASE_ )}.' ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( f'`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE_ )}, but `prompt`:' f' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches' """ the batch size of `prompt`.""" ) else: UpperCamelCase : str = negative_prompt UpperCamelCase : Tuple = text_input_ids.shape[-1] UpperCamelCase : Dict = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Tuple = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method UpperCamelCase : Optional[Any] = uncond_embeddings.shape[1] UpperCamelCase : str = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase : str = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # 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 UpperCamelCase : Optional[int] = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. UpperCamelCase : Union[str, Any] = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) UpperCamelCase : Optional[Any] = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) UpperCamelCase : List[str] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps UpperCamelCase : Any = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to(self.device ) UpperCamelCase : Tuple = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: UpperCamelCase : Any = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents_reference.shape != latents_shape: raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {latents_shape}' ) UpperCamelCase : Tuple = latents_reference.to(self.device ) UpperCamelCase : Union[str, Any] = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images UpperCamelCase : str = (latents_shape[3] - latents_shape_reference[3]) // 2 UpperCamelCase : Union[str, Any] = (latents_shape[2] - latents_shape_reference[2]) // 2 UpperCamelCase : Tuple = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx UpperCamelCase : Optional[int] = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy UpperCamelCase : int = 0 if dx < 0 else dx UpperCamelCase : Union[str, Any] = 0 if dy < 0 else dy UpperCamelCase : List[Any] = max(-dx , 0 ) UpperCamelCase : Union[str, Any] = max(-dy , 0 ) # import pdb # pdb.set_trace() UpperCamelCase : List[str] = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand UpperCamelCase : List[Any] = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase : Any = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase : Dict = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase : Any = {} if accepts_eta: UpperCamelCase : List[Any] = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance UpperCamelCase : str = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase : Tuple = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase : int = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform guidance if do_classifier_free_guidance: UpperCamelCase : Tuple = noise_pred.chunk(2 ) UpperCamelCase : Tuple = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase : Dict = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = 1 / 0.18215 * latents UpperCamelCase : Dict = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase : Optional[int] = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 UpperCamelCase : int = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: UpperCamelCase : Any = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).to( self.device ) UpperCamelCase : Optional[int] = self.safety_checker( images=SCREAMING_SNAKE_CASE_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: UpperCamelCase : List[str] = None if output_type == "pil": UpperCamelCase : List[Any] = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
355
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Any = AudioLDMPipeline lowercase : Union[str, Any] = TEXT_TO_AUDIO_PARAMS lowercase : List[str] = TEXT_TO_AUDIO_BATCH_PARAMS lowercase : Tuple = frozenset( [ 'num_inference_steps', 'num_waveforms_per_prompt', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=(32, 64) , class_embed_type="""simple_projection""" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[Any] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , ) torch.manual_seed(0 ) UpperCamelCase : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCamelCase : int = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) UpperCamelCase : Optional[int] = ClapTextModelWithProjection(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta""" , model_max_length=77 ) UpperCamelCase : Tuple = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """vocoder""": vocoder, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Any = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """prompt""": """A hammer hitting a wooden surface""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, } return inputs def a_ ( self ): UpperCamelCase : str = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Any = self.get_dummy_components() UpperCamelCase : int = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Tuple = audio[:10] UpperCamelCase : Dict = np.array( [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[str] = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Optional[int] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) UpperCamelCase : Tuple = prompt_embeds # forward UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : List[str] = self.get_dummy_components() UpperCamelCase : List[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * ["""this is a negative prompt"""] UpperCamelCase : List[Any] = negative_prompt UpperCamelCase : str = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : str = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] UpperCamelCase : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[Any] = [] for p in [prompt, negative_prompt]: UpperCamelCase : int = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Union[str, Any] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = text_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) embeds.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Tuple = embeds # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Optional[int] = self.get_dummy_components() UpperCamelCase : List[str] = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = """egg cracking""" UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Union[str, Any] = audio[:10] UpperCamelCase : Dict = np.array( [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Union[str, Any] = self.get_dummy_components() UpperCamelCase : Tuple = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = """A hammer hitting a wooden surface""" # test num_waveforms_per_prompt=1 (default) UpperCamelCase : List[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts UpperCamelCase : Dict = 2 UpperCamelCase : List[str] = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt UpperCamelCase : List[str] = 2 UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts UpperCamelCase : Any = 2 UpperCamelCase : str = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = audioldm_pipe.vocoder.config.sampling_rate UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe(audio_length_in_s=0.016 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.016 UpperCamelCase : Optional[Any] = audioldm_pipe(audio_length_in_s=0.032 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.032 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Optional[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = ["""hey"""] UpperCamelCase : Dict = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : str = output.audios.shape assert audio_shape == (1, 256) UpperCamelCase : Optional[Any] = audioldm_pipe.vocoder.config config.model_in_dim *= 2 UpperCamelCase : str = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : List[str] = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def a_ ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self._test_inference_batch_single_identical(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def a_ ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @slow class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="cpu" , SCREAMING_SNAKE_CASE_=torch.floataa , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : str = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = np.random.RandomState(SCREAMING_SNAKE_CASE_ ).standard_normal((1, 8, 128, 16) ) UpperCamelCase : int = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = { """prompt""": """A hammer hitting a wooden surface""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 2.5, } return inputs def a_ ( self ): UpperCamelCase : Optional[int] = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = 25 UpperCamelCase : Optional[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[7_7230:7_7240] UpperCamelCase : Optional[Any] = np.array( [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] ) UpperCamelCase : Any = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def a_ ( self ): UpperCamelCase : Any = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : Any = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) UpperCamelCase : str = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[2_7780:2_7790] UpperCamelCase : Tuple = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] ) UpperCamelCase : Tuple = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
27
0
"""simple docstring""" def A_ ( snake_case_ : str ): '''simple docstring''' if not all(char in """01""" for char in bin_string ): raise ValueError("""Non-binary value was passed to the function""" ) if not bin_string: raise ValueError("""Empty string was passed to the function""" ) UpperCamelCase : Any = """""" while len(snake_case_ ) % 3 != 0: UpperCamelCase : List[str] = """0""" + bin_string UpperCamelCase : Tuple = [ bin_string[index : index + 3] for index in range(len(snake_case_ ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: UpperCamelCase : int = 0 for index, val in enumerate(snake_case_ ): oct_val += int(2 ** (2 - index) * int(snake_case_ ) ) oct_string += str(snake_case_ ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
356
"""simple docstring""" import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def A_ ( snake_case_ : Dataset ,snake_case_ : Dict[str, str] ): '''simple docstring''' UpperCamelCase : List[str] = args.log_outputs UpperCamelCase : Tuple = """_""".join(args.dataset.split("""/""" ) + [args.config, args.split] ) # load metric UpperCamelCase : List[Any] = load_metric("""wer""" ) UpperCamelCase : Any = load_metric("""cer""" ) # compute metrics UpperCamelCase : str = wer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) UpperCamelCase : Dict = cer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) # print & log results UpperCamelCase : Optional[int] = f'WER: {wer_result}\nCER: {cer_result}' print(snake_case_ ) with open(f'{dataset_id}_eval_results.txt' ,"""w""" ) as f: f.write(snake_case_ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: UpperCamelCase : Optional[Any] = f'log_{dataset_id}_predictions.txt' UpperCamelCase : str = f'log_{dataset_id}_targets.txt' with open(snake_case_ ,"""w""" ) as p, open(snake_case_ ,"""w""" ) as t: # mapping function to write output def write_to_file(snake_case_ : Union[str, Any] ,snake_case_ : Tuple ): p.write(f'{i}' + """\n""" ) p.write(batch["""prediction"""] + """\n""" ) t.write(f'{i}' + """\n""" ) t.write(batch["""target"""] + """\n""" ) result.map(snake_case_ ,with_indices=snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Dict = """[,?.!\-\;\:\"“%‘”�—’…–]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training UpperCamelCase : str = re.sub(snake_case_ ,"""""" ,text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! UpperCamelCase : List[str] = ["""\n\n""", """\n""", """ """, """ """] for t in token_sequences_to_ignore: UpperCamelCase : Tuple = """ """.join(text.split(snake_case_ ) ) return text def A_ ( snake_case_ : str ): '''simple docstring''' # load dataset UpperCamelCase : Union[str, Any] = load_dataset(args.dataset ,args.config ,split=args.split ,use_auth_token=snake_case_ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor UpperCamelCase : List[Any] = AutoFeatureExtractor.from_pretrained(args.model_id ) UpperCamelCase : Dict = feature_extractor.sampling_rate # resample audio UpperCamelCase : Optional[Any] = dataset.cast_column("""audio""" ,Audio(sampling_rate=snake_case_ ) ) # load eval pipeline if args.device is None: UpperCamelCase : int = 0 if torch.cuda.is_available() else -1 UpperCamelCase : Union[str, Any] = pipeline("""automatic-speech-recognition""" ,model=args.model_id ,device=args.device ) # map function to decode audio def map_to_pred(snake_case_ : Union[str, Any] ): UpperCamelCase : List[Any] = asr( batch["""audio"""]["""array"""] ,chunk_length_s=args.chunk_length_s ,stride_length_s=args.stride_length_s ) UpperCamelCase : Union[str, Any] = prediction["""text"""] UpperCamelCase : Optional[Any] = normalize_text(batch["""sentence"""] ) return batch # run inference on all examples UpperCamelCase : Any = dataset.map(snake_case_ ,remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(snake_case_ ,snake_case_ ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() parser.add_argument( '''--model_id''', type=str, required=True, help='''Model identifier. Should be loadable with 🤗 Transformers''' ) parser.add_argument( '''--dataset''', type=str, required=True, help='''Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets''', ) parser.add_argument( '''--config''', type=str, required=True, help='''Config of the dataset. *E.g.* `\'en\'` for Common Voice''' ) parser.add_argument('''--split''', type=str, required=True, help='''Split of the dataset. *E.g.* `\'test\'`''') parser.add_argument( '''--chunk_length_s''', type=float, default=None, help='''Chunk length in seconds. Defaults to 5 seconds.''' ) parser.add_argument( '''--stride_length_s''', type=float, default=None, help='''Stride of the audio chunks. Defaults to 1 second.''' ) parser.add_argument( '''--log_outputs''', action='''store_true''', help='''If defined, write outputs to log file for analysis.''' ) parser.add_argument( '''--device''', type=int, default=None, help='''The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.''', ) __A : Optional[Any] = parser.parse_args() main(args)
27
0
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": __A : Optional[Any] = pd.read_csv('''sample_data.csv''', header=None) __A : List[Any] = df.shape[:1][0] # If you're using some other dataset input the target column __A : Dict = df.iloc[:, 1:2] __A : List[str] = actual_data.values.reshape(len_data, 1) __A : List[str] = MinMaxScaler().fit_transform(actual_data) __A : List[str] = 10 __A : Optional[int] = 5 __A : Optional[int] = 20 __A : Optional[Any] = len_data - periods * look_back __A : int = actual_data[:division] __A : int = actual_data[division - look_back :] __A : Dict = [], [] __A : Tuple = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) __A : List[Any] = np.array(train_x) __A : str = np.array(test_x) __A : Dict = np.array([list(i.ravel()) for i in train_y]) __A : int = np.array([list(i.ravel()) for i in test_y]) __A : Optional[Any] = Sequential() model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(128, 1))) model.add(Dense(forward_days)) model.compile(loss='''mean_squared_error''', optimizer='''adam''') __A : Union[str, Any] = model.fit( x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4 ) __A : Union[str, Any] = model.predict(x_test)
357
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'EncodecFeatureExtractor' lowercase : List[Any] = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.feature_extractor UpperCamelCase : Any = False def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True ): return self.tokenizer.get_decoder_prompt_ids(task=SCREAMING_SNAKE_CASE_ , language=SCREAMING_SNAKE_CASE_ , no_timestamps=SCREAMING_SNAKE_CASE_ ) def __call__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = kwargs.pop("""sampling_rate""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Any = args[0] UpperCamelCase : str = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if text is not None: UpperCamelCase : Optional[int] = self.tokenizer(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is not None: UpperCamelCase : str = self.feature_extractor(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is None: return inputs elif text is None: return audio_inputs else: UpperCamelCase : int = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: UpperCamelCase : Optional[Any] = audio_inputs["""padding_mask"""] return inputs def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = kwargs.pop("""padding_mask""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Optional[int] = args[0] UpperCamelCase : Any = args[1:] if audio_values is not None: return self._decode_audio(SCREAMING_SNAKE_CASE_ , padding_mask=SCREAMING_SNAKE_CASE_ ) else: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = to_numpy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase : int = audio_values.shape if padding_mask is None: return list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = to_numpy(SCREAMING_SNAKE_CASE_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) UpperCamelCase : List[str] = seq_len - padding_mask.shape[-1] UpperCamelCase : Optional[int] = 1 - self.feature_extractor.padding_value UpperCamelCase : Any = np.pad(SCREAMING_SNAKE_CASE_ , ((0, 0), (0, difference)) , """constant""" , constant_values=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audio_values.tolist() for i in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] UpperCamelCase : Optional[Any] = sliced_audio.reshape(SCREAMING_SNAKE_CASE_ , -1 ) return audio_values
27
0
"""simple docstring""" __A : dict[tuple[int, int, int], int] = {} def A_ ( snake_case_ : int ,snake_case_ : int ,snake_case_ : int ): '''simple docstring''' # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on UpperCamelCase : str = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one UpperCamelCase : Dict = _calculate(days - 1 ,snake_case_ ,late + 1 ) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 UpperCamelCase : Dict = _calculate(days - 1 ,absent + 1 ,0 ) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter UpperCamelCase : Any = _calculate(days - 1 ,snake_case_ ,0 ) UpperCamelCase : str = state_late + state_absent + state_ontime UpperCamelCase : int = prizestrings return prizestrings def A_ ( snake_case_ : int = 3_0 ): '''simple docstring''' return _calculate(snake_case_ ,absent=0 ,late=0 ) if __name__ == "__main__": print(solution())
358
"""simple docstring""" import requests from bsa import BeautifulSoup def A_ ( snake_case_ : str = "https://www.worldometers.info/coronavirus" ): '''simple docstring''' UpperCamelCase : Any = BeautifulSoup(requests.get(snake_case_ ).text ,"""html.parser""" ) UpperCamelCase : Optional[int] = soup.findAll("""h1""" ) UpperCamelCase : List[Any] = soup.findAll("""div""" ,{"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" ,{"""class""": """panel-title"""} ) values += soup.findAll("""div""" ,{"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(snake_case_ ,snake_case_ )} if __name__ == "__main__": print('''\033[1m''' + '''COVID-19 Status of the World''' + '''\033[0m\n''') for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
27
0
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): UpperCamelCase : Optional[Any] = """laion/clap-htsat-unfused""" UpperCamelCase : Tuple = tempfile.mkdtemp() def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return RobertaTokenizer.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return ClapFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE_ ) def a_ ( self ): shutil.rmtree(self.tmpdirname ) def a_ ( self ): UpperCamelCase : Any = self.get_tokenizer() UpperCamelCase : Any = self.get_feature_extractor() UpperCamelCase : List[Any] = ClapProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase : Optional[Any] = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE_ ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase : Union[str, Any] = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) UpperCamelCase : Any = self.get_feature_extractor(do_normalize=SCREAMING_SNAKE_CASE_ , padding_value=1.0 ) UpperCamelCase : str = ClapProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=SCREAMING_SNAKE_CASE_ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE_ ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : str = self.get_feature_extractor() UpperCamelCase : int = self.get_tokenizer() UpperCamelCase : Optional[int] = ClapProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = floats_list((3, 1000) ) UpperCamelCase : Optional[Any] = feature_extractor(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ) UpperCamelCase : Union[str, Any] = processor(audios=SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a_ ( self ): UpperCamelCase : List[Any] = self.get_feature_extractor() UpperCamelCase : Optional[int] = self.get_tokenizer() UpperCamelCase : int = ClapProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = """This is a test string""" UpperCamelCase : Dict = processor(text=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = tokenizer(SCREAMING_SNAKE_CASE_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def a_ ( self ): UpperCamelCase : Optional[int] = self.get_feature_extractor() UpperCamelCase : List[Any] = self.get_tokenizer() UpperCamelCase : Any = ClapProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] UpperCamelCase : List[str] = processor.batch_decode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[int] = self.get_feature_extractor() UpperCamelCase : Dict = self.get_tokenizer() UpperCamelCase : Optional[int] = ClapProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg="""`processor` and `feature_extractor` model input names do not match""" , )
359
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=1 , ): UpperCamelCase : Tuple = parent UpperCamelCase : Optional[int] = batch_size UpperCamelCase : Optional[Any] = seq_length UpperCamelCase : int = is_training UpperCamelCase : Union[str, Any] = use_input_mask UpperCamelCase : Union[str, Any] = use_token_type_ids UpperCamelCase : Dict = use_labels UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : Tuple = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : int = intermediate_size UpperCamelCase : str = hidden_act UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Optional[Any] = type_vocab_size UpperCamelCase : int = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : Dict = num_labels UpperCamelCase : Tuple = num_choices UpperCamelCase : Optional[int] = scope UpperCamelCase : List[Any] = q_groups UpperCamelCase : Tuple = k_groups UpperCamelCase : Any = v_groups UpperCamelCase : List[str] = post_attention_groups UpperCamelCase : Tuple = intermediate_groups UpperCamelCase : int = output_groups def a_ ( self ): UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Tuple = None if self.use_input_mask: UpperCamelCase : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Optional[int] = None UpperCamelCase : List[Any] = None UpperCamelCase : Dict = None if self.use_labels: UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self ): return SqueezeBertConfig( embedding_size=self.hidden_size , vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = SqueezeBertModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = SqueezeBertForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = SqueezeBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : str = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.num_labels UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.num_labels UpperCamelCase : str = SqueezeBertForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = self.num_choices UpperCamelCase : Tuple = SqueezeBertForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = config_and_inputs UpperCamelCase : Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) lowercase : Dict = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) lowercase : Dict = False lowercase : str = True lowercase : str = False def a_ ( self ): UpperCamelCase : Any = SqueezeBertModelTester(self ) UpperCamelCase : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Optional[Any] = SqueezeBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_sentencepiece @require_tokenizers @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification.from_pretrained("""squeezebert/squeezebert-mnli""" ) UpperCamelCase : Dict = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]] ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[Any] = torch.Size((1, 3) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
27
0
"""simple docstring""" import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 __A : Optional[int] = sys.version_info >= (3, 10) def A_ ( snake_case_ : Optional[Any]=None ,snake_case_ : List[Any]=None ): '''simple docstring''' return field(default_factory=lambda: default ,metadata=snake_case_ ) @dataclass class lowerCamelCase : lowercase : int lowercase : float lowercase : str lowercase : bool @dataclass class lowerCamelCase : lowercase : int = 4_2 lowercase : str = field(default='toto' , metadata={'help': 'help message'} ) @dataclass class lowerCamelCase : lowercase : bool = False lowercase : bool = True lowercase : Optional[bool] = None class lowerCamelCase ( _UpperCAmelCase ): lowercase : Any = 'titi' lowercase : Optional[Any] = 'toto' class lowerCamelCase ( _UpperCAmelCase ): lowercase : Any = 'titi' lowercase : Optional[Any] = 'toto' lowercase : int = 4_2 @dataclass class lowerCamelCase : lowercase : BasicEnum = "toto" def a_ ( self ): UpperCamelCase : str = BasicEnum(self.foo ) @dataclass class lowerCamelCase : lowercase : MixedTypeEnum = "toto" def a_ ( self ): UpperCamelCase : Dict = MixedTypeEnum(self.foo ) @dataclass class lowerCamelCase : lowercase : Optional[int] = None lowercase : Optional[float] = field(default=_UpperCAmelCase , metadata={'help': 'help message'} ) lowercase : Optional[str] = None lowercase : Optional[List[str]] = list_field(default=[] ) lowercase : Optional[List[int]] = list_field(default=[] ) @dataclass class lowerCamelCase : lowercase : List[int] = list_field(default=[] ) lowercase : List[int] = list_field(default=[1, 2, 3] ) lowercase : List[str] = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) lowercase : List[float] = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class lowerCamelCase : lowercase : List[int] = field() lowercase : str = field() lowercase : BasicEnum = field() def a_ ( self ): UpperCamelCase : Dict = BasicEnum(self.required_enum ) @dataclass class lowerCamelCase : lowercase : int lowercase : "BasicEnum" = field() lowercase : "Optional[bool]" = None lowercase : "str" = field(default='toto' , metadata={'help': 'help message'} ) lowercase : "List[str]" = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) if is_python_no_less_than_3_10: @dataclass class lowerCamelCase : lowercase : bool = False lowercase : bool = True lowercase : bool | None = None @dataclass class lowerCamelCase : lowercase : int | None = None lowercase : float | None = field(default=_UpperCAmelCase , metadata={'help': 'help message'} ) lowercase : str | None = None lowercase : list[str] | None = list_field(default=[] ) lowercase : list[int] | None = list_field(default=[] ) class lowerCamelCase ( unittest.TestCase ): def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): UpperCamelCase : List[str] = {k: v for k, v in vars(SCREAMING_SNAKE_CASE_ ).items() if k != """container"""} UpperCamelCase : int = {k: v for k, v in vars(SCREAMING_SNAKE_CASE_ ).items() if k != """container"""} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("""choices""" , SCREAMING_SNAKE_CASE_ ) and yy.get("""choices""" , SCREAMING_SNAKE_CASE_ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["""type"""](SCREAMING_SNAKE_CASE_ ) , yy["""type"""](SCREAMING_SNAKE_CASE_ ) ) del xx["type"], yy["type"] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=SCREAMING_SNAKE_CASE_ , required=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--bar""" , type=SCREAMING_SNAKE_CASE_ , required=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--baz""" , type=SCREAMING_SNAKE_CASE_ , required=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--flag""" , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ , const=SCREAMING_SNAKE_CASE_ , nargs="""?""" ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = ["""--foo""", """1""", """--baz""", """quux""", """--bar""", """0.5"""] (UpperCamelCase ) : Optional[Any] = parser.parse_args_into_dataclasses(SCREAMING_SNAKE_CASE_ , look_for_args_file=SCREAMING_SNAKE_CASE_ ) self.assertFalse(example.flag ) def a_ ( self ): UpperCamelCase : Tuple = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=42 , type=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--baz""" , default="""toto""" , type=SCREAMING_SNAKE_CASE_ , help="""help message""" ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ , const=SCREAMING_SNAKE_CASE_ , nargs="""?""" ) expected.add_argument("""--baz""" , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ , const=SCREAMING_SNAKE_CASE_ , nargs="""?""" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("""--no_baz""" , action="""store_false""" , default=SCREAMING_SNAKE_CASE_ , dest="""baz""" ) expected.add_argument("""--opt""" , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(SCREAMING_SNAKE_CASE_ ) for dataclass_type in dataclass_types: UpperCamelCase : Optional[Any] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = parser.parse_args([] ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo=SCREAMING_SNAKE_CASE_ , baz=SCREAMING_SNAKE_CASE_ , opt=SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Tuple = parser.parse_args(["""--foo""", """--no_baz"""] ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo=SCREAMING_SNAKE_CASE_ , baz=SCREAMING_SNAKE_CASE_ , opt=SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Optional[int] = parser.parse_args(["""--foo""", """--baz"""] ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo=SCREAMING_SNAKE_CASE_ , baz=SCREAMING_SNAKE_CASE_ , opt=SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Union[str, Any] = parser.parse_args(["""--foo""", """True""", """--baz""", """True""", """--opt""", """True"""] ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo=SCREAMING_SNAKE_CASE_ , baz=SCREAMING_SNAKE_CASE_ , opt=SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Optional[int] = parser.parse_args(["""--foo""", """False""", """--baz""", """False""", """--opt""", """False"""] ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo=SCREAMING_SNAKE_CASE_ , baz=SCREAMING_SNAKE_CASE_ , opt=SCREAMING_SNAKE_CASE_ ) ) def a_ ( self ): UpperCamelCase : Optional[int] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=["""titi""", """toto""", 42] , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) UpperCamelCase : Optional[Any] = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) UpperCamelCase : int = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) UpperCamelCase : Optional[int] = parser.parse_args_into_dataclasses(["""--foo""", """titi"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) UpperCamelCase : str = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) UpperCamelCase : Optional[int] = parser.parse_args_into_dataclasses(["""--foo""", """42"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def a_ ( self ): @dataclass class lowerCamelCase : lowercase : Literal["titi", "toto", 4_2] = "toto" UpperCamelCase : Optional[Any] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=("""titi""", """toto""", 42) , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) UpperCamelCase : Optional[int] = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) UpperCamelCase : int = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) def a_ ( self ): UpperCamelCase : str = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = argparse.ArgumentParser() expected.add_argument("""--foo_int""" , nargs="""+""" , default=[] , type=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--bar_int""" , nargs="""+""" , default=[1, 2, 3] , type=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--foo_float""" , nargs="""+""" , default=[0.1, 0.2, 0.3] , type=SCREAMING_SNAKE_CASE_ ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = parser.parse_args([] ) self.assertEqual( SCREAMING_SNAKE_CASE_ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["""Hallo""", """Bonjour""", """Hello"""] , foo_float=[0.1, 0.2, 0.3] ) , ) UpperCamelCase : Optional[Any] = parser.parse_args("""--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7""".split() ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["""a""", """b""", """c"""] , foo_float=[0.1, 0.7] ) ) def a_ ( self ): UpperCamelCase : Dict = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=SCREAMING_SNAKE_CASE_ , type=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--bar""" , default=SCREAMING_SNAKE_CASE_ , type=SCREAMING_SNAKE_CASE_ , help="""help message""" ) expected.add_argument("""--baz""" , default=SCREAMING_SNAKE_CASE_ , type=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--ces""" , nargs="""+""" , default=[] , type=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--des""" , nargs="""+""" , default=[] , type=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(SCREAMING_SNAKE_CASE_ ) for dataclass_type in dataclass_types: UpperCamelCase : List[Any] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = parser.parse_args([] ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo=SCREAMING_SNAKE_CASE_ , bar=SCREAMING_SNAKE_CASE_ , baz=SCREAMING_SNAKE_CASE_ , ces=[] , des=[] ) ) UpperCamelCase : int = parser.parse_args("""--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3""".split() ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo=12 , bar=3.14 , baz="""42""" , ces=["""a""", """b""", """c"""] , des=[1, 2, 3] ) ) def a_ ( self ): UpperCamelCase : List[Any] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = argparse.ArgumentParser() expected.add_argument("""--required_list""" , nargs="""+""" , type=SCREAMING_SNAKE_CASE_ , required=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--required_str""" , type=SCREAMING_SNAKE_CASE_ , required=SCREAMING_SNAKE_CASE_ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=SCREAMING_SNAKE_CASE_ , ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=SCREAMING_SNAKE_CASE_ , required=SCREAMING_SNAKE_CASE_ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=SCREAMING_SNAKE_CASE_ , ) expected.add_argument("""--opt""" , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--baz""" , default="""toto""" , type=SCREAMING_SNAKE_CASE_ , help="""help message""" ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=SCREAMING_SNAKE_CASE_ ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[int] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } UpperCamelCase : Optional[Any] = parser.parse_dict(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[int] = BasicExample(**SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, """extra""": 42, } self.assertRaises(SCREAMING_SNAKE_CASE_ , parser.parse_dict , SCREAMING_SNAKE_CASE_ , allow_extra_keys=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase : List[Any] = os.path.join(SCREAMING_SNAKE_CASE_ , """temp_json""" ) os.mkdir(SCREAMING_SNAKE_CASE_ ) with open(temp_local_path + """.json""" , """w+""" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = parser.parse_yaml_file(Path(temp_local_path + """.json""" ) )[0] UpperCamelCase : Optional[Any] = BasicExample(**SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase : List[str] = os.path.join(SCREAMING_SNAKE_CASE_ , """temp_yaml""" ) os.mkdir(SCREAMING_SNAKE_CASE_ ) with open(temp_local_path + """.yaml""" , """w+""" ) as f: yaml.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = parser.parse_yaml_file(Path(temp_local_path + """.yaml""" ) )[0] UpperCamelCase : str = BasicExample(**SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
360
"""simple docstring""" from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class lowerCamelCase ( nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 88 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "geglu" , SCREAMING_SNAKE_CASE_ = None , ): super().__init__() UpperCamelCase : int = nn.ModuleList( [ TransformeraDModel( num_attention_heads=SCREAMING_SNAKE_CASE_ , attention_head_dim=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , dropout=SCREAMING_SNAKE_CASE_ , norm_num_groups=SCREAMING_SNAKE_CASE_ , cross_attention_dim=SCREAMING_SNAKE_CASE_ , attention_bias=SCREAMING_SNAKE_CASE_ , sample_size=SCREAMING_SNAKE_CASE_ , num_vector_embeds=SCREAMING_SNAKE_CASE_ , activation_fn=SCREAMING_SNAKE_CASE_ , num_embeds_ada_norm=SCREAMING_SNAKE_CASE_ , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference UpperCamelCase : Optional[Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` UpperCamelCase : List[Any] = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` UpperCamelCase : int = [1, 0] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = True , ): UpperCamelCase : Dict = hidden_states UpperCamelCase : Optional[Any] = [] UpperCamelCase : List[Any] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens UpperCamelCase : Optional[int] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] UpperCamelCase : str = self.transformer_index_for_condition[i] UpperCamelCase : Any = self.transformers[transformer_index]( SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , timestep=SCREAMING_SNAKE_CASE_ , cross_attention_kwargs=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] UpperCamelCase : Any = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) UpperCamelCase : List[str] = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=SCREAMING_SNAKE_CASE_ )
27
0
import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=3.6 ): UpperCamelCase : Dict = tokenizer UpperCamelCase : Optional[Any] = tokenizer.bos_token_id UpperCamelCase : Any = dataset UpperCamelCase : List[str] = seq_length UpperCamelCase : Optional[Any] = seq_length * chars_per_token * num_of_sequences def __iter__( self ): UpperCamelCase : Dict = iter(self.dataset ) UpperCamelCase : Union[str, Any] = True while more_examples: UpperCamelCase : Tuple = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(SCREAMING_SNAKE_CASE_ )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: UpperCamelCase : Dict = False break UpperCamelCase : str = tokenizer(SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )["""input_ids"""] UpperCamelCase : str = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , self.seq_length ): UpperCamelCase : List[str] = all_token_ids[i : i + self.seq_length] if len(SCREAMING_SNAKE_CASE_ ) == self.seq_length: yield torch.tensor(SCREAMING_SNAKE_CASE_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Dict = {"""streaming""": True} UpperCamelCase : Optional[int] = load_dataset(args.dataset_name ,split="""train""" ,**snake_case_ ) UpperCamelCase : Optional[int] = ConstantLengthDataset(snake_case_ ,snake_case_ ,seq_length=args.seq_length ) UpperCamelCase : List[Any] = DataLoader(snake_case_ ,batch_size=args.batch_size ) return eval_dataloader def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' model.eval() UpperCamelCase : Dict = [] for step, batch in enumerate(snake_case_ ): with torch.no_grad(): UpperCamelCase : List[Any] = model(snake_case_ ,labels=snake_case_ ) UpperCamelCase : Any = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(snake_case_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break UpperCamelCase : Dict = torch.mean(torch.cat(snake_case_ ) ) try: UpperCamelCase : Dict = torch.exp(snake_case_ ) except OverflowError: UpperCamelCase : Optional[int] = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator __A : List[Any] = Accelerator() # Parse configuration __A : str = HfArgumentParser(EvaluationArguments) __A : List[Any] = parser.parse_args() set_seed(args.seed) # Logging __A : Any = logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer __A : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) __A : List[Any] = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader __A : int = create_dataloader(args) # Prepare everything with our `accelerator`. __A : Optional[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') __A : Tuple = evaluate(args) logger.info(F'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
361
"""simple docstring""" import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : Optional[int] = { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json''', } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[int] = 'mvp' lowercase : Optional[Any] = ['past_key_values'] lowercase : Union[str, Any] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , SCREAMING_SNAKE_CASE_=5_0267 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=100 , SCREAMING_SNAKE_CASE_=800 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Dict = max_position_embeddings UpperCamelCase : Optional[int] = d_model UpperCamelCase : Optional[Any] = encoder_ffn_dim UpperCamelCase : Any = encoder_layers UpperCamelCase : List[Any] = encoder_attention_heads UpperCamelCase : Optional[Any] = decoder_ffn_dim UpperCamelCase : Optional[int] = decoder_layers UpperCamelCase : Dict = decoder_attention_heads UpperCamelCase : List[str] = dropout UpperCamelCase : List[str] = attention_dropout UpperCamelCase : List[Any] = activation_dropout UpperCamelCase : Dict = activation_function UpperCamelCase : List[str] = init_std UpperCamelCase : int = encoder_layerdrop UpperCamelCase : Dict = decoder_layerdrop UpperCamelCase : Any = classifier_dropout UpperCamelCase : Tuple = use_cache UpperCamelCase : Dict = encoder_layers UpperCamelCase : Tuple = scale_embedding # scale factor will be sqrt(d_model) if True UpperCamelCase : Optional[Any] = use_prompt UpperCamelCase : Any = prompt_length UpperCamelCase : List[Any] = prompt_mid_dim super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , forced_eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated""" , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = self.bos_token_id warnings.warn( f'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ' """The config can simply be saved and uploaded again to be fixed.""" )
27
0
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'EncodecFeatureExtractor' lowercase : List[Any] = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.feature_extractor UpperCamelCase : Any = False def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True ): return self.tokenizer.get_decoder_prompt_ids(task=SCREAMING_SNAKE_CASE_ , language=SCREAMING_SNAKE_CASE_ , no_timestamps=SCREAMING_SNAKE_CASE_ ) def __call__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = kwargs.pop("""sampling_rate""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Any = args[0] UpperCamelCase : str = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if text is not None: UpperCamelCase : Optional[int] = self.tokenizer(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is not None: UpperCamelCase : str = self.feature_extractor(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is None: return inputs elif text is None: return audio_inputs else: UpperCamelCase : int = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: UpperCamelCase : Optional[Any] = audio_inputs["""padding_mask"""] return inputs def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = kwargs.pop("""padding_mask""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Optional[int] = args[0] UpperCamelCase : Any = args[1:] if audio_values is not None: return self._decode_audio(SCREAMING_SNAKE_CASE_ , padding_mask=SCREAMING_SNAKE_CASE_ ) else: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = to_numpy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = audio_values.shape if padding_mask is None: return list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = to_numpy(SCREAMING_SNAKE_CASE_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) UpperCamelCase : List[str] = seq_len - padding_mask.shape[-1] UpperCamelCase : Optional[int] = 1 - self.feature_extractor.padding_value UpperCamelCase : Any = np.pad(SCREAMING_SNAKE_CASE_ , ((0, 0), (0, difference)) , """constant""" , constant_values=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audio_values.tolist() for i in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] UpperCamelCase : Optional[Any] = sliced_audio.reshape(SCREAMING_SNAKE_CASE_ , -1 ) return audio_values
362
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __A : Optional[Any] = 16 __A : str = 32 def A_ ( snake_case_ : Accelerator ,snake_case_ : int = 1_6 ): '''simple docstring''' UpperCamelCase : Tuple = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCamelCase : Optional[int] = load_dataset("""glue""" ,"""mrpc""" ) def tokenize_function(snake_case_ : List[Any] ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase : Union[str, Any] = tokenizer(examples["""sentence1"""] ,examples["""sentence2"""] ,truncation=snake_case_ ,max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase : Optional[Any] = datasets.map( snake_case_ ,batched=snake_case_ ,remove_columns=["""idx""", """sentence1""", """sentence2"""] ,) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase : str = tokenized_datasets.rename_column("""label""" ,"""labels""" ) def collate_fn(snake_case_ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase : Optional[Any] = 1_6 elif accelerator.mixed_precision != "no": UpperCamelCase : Any = 8 else: UpperCamelCase : Optional[Any] = None return tokenizer.pad( snake_case_ ,padding="""longest""" ,max_length=snake_case_ ,pad_to_multiple_of=snake_case_ ,return_tensors="""pt""" ,) # Instantiate dataloaders. UpperCamelCase : str = DataLoader( tokenized_datasets["""train"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) UpperCamelCase : Dict = DataLoader( tokenized_datasets["""validation"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders __A : int = mocked_dataloaders # noqa: F811 def A_ ( snake_case_ : Tuple ,snake_case_ : Dict ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" ,snake_case_ ) == "1": UpperCamelCase : Union[str, Any] = 2 # New Code # UpperCamelCase : Dict = int(args.gradient_accumulation_steps ) UpperCamelCase : List[Any] = int(args.local_sgd_steps ) # Initialize accelerator UpperCamelCase : str = Accelerator( cpu=args.cpu ,mixed_precision=args.mixed_precision ,gradient_accumulation_steps=snake_case_ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase : Union[str, Any] = config["""lr"""] UpperCamelCase : int = int(config["""num_epochs"""] ) UpperCamelCase : int = int(config["""seed"""] ) UpperCamelCase : List[Any] = int(config["""batch_size"""] ) UpperCamelCase : Optional[int] = evaluate.load("""glue""" ,"""mrpc""" ) set_seed(snake_case_ ) UpperCamelCase , UpperCamelCase : Dict = get_dataloaders(snake_case_ ,snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase : Optional[int] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" ,return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase : Tuple = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase : List[Any] = AdamW(params=model.parameters() ,lr=snake_case_ ) # Instantiate scheduler UpperCamelCase : str = get_linear_schedule_with_warmup( optimizer=snake_case_ ,num_warmup_steps=1_0_0 ,num_training_steps=(len(snake_case_ ) * num_epochs) ,) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Any = accelerator.prepare( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() with LocalSGD( accelerator=snake_case_ ,model=snake_case_ ,local_sgd_steps=snake_case_ ,enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(snake_case_ ): UpperCamelCase : Optional[Any] = model(**snake_case_ ) UpperCamelCase : Optional[int] = output.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase : Any = model(**snake_case_ ) UpperCamelCase : Tuple = outputs.logits.argmax(dim=-1 ) UpperCamelCase , UpperCamelCase : int = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case_ ,references=snake_case_ ,) UpperCamelCase : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' ,snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" ,type=snake_case_ ,default=snake_case_ ,choices=["""no""", """fp16""", """bf16""", """fp8"""] ,help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" ,) # New Code # parser.add_argument( """--gradient_accumulation_steps""" ,type=snake_case_ ,default=1 ,help="""The number of minibatches to be ran before gradients are accumulated.""" ,) parser.add_argument( """--local_sgd_steps""" ,type=snake_case_ ,default=8 ,help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" ,action="""store_true""" ,help="""If passed, will train on the CPU.""" ) UpperCamelCase : Dict = parser.parse_args() UpperCamelCase : List[Any] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(snake_case_ ,snake_case_ ) if __name__ == "__main__": main()
27
0
"""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 A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Optional[Any] ,snake_case_ : int ,snake_case_ : str ): '''simple docstring''' if isinstance(snake_case_ ,snake_case_ ): UpperCamelCase : Any = np.full((len(snake_case_ ), sequence_length, 2) ,snake_case_ ) else: UpperCamelCase : Dict = np.full((len(snake_case_ ), sequence_length) ,snake_case_ ) for i, tensor in enumerate(snake_case_ ): if padding_side == "right": if isinstance(snake_case_ ,snake_case_ ): UpperCamelCase : str = tensor[:sequence_length] else: UpperCamelCase : Any = tensor[:sequence_length] else: if isinstance(snake_case_ ,snake_case_ ): UpperCamelCase : int = tensor[:sequence_length] else: UpperCamelCase : str = tensor[:sequence_length] return out_tensor.tolist() def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' UpperCamelCase : Optional[int] = ord(snake_case_ ) if (cp >= 3_3 and cp <= 4_7) or (cp >= 5_8 and cp <= 6_4) or (cp >= 9_1 and cp <= 9_6) or (cp >= 1_2_3 and cp <= 1_2_6): return True UpperCamelCase : Optional[Any] = unicodedata.category(snake_case_ ) if cat.startswith("""P""" ): return True return False @dataclass class lowerCamelCase ( _UpperCAmelCase ): lowercase : PreTrainedTokenizerBase lowercase : Union[bool, str, PaddingStrategy] = True lowercase : Optional[int] = None lowercase : Optional[int] = None lowercase : int = -1_0_0 lowercase : str = "pt" def a_ ( self , SCREAMING_SNAKE_CASE_ ): import torch UpperCamelCase : str = """label""" if """label""" in features[0].keys() else """labels""" UpperCamelCase : Optional[int] = [feature[label_name] for feature in features] if label_name in features[0].keys() else None UpperCamelCase : Union[str, Any] = self.tokenizer.pad( SCREAMING_SNAKE_CASE_ , 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 UpperCamelCase : Tuple = torch.tensor(batch["""entity_ids"""] ).shape[1] UpperCamelCase : Any = self.tokenizer.padding_side if padding_side == "right": UpperCamelCase : str = [ list(SCREAMING_SNAKE_CASE_ ) + [self.label_pad_token_id] * (sequence_length - len(SCREAMING_SNAKE_CASE_ )) for label in labels ] else: UpperCamelCase : List[Any] = [ [self.label_pad_token_id] * (sequence_length - len(SCREAMING_SNAKE_CASE_ )) + list(SCREAMING_SNAKE_CASE_ ) for label in labels ] UpperCamelCase : List[Any] = [feature["""ner_tags"""] for feature in features] UpperCamelCase : List[Any] = padding_tensor(SCREAMING_SNAKE_CASE_ , -1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = [feature["""original_entity_spans"""] for feature in features] UpperCamelCase : Dict = padding_tensor(SCREAMING_SNAKE_CASE_ , (-1, -1) , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = {k: torch.tensor(SCREAMING_SNAKE_CASE_ , dtype=torch.intaa ) for k, v in batch.items()} return batch
363
"""simple docstring""" from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer __A : Any = logging.get_logger(__name__) __A : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A : Optional[Any] = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } __A : Any = {'''allegro/herbert-base-cased''': 514} __A : Optional[Any] = {} class lowerCamelCase ( _UpperCAmelCase ): lowercase : Dict = VOCAB_FILES_NAMES lowercase : Any = PRETRAINED_VOCAB_FILES_MAP lowercase : List[str] = PRETRAINED_INIT_CONFIGURATION lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Union[str, Any] = HerbertTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_="</s>" , **SCREAMING_SNAKE_CASE_ , ): super().__init__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = [self.cls_token_id] UpperCamelCase : str = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Tuple = [self.sep_token_id] UpperCamelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Optional[int] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
27
0
"""simple docstring""" import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def A_ ( snake_case_ : Union[str, Any] ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : int = create_tensor(snake_case_ ) UpperCamelCase : str = gather(snake_case_ ) assert gathered_tensor.tolist() == list(range(1 ,state.num_processes**2 + 1 ) ) def A_ ( snake_case_ : int ): '''simple docstring''' UpperCamelCase : int = [state.process_index] UpperCamelCase : Optional[int] = gather_object(snake_case_ ) assert len(snake_case_ ) == state.num_processes, f'{gathered_obj}, {len(snake_case_ )} != {state.num_processes}' assert gathered_obj == list(range(state.num_processes ) ), f'{gathered_obj} != {list(range(state.num_processes ) )}' def A_ ( snake_case_ : Any ): '''simple docstring''' UpperCamelCase : List[Any] = create_tensor(snake_case_ ) UpperCamelCase : Tuple = broadcast(snake_case_ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 ,state.num_processes + 1 ) ) def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' # We need to pad the tensor with one more element if we are the main process # to ensure that we can pad if state.is_main_process: UpperCamelCase : Tuple = torch.arange(state.num_processes + 1 ).to(state.device ) else: UpperCamelCase : Union[str, Any] = torch.arange(state.num_processes ).to(state.device ) UpperCamelCase : Dict = pad_across_processes(snake_case_ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 ,state.num_processes ) ) + [0] def A_ ( snake_case_ : str ): '''simple docstring''' # For now runs on only two processes if state.num_processes != 2: return UpperCamelCase : Tuple = create_tensor(snake_case_ ) UpperCamelCase : Dict = reduce(snake_case_ ,"""sum""" ) UpperCamelCase : Dict = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(snake_case_ ,snake_case_ ), f'{reduced_tensor} != {truth_tensor}' def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' # For now runs on only two processes if state.num_processes != 2: return UpperCamelCase : Optional[Any] = create_tensor(snake_case_ ) UpperCamelCase : int = reduce(snake_case_ ,"""mean""" ) UpperCamelCase : List[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(snake_case_ ,snake_case_ ), f'{reduced_tensor} != {truth_tensor}' def A_ ( snake_case_ : str ): '''simple docstring''' main() def A_ ( ): '''simple docstring''' UpperCamelCase : Any = PartialState() state.print(f'State: {state}' ) state.print("""testing gather""" ) test_gather(snake_case_ ) state.print("""testing gather_object""" ) test_gather_object(snake_case_ ) state.print("""testing broadcast""" ) test_broadcast(snake_case_ ) state.print("""testing pad_across_processes""" ) test_pad_across_processes(snake_case_ ) state.print("""testing reduce_sum""" ) test_reduce_sum(snake_case_ ) state.print("""testing reduce_mean""" ) test_reduce_mean(snake_case_ ) if __name__ == "__main__": main()
364
"""simple docstring""" import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=3.6 ): UpperCamelCase : Dict = tokenizer UpperCamelCase : Optional[Any] = tokenizer.bos_token_id UpperCamelCase : Any = dataset UpperCamelCase : List[str] = seq_length UpperCamelCase : Optional[Any] = seq_length * chars_per_token * num_of_sequences def __iter__( self ): UpperCamelCase : Dict = iter(self.dataset ) UpperCamelCase : Union[str, Any] = True while more_examples: UpperCamelCase , UpperCamelCase : Tuple = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(SCREAMING_SNAKE_CASE_ )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: UpperCamelCase : Dict = False break UpperCamelCase : str = tokenizer(SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )["""input_ids"""] UpperCamelCase : str = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , self.seq_length ): UpperCamelCase : List[str] = all_token_ids[i : i + self.seq_length] if len(SCREAMING_SNAKE_CASE_ ) == self.seq_length: yield torch.tensor(SCREAMING_SNAKE_CASE_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Dict = {"""streaming""": True} UpperCamelCase : Optional[int] = load_dataset(args.dataset_name ,split="""train""" ,**snake_case_ ) UpperCamelCase : Optional[int] = ConstantLengthDataset(snake_case_ ,snake_case_ ,seq_length=args.seq_length ) UpperCamelCase : List[Any] = DataLoader(snake_case_ ,batch_size=args.batch_size ) return eval_dataloader def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' model.eval() UpperCamelCase : Dict = [] for step, batch in enumerate(snake_case_ ): with torch.no_grad(): UpperCamelCase : List[Any] = model(snake_case_ ,labels=snake_case_ ) UpperCamelCase : Any = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(snake_case_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break UpperCamelCase : Dict = torch.mean(torch.cat(snake_case_ ) ) try: UpperCamelCase : Dict = torch.exp(snake_case_ ) except OverflowError: UpperCamelCase : Optional[int] = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator __A : List[Any] = Accelerator() # Parse configuration __A : str = HfArgumentParser(EvaluationArguments) __A : List[Any] = parser.parse_args() set_seed(args.seed) # Logging __A : Any = logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer __A : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) __A : List[Any] = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader __A : int = create_dataloader(args) # Prepare everything with our `accelerator`. __A , __A : Optional[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') __A , __A : Tuple = evaluate(args) logger.info(F'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
27
0
import argparse import torch from ...utils import logging from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert logging.set_verbosity_info() def A_ ( snake_case_ : Tuple ,snake_case_ : Union[str, Any] ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : List[str] = AlbertConfig.from_json_file(snake_case_ ) print(f'Building PyTorch model from configuration: {config}' ) UpperCamelCase : int = AlbertForPreTraining(snake_case_ ) # Load weights from tf checkpoint load_tf_weights_in_albert(snake_case_ ,snake_case_ ,snake_case_ ) # Save pytorch-model print(f'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() ,snake_case_ ) if __name__ == "__main__": __A : Tuple = 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( '''--albert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained ALBERT 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.''' ) __A : str = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
365
"""simple docstring""" import argparse import os import re __A : Any = '''src/transformers''' # Pattern that looks at the indentation in a line. __A : Tuple = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : List[Any] = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : List[Any] = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : Any = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : str ,snake_case_ : str="" ,snake_case_ : Any=None ,snake_case_ : Union[str, Any]=None ): '''simple docstring''' UpperCamelCase : List[Any] = 0 UpperCamelCase : Optional[int] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Tuple = ["""\n""".join(lines[:index] )] else: UpperCamelCase : Tuple = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Dict = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Optional[Any] = [lines[index + 1]] index += 1 else: UpperCamelCase : str = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : List[Any] ): '''simple docstring''' def _inner(snake_case_ : List[str] ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Tuple=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Optional[int] ): return x if key is None: UpperCamelCase : List[str] = noop # Constants are all uppercase, they go first. UpperCamelCase : List[str] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : Tuple = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : int = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Union[str, Any] = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : Any ): UpperCamelCase : Union[str, Any] = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : int = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : str = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : Optional[int] = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : int = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Tuple = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : List[Any] = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Union[str, Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : List[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : Optional[int] = keys[:-1] UpperCamelCase : Union[str, Any] = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : Any = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : int=True ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : List[str] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : int = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Dict = main_blocks[block_idx] UpperCamelCase : Dict = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : List[str] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : Optional[Any] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Optional[Any] = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Any = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : List[Any] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Optional[Any] = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Optional[Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Any = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : Union[str, Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[str] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: UpperCamelCase : Optional[int] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Optional[int] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : List[Any] = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : Union[str, Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
0
"""simple docstring""" import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotSmallConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin 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 __A : List[Any] = '''platform''' import jax import jax.numpy as jnp from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, shift_tokens_right, ) def A_ ( snake_case_ : str ,snake_case_ : Optional[Any] ,snake_case_ : Union[str, Any]=None ,snake_case_ : List[str]=None ,snake_case_ : List[str]=None ,snake_case_ : Tuple=None ,snake_case_ : str=None ,snake_case_ : Any=None ,): '''simple docstring''' if attention_mask is None: UpperCamelCase : List[str] = np.where(input_ids != config.pad_token_id ,1 ,0 ) if decoder_attention_mask is None: UpperCamelCase : List[Any] = np.where(decoder_input_ids != config.pad_token_id ,1 ,0 ) if head_mask is None: UpperCamelCase : int = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCamelCase : int = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCamelCase : int = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=0.02 , ): UpperCamelCase : Tuple = parent UpperCamelCase : Dict = batch_size UpperCamelCase : int = seq_length UpperCamelCase : Any = is_training UpperCamelCase : int = use_labels UpperCamelCase : str = vocab_size UpperCamelCase : str = hidden_size UpperCamelCase : Optional[int] = num_hidden_layers UpperCamelCase : Union[str, Any] = num_attention_heads UpperCamelCase : str = intermediate_size UpperCamelCase : Optional[int] = hidden_act UpperCamelCase : List[str] = hidden_dropout_prob UpperCamelCase : List[str] = attention_probs_dropout_prob UpperCamelCase : int = max_position_embeddings UpperCamelCase : int = eos_token_id UpperCamelCase : Any = pad_token_id UpperCamelCase : int = bos_token_id UpperCamelCase : Any = initializer_range def a_ ( self ): UpperCamelCase : Optional[int] = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) UpperCamelCase : Optional[int] = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) UpperCamelCase : Tuple = shift_tokens_right(SCREAMING_SNAKE_CASE_ , 1 , 2 ) UpperCamelCase : int = BlenderbotSmallConfig( 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_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Union[str, Any] = prepare_blenderbot_inputs_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return config, inputs_dict def a_ ( self ): UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() return config, inputs_dict def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = 20 UpperCamelCase : Tuple = model_class_name(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model.encode(inputs_dict["""input_ids"""] ) UpperCamelCase : Any = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) UpperCamelCase : Dict = model.init_cache(decoder_input_ids.shape[0] , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) UpperCamelCase : List[str] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) UpperCamelCase : Union[str, Any] = model.decode( decoder_input_ids[:, :-1] , SCREAMING_SNAKE_CASE_ , decoder_attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , decoder_position_ids=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[int] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) UpperCamelCase : Any = model.decode( decoder_input_ids[:, -1:] , SCREAMING_SNAKE_CASE_ , decoder_attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = model.decode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[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 a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = 20 UpperCamelCase : int = model_class_name(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model.encode(inputs_dict["""input_ids"""] ) UpperCamelCase : Dict = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) UpperCamelCase : List[Any] = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) UpperCamelCase : Optional[Any] = model.init_cache(decoder_input_ids.shape[0] , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) UpperCamelCase : Optional[Any] = model.decode( decoder_input_ids[:, :-1] , SCREAMING_SNAKE_CASE_ , decoder_attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , decoder_position_ids=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) UpperCamelCase : List[str] = model.decode( decoder_input_ids[:, -1:] , SCREAMING_SNAKE_CASE_ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=SCREAMING_SNAKE_CASE_ , decoder_position_ids=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model.decode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , decoder_attention_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : 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}' ) @require_flax class lowerCamelCase ( unittest.TestCase ): lowercase : int = 9_9 def a_ ( self ): UpperCamelCase : Dict = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) UpperCamelCase : List[str] = input_ids.shape[0] UpperCamelCase : int = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def a_ ( self ): UpperCamelCase : Tuple = self._get_config_and_data() UpperCamelCase : Union[str, Any] = FlaxBlenderbotSmallForConditionalGeneration(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = lm_model(input_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs["""logits"""].shape , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) UpperCamelCase : Tuple = FlaxBlenderbotSmallForConditionalGeneration(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) UpperCamelCase : Dict = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) UpperCamelCase : Dict = lm_model(input_ids=SCREAMING_SNAKE_CASE_ , decoder_input_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = (*summary.shape, config.vocab_size) self.assertEqual(outputs["""logits"""].shape , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) UpperCamelCase : Optional[Any] = shift_tokens_right(SCREAMING_SNAKE_CASE_ , 1 , 2 ) UpperCamelCase : Dict = np.equal(SCREAMING_SNAKE_CASE_ , 1 ).astype(np.floataa ).sum() UpperCamelCase : Tuple = np.equal(SCREAMING_SNAKE_CASE_ , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(SCREAMING_SNAKE_CASE_ , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase , _UpperCAmelCase ): lowercase : Union[str, Any] = True lowercase : List[str] = ( ( FlaxBlenderbotSmallModel, FlaxBlenderbotSmallForConditionalGeneration, ) if is_flax_available() else () ) lowercase : int = (FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else () def a_ ( self ): UpperCamelCase : List[str] = FlaxBlenderbotSmallModelTester(self ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase : str = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model_class(SCREAMING_SNAKE_CASE_ ) @jax.jit def encode_jitted(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ): return model.encode(input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) with self.subTest("""JIT Enabled""" ): UpperCamelCase : Union[str, Any] = encode_jitted(**SCREAMING_SNAKE_CASE_ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): UpperCamelCase : Optional[Any] = encode_jitted(**SCREAMING_SNAKE_CASE_ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) for jitted_output, output in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(jitted_output.shape , output.shape ) def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) UpperCamelCase : Union[str, Any] = { """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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return model.decode( decoder_input_ids=SCREAMING_SNAKE_CASE_ , decoder_attention_mask=SCREAMING_SNAKE_CASE_ , encoder_outputs=SCREAMING_SNAKE_CASE_ , ) with self.subTest("""JIT Enabled""" ): UpperCamelCase : Dict = decode_jitted(**SCREAMING_SNAKE_CASE_ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): UpperCamelCase : List[Any] = decode_jitted(**SCREAMING_SNAKE_CASE_ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) for jitted_output, output in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def a_ ( self ): for model_class_name in self.all_model_classes: UpperCamelCase : Optional[int] = model_class_name.from_pretrained("""facebook/blenderbot_small-90M""" ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids UpperCamelCase : Union[str, Any] = np.ones((1, 1) ) * model.config.eos_token_id UpperCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
366
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' if number < 0: raise ValueError("""number must not be negative""" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
27
0
"""simple docstring""" from collections.abc import Callable def A_ ( snake_case_ : Callable[[float], float] ,snake_case_ : float ,snake_case_ : float ): '''simple docstring''' UpperCamelCase : float = a UpperCamelCase : float = b if function(snake_case_ ) == 0: # one of the a or b is a root for the function return a elif function(snake_case_ ) == 0: return b elif ( function(snake_case_ ) * function(snake_case_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("""could not find root in given interval.""" ) else: UpperCamelCase : float = start + (end - start) / 2.0 while abs(start - mid ) > 1_0**-7: # until precisely equals to 10^-7 if function(snake_case_ ) == 0: return mid elif function(snake_case_ ) * function(snake_case_ ) < 0: UpperCamelCase : Dict = mid else: UpperCamelCase : List[str] = mid UpperCamelCase : Tuple = start + (end - start) / 2.0 return mid def A_ ( snake_case_ : float ): '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
367
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL __A : Optional[Any] = logging.get_logger(__name__) def A_ ( snake_case_ : np.ndarray ,snake_case_ : Union[int, Iterable[int]] ,snake_case_ : bool ,snake_case_ : int ): '''simple docstring''' def constraint_to_multiple_of(snake_case_ : Optional[Any] ,snake_case_ : Optional[int] ,snake_case_ : List[str]=0 ,snake_case_ : Optional[Any]=None ): UpperCamelCase : List[str] = round(val / multiple ) * multiple if max_val is not None and x > max_val: UpperCamelCase : Optional[Any] = math.floor(val / multiple ) * multiple if x < min_val: UpperCamelCase : Dict = math.ceil(val / multiple ) * multiple return x UpperCamelCase : Any = (output_size, output_size) if isinstance(snake_case_ ,snake_case_ ) else output_size UpperCamelCase , UpperCamelCase : int = get_image_size(snake_case_ ) UpperCamelCase , UpperCamelCase : Union[str, Any] = output_size # determine new height and width UpperCamelCase : List[str] = output_height / input_height UpperCamelCase : List[str] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width UpperCamelCase : int = scale_width else: # fit height UpperCamelCase : Optional[Any] = scale_height UpperCamelCase : int = constraint_to_multiple_of(scale_height * input_height ,multiple=snake_case_ ) UpperCamelCase : Union[str, Any] = constraint_to_multiple_of(scale_width * input_width ,multiple=snake_case_ ) return (new_height, new_width) class lowerCamelCase ( _UpperCAmelCase ): lowercase : str = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = size if size is not None else {"""height""": 384, """width""": 384} UpperCamelCase : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = do_resize UpperCamelCase : Union[str, Any] = size UpperCamelCase : Union[str, Any] = keep_aspect_ratio UpperCamelCase : Any = ensure_multiple_of UpperCamelCase : List[Any] = resample UpperCamelCase : str = do_rescale UpperCamelCase : Optional[Any] = rescale_factor UpperCamelCase : List[str] = do_normalize UpperCamelCase : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCamelCase : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) UpperCamelCase : Dict = get_resize_output_image_size( SCREAMING_SNAKE_CASE_ , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=SCREAMING_SNAKE_CASE_ , multiple=SCREAMING_SNAKE_CASE_ , ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize UpperCamelCase : List[Any] = size if size is not None else self.size UpperCamelCase : Dict = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio UpperCamelCase : Optional[int] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of UpperCamelCase : Tuple = resample if resample is not None else self.resample UpperCamelCase : str = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase : Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase : Any = image_mean if image_mean is not None else self.image_mean UpperCamelCase : List[Any] = image_std if image_std is not None else self.image_std UpperCamelCase : str = make_list_of_images(SCREAMING_SNAKE_CASE_ ) if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. UpperCamelCase : Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase : Union[str, Any] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase : int = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase : List[str] = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Union[str, Any] = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : str = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = target_sizes.numpy() UpperCamelCase : Dict = [] for idx in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase : List[Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : List[Any] = logits.argmax(dim=1 ) UpperCamelCase : Dict = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
27
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Tuple = logging.get_logger(__name__) __A : List[str] = { '''google/bigbird-roberta-base''': '''https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json''', '''google/bigbird-roberta-large''': '''https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json''', '''google/bigbird-base-trivia-itc''': '''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json''', # See all BigBird models at https://huggingface.co/models?filter=big_bird } class lowerCamelCase ( _UpperCAmelCase ): lowercase : str = 'big_bird' def __init__( self , SCREAMING_SNAKE_CASE_=5_0358 , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_="gelu_new" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-12 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=66 , SCREAMING_SNAKE_CASE_="block_sparse" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ): super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , sep_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : List[Any] = vocab_size UpperCamelCase : Optional[int] = max_position_embeddings UpperCamelCase : List[Any] = hidden_size UpperCamelCase : Any = num_hidden_layers UpperCamelCase : List[Any] = num_attention_heads UpperCamelCase : Any = intermediate_size UpperCamelCase : Dict = hidden_act UpperCamelCase : Any = hidden_dropout_prob UpperCamelCase : int = attention_probs_dropout_prob UpperCamelCase : List[str] = initializer_range UpperCamelCase : str = type_vocab_size UpperCamelCase : str = layer_norm_eps UpperCamelCase : Dict = use_cache UpperCamelCase : List[Any] = rescale_embeddings UpperCamelCase : List[Any] = attention_type UpperCamelCase : List[Any] = use_bias UpperCamelCase : List[Any] = block_size UpperCamelCase : Any = num_random_blocks UpperCamelCase : List[str] = classifier_dropout class lowerCamelCase ( _UpperCAmelCase ): @property def a_ ( self ): if self.task == "multiple-choice": UpperCamelCase : Dict = {0: """batch""", 1: """choice""", 2: """sequence"""} else: UpperCamelCase : Dict = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
368
"""simple docstring""" from collections.abc import Callable def A_ ( snake_case_ : Callable[[float], float] ,snake_case_ : float ,snake_case_ : float ): '''simple docstring''' UpperCamelCase : float = a UpperCamelCase : float = b if function(snake_case_ ) == 0: # one of the a or b is a root for the function return a elif function(snake_case_ ) == 0: return b elif ( function(snake_case_ ) * function(snake_case_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("""could not find root in given interval.""" ) else: UpperCamelCase : float = start + (end - start) / 2.0 while abs(start - mid ) > 1_0**-7: # until precisely equals to 10^-7 if function(snake_case_ ) == 0: return mid elif function(snake_case_ ) * function(snake_case_ ) < 0: UpperCamelCase : Dict = mid else: UpperCamelCase : List[str] = mid UpperCamelCase : Tuple = start + (end - start) / 2.0 return mid def A_ ( snake_case_ : float ): '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
27
0
"""simple docstring""" import argparse import os import re __A : Dict = '''src/diffusers''' # Pattern that looks at the indentation in a line. __A : Union[str, Any] = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : Tuple = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Tuple = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Union[str, Any] = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Dict="" ,snake_case_ : Dict=None ,snake_case_ : Any=None ): '''simple docstring''' UpperCamelCase : Optional[int] = 0 UpperCamelCase : List[Any] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Optional[Any] = ["""\n""".join(lines[:index] )] else: UpperCamelCase : int = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Any = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Any = [lines[index + 1]] index += 1 else: UpperCamelCase : List[str] = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' def _inner(snake_case_ : Tuple ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[int]=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Dict ): return x if key is None: UpperCamelCase : int = noop # Constants are all uppercase, they go first. UpperCamelCase : List[Any] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : str = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : List[str] = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Tuple = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : int ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : List[Any] ): UpperCamelCase : Any = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : Union[str, Any] = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[str] = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : str = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : str = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Dict = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : int = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[Any] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : Optional[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[Any] = keys[:-1] UpperCamelCase : int = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Tuple ,snake_case_ : str=True ): '''simple docstring''' with open(snake_case_ ,"""r""" ) as f: UpperCamelCase : int = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : Dict = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Optional[Any] = main_blocks[block_idx] UpperCamelCase : Optional[int] = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : Union[str, Any] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : List[str] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Dict = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Union[str, Any] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : Optional[int] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Union[str, Any] = _re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Union[str, Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Optional[Any] = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : List[Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[Any] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: UpperCamelCase : str = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Any = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Union[str, Any] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : Any = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Any = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : str = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
369
"""simple docstring""" import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def a_ ( self ): UpperCamelCase : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) UpperCamelCase : int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) UpperCamelCase : Dict = """xvjiarui/stable-diffusion-2-inpainting""" UpperCamelCase , UpperCamelCase : List[str] = FlaxStableDiffusionInpaintPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = """Face of a yellow cat, high resolution, sitting on a park bench""" UpperCamelCase : List[str] = jax.random.PRNGKey(0 ) UpperCamelCase : Tuple = 50 UpperCamelCase : Dict = jax.device_count() UpperCamelCase : Optional[int] = num_samples * [prompt] UpperCamelCase : int = num_samples * [init_image] UpperCamelCase : List[Any] = num_samples * [mask_image] UpperCamelCase , UpperCamelCase , UpperCamelCase : Optional[Any] = pipeline.prepare_inputs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # shard inputs and rng UpperCamelCase : Optional[int] = replicate(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = jax.random.split(SCREAMING_SNAKE_CASE_ , jax.device_count() ) UpperCamelCase : str = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = pipeline( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , jit=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = output.images.reshape(SCREAMING_SNAKE_CASE_ , 512 , 512 , 3 ) UpperCamelCase : List[Any] = images[0, 253:256, 253:256, -1] UpperCamelCase : List[Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) UpperCamelCase : Dict = jnp.array( [0.3611307, 0.37649736, 0.3757408, 0.38213953, 0.39295167, 0.3841631, 0.41554978, 0.4137475, 0.4217084] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
27
0
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : List[str] = StableDiffusionDiffEditPipeline lowercase : List[Any] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'height', 'width', 'image'} | {'image_latents'} lowercase : str = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'image'} | {'image_latents'} lowercase : List[Any] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowercase : Union[str, Any] = frozenset([] ) def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : List[str] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Union[str, Any] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Dict = DDIMInverseScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_zero=SCREAMING_SNAKE_CASE_ , ) torch.manual_seed(0 ) UpperCamelCase : Any = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) UpperCamelCase : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=512 , ) UpperCamelCase : List[str] = CLIPTextModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) UpperCamelCase : Any = { """unet""": unet, """scheduler""": scheduler, """inverse_scheduler""": inverse_scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : str = floats_tensor((1, 16, 16) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Dict = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = { """prompt""": """a dog and a newt""", """mask_image""": mask, """image_latents""": latents, """generator""": generator, """num_inference_steps""": 2, """inpaint_strength""": 1.0, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCamelCase : Optional[int] = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE_ ) ).convert("""RGB""" ) if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : Optional[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : str = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = { """image""": image, """source_prompt""": """a cat and a frog""", """target_prompt""": """a dog and a newt""", """generator""": generator, """num_inference_steps""": 2, """num_maps_per_mask""": 2, """mask_encode_strength""": 1.0, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : Any = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCamelCase : List[Any] = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE_ ) ).convert("""RGB""" ) if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : Any = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Optional[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = { """image""": image, """prompt""": """a cat and a frog""", """generator""": generator, """num_inference_steps""": 2, """inpaint_strength""": 1.0, """guidance_scale""": 6.0, """decode_latents""": True, """output_type""": """numpy""", } return inputs def a_ ( self ): if not hasattr(self.pipeline_class , """_optional_components""" ): return UpperCamelCase : Optional[Any] = self.get_dummy_components() UpperCamelCase : str = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} ) UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = pipe(**SCREAMING_SNAKE_CASE_ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = self.pipeline_class.from_pretrained(SCREAMING_SNAKE_CASE_ ) pipe_loaded.to(SCREAMING_SNAKE_CASE_ ) pipe_loaded.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) for optional_component in pipe._optional_components: self.assertTrue( getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) is None , f'`{optional_component}` did not stay set to None after loading.' , ) UpperCamelCase : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = pipe_loaded(**SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Dict = np.abs(output - output_loaded ).max() self.assertLess(SCREAMING_SNAKE_CASE_ , 1e-4 ) def a_ ( self ): UpperCamelCase : Dict = """cpu""" UpperCamelCase : Dict = self.get_dummy_components() UpperCamelCase : Dict = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.get_dummy_mask_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = pipe.generate_mask(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16) ) UpperCamelCase : List[Any] = np.array([0] * 9 ) UpperCamelCase : List[Any] = np.abs(mask_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1e-3 ) self.assertEqual(mask[0, -3, -4] , 0 ) def a_ ( self ): UpperCamelCase : Dict = """cpu""" UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : Any = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.get_dummy_inversion_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = pipe.invert(**SCREAMING_SNAKE_CASE_ ).images UpperCamelCase : str = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) UpperCamelCase : Union[str, Any] = np.array( [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799] , ) UpperCamelCase : Dict = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1e-3 ) def a_ ( self ): super().test_inference_batch_single_identical(expected_max_diff=5e-3 ) def a_ ( self ): UpperCamelCase : str = """cpu""" UpperCamelCase : int = self.get_dummy_components() UpperCamelCase : str = {"""beta_start""": 0.00085, """beta_end""": 0.012, """beta_schedule""": """scaled_linear"""} UpperCamelCase : List[Any] = DPMSolverMultistepScheduler(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = DPMSolverMultistepInverseScheduler(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.get_dummy_inversion_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = pipe.invert(**SCREAMING_SNAKE_CASE_ ).images UpperCamelCase : Optional[Any] = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) UpperCamelCase : Tuple = np.array( [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799] , ) UpperCamelCase : Optional[Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1e-3 ) @require_torch_gpu @slow class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def a_ ( cls ): UpperCamelCase : Any = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png""" ) UpperCamelCase : List[str] = raw_image.convert("""RGB""" ).resize((768, 768) ) UpperCamelCase : Optional[int] = raw_image def a_ ( self ): UpperCamelCase : List[Any] = torch.manual_seed(0 ) UpperCamelCase : List[Any] = StableDiffusionDiffEditPipeline.from_pretrained( """stabilityai/stable-diffusion-2-1""" , safety_checker=SCREAMING_SNAKE_CASE_ , torch_dtype=torch.floataa ) UpperCamelCase : List[Any] = DDIMScheduler.from_config(pipe.scheduler.config ) UpperCamelCase : List[Any] = DDIMInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = """a bowl of fruit""" UpperCamelCase : int = """a bowl of pears""" UpperCamelCase : Tuple = pipe.generate_mask( image=self.raw_image , source_prompt=SCREAMING_SNAKE_CASE_ , target_prompt=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = pipe.invert( prompt=SCREAMING_SNAKE_CASE_ , image=self.raw_image , inpaint_strength=0.7 , generator=SCREAMING_SNAKE_CASE_ ).latents UpperCamelCase : Optional[int] = pipe( prompt=SCREAMING_SNAKE_CASE_ , mask_image=SCREAMING_SNAKE_CASE_ , image_latents=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , inpaint_strength=0.7 , output_type="""numpy""" , ).images[0] UpperCamelCase : Dict = ( np.array( load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/diffedit/pears.png""" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5e-1 def a_ ( self ): UpperCamelCase : Union[str, Any] = torch.manual_seed(0 ) UpperCamelCase : int = StableDiffusionDiffEditPipeline.from_pretrained( """stabilityai/stable-diffusion-2-1""" , safety_checker=SCREAMING_SNAKE_CASE_ , torch_dtype=torch.floataa ) UpperCamelCase : Optional[int] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) UpperCamelCase : Dict = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = """a bowl of fruit""" UpperCamelCase : List[Any] = """a bowl of pears""" UpperCamelCase : List[str] = pipe.generate_mask( image=self.raw_image , source_prompt=SCREAMING_SNAKE_CASE_ , target_prompt=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Dict = pipe.invert( prompt=SCREAMING_SNAKE_CASE_ , image=self.raw_image , inpaint_strength=0.7 , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=25 , ).latents UpperCamelCase : Any = pipe( prompt=SCREAMING_SNAKE_CASE_ , mask_image=SCREAMING_SNAKE_CASE_ , image_latents=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , inpaint_strength=0.7 , num_inference_steps=25 , output_type="""numpy""" , ).images[0] UpperCamelCase : Any = ( np.array( load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/diffedit/pears.png""" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5e-1
370
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def A_ ( snake_case_ : int ): # picklable for multiprocessing '''simple docstring''' return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def A_ ( ): '''simple docstring''' with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" UpperCamelCase : Optional[Any] = [1, 2, 3] with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=2 ) with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" ,[2, -1] ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : List[Any] = [1, 2] UpperCamelCase : List[Any] = {"""a""": 1, """b""": 2} UpperCamelCase : List[str] = {"""a""": [1, 2], """b""": [3, 4]} UpperCamelCase : Tuple = {"""a""": {"""1""": 1}, """b""": 2} UpperCamelCase : Any = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} UpperCamelCase : Optional[int] = [2, 3] UpperCamelCase : List[str] = {"""a""": 2, """b""": 3} UpperCamelCase : Any = {"""a""": [2, 3], """b""": [4, 5]} UpperCamelCase : Tuple = {"""a""": {"""1""": 2}, """b""": 3} UpperCamelCase : List[str] = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa
27
0
"""simple docstring""" import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": __A : List[Any] = '''%20'''.join(argv[1:]) if len(argv) > 1 else quote(str(input('''Search: '''))) print('''Googling.....''') __A : Optional[Any] = F'''https://www.google.com/search?q={query}&num=100''' __A : Optional[int] = requests.get( url, headers={'''User-Agent''': str(UserAgent().random)}, ) try: __A : Optional[int] = ( BeautifulSoup(res.text, '''html.parser''') .find('''div''', attrs={'''class''': '''yuRUbf'''}) .find('''a''') .get('''href''') ) except AttributeError: __A : str = parse_qs( BeautifulSoup(res.text, '''html.parser''') .find('''div''', attrs={'''class''': '''kCrYT'''}) .find('''a''') .get('''href''') )['''url'''][0] webbrowser.open(link)
371
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="last" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=0 , ): UpperCamelCase : Union[str, Any] = parent UpperCamelCase : str = batch_size UpperCamelCase : int = seq_length UpperCamelCase : Optional[Any] = is_training UpperCamelCase : Any = use_input_lengths UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : List[Any] = use_labels UpperCamelCase : Union[str, Any] = gelu_activation UpperCamelCase : Dict = sinusoidal_embeddings UpperCamelCase : Optional[int] = causal UpperCamelCase : List[Any] = asm UpperCamelCase : int = n_langs UpperCamelCase : Optional[Any] = vocab_size UpperCamelCase : str = n_special UpperCamelCase : Dict = hidden_size UpperCamelCase : Union[str, Any] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : int = max_position_embeddings UpperCamelCase : Any = type_sequence_label_size UpperCamelCase : str = initializer_range UpperCamelCase : str = num_labels UpperCamelCase : Union[str, Any] = num_choices UpperCamelCase : List[str] = summary_type UpperCamelCase : int = use_proj UpperCamelCase : List[str] = scope UpperCamelCase : Dict = bos_token_id def a_ ( self ): UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Union[str, Any] = None if self.use_input_lengths: UpperCamelCase : str = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase : Tuple = None if self.use_token_type_ids: UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase : int = None UpperCamelCase : Dict = None UpperCamelCase : str = None if self.use_labels: UpperCamelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Dict = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : List[str] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def a_ ( self ): return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[int] = XLMModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , lengths=SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[Any] = XLMWithLMHeadModel(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : List[str] = XLMForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : int = XLMForQuestionAnswering(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , p_mask=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , ) ((UpperCamelCase) , ) : Union[str, Any] = result_with_labels.to_tuple() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , ) : Tuple = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = XLMForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : int = self.num_labels UpperCamelCase : int = XLMForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : List[Any] = self.num_choices UpperCamelCase : Tuple = XLMForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Optional[Any] = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : int = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : List[Any] = config_and_inputs UpperCamelCase : Dict = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) lowercase : List[Any] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable lowercase : Optional[Any] = ( { 'feature-extraction': XLMModel, 'fill-mask': XLMWithLMHeadModel, 'question-answering': XLMForQuestionAnsweringSimple, 'text-classification': XLMForSequenceClassification, 'text-generation': XLMWithLMHeadModel, 'token-classification': XLMForTokenClassification, 'zero-shot': XLMForSequenceClassification, } if is_torch_available() else {} ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": UpperCamelCase : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) return inputs_dict def a_ ( self ): UpperCamelCase : List[Any] = XLMModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , emb_dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_attentions in attentions] , [True] * len(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : int = min_length + idx + 1 UpperCamelCase : Tuple = min_length + idx + 1 UpperCamelCase : Any = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_hidden_states in hidden_states] , [True] * len(SCREAMING_SNAKE_CASE_ ) , ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : List[str] = min_length + idx + 1 UpperCamelCase : Optional[Any] = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) , ) pass @slow def a_ ( self ): for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : str = XLMModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Dict = XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.tensor([[14, 447]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # the president UpperCamelCase : List[Any] = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference UpperCamelCase : Optional[int] = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , SCREAMING_SNAKE_CASE_ )
27
0
import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Tuple = tmp_path / """file.csv""" UpperCamelCase : Union[str, Any] = textwrap.dedent( """\ header1,header2 1,2 10,20 """ ) with open(snake_case_ ,"""w""" ) as f: f.write(snake_case_ ) return str(snake_case_ ) @pytest.fixture def A_ ( snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : Optional[Any] = tmp_path / """malformed_file.csv""" UpperCamelCase : int = textwrap.dedent( """\ header1,header2 1,2 10,20, """ ) with open(snake_case_ ,"""w""" ) as f: f.write(snake_case_ ) return str(snake_case_ ) @pytest.fixture def A_ ( snake_case_ : List[str] ,snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : Tuple = tmp_path / """csv_with_image.csv""" UpperCamelCase : List[str] = textwrap.dedent( f'\\n image\n {image_file}\n ' ) with open(snake_case_ ,"""w""" ) as f: f.write(snake_case_ ) return str(snake_case_ ) @pytest.fixture def A_ ( snake_case_ : int ): '''simple docstring''' UpperCamelCase : List[Any] = tmp_path / """csv_with_label.csv""" UpperCamelCase : Optional[Any] = textwrap.dedent( """\ label good bad good """ ) with open(snake_case_ ,"""w""" ) as f: f.write(snake_case_ ) return str(snake_case_ ) @pytest.fixture def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : List[Any] = tmp_path / """csv_with_int_list.csv""" UpperCamelCase : int = textwrap.dedent( """\ int_list 1 2 3 4 5 6 7 8 9 """ ) with open(snake_case_ ,"""w""" ) as f: f.write(snake_case_ ) return str(snake_case_ ) def A_ ( snake_case_ : Dict ,snake_case_ : Optional[Any] ,snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Tuple = Csv() UpperCamelCase : Optional[Any] = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(snake_case_ ,match="""Error tokenizing data""" ): for _ in generator: pass assert any( record.levelname == """ERROR""" and """Failed to read file""" in record.message and os.path.basename(snake_case_ ) in record.message for record in caplog.records ) @require_pil def A_ ( snake_case_ : Tuple ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : Tuple = f.read().splitlines()[1] UpperCamelCase : List[str] = Csv(encoding="""utf-8""" ,features=Features({"""image""": Image()} ) ) UpperCamelCase : Any = csv._generate_tables([[csv_file_with_image]] ) UpperCamelCase : List[str] = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("""image""" ).type == Image()() UpperCamelCase : List[str] = pa_table.to_pydict()["""image"""] assert generated_content == [{"path": image_file, "bytes": None}] def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : List[str] = f.read().splitlines()[1:] UpperCamelCase : Optional[int] = Csv(encoding="""utf-8""" ,features=Features({"""label""": ClassLabel(names=["""good""", """bad"""] )} ) ) UpperCamelCase : Any = csv._generate_tables([[csv_file_with_label]] ) UpperCamelCase : Union[str, Any] = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("""label""" ).type == ClassLabel(names=["""good""", """bad"""] )() UpperCamelCase : Tuple = pa_table.to_pydict()["""label"""] assert generated_content == [ClassLabel(names=["""good""", """bad"""] ).straint(snake_case_ ) for label in labels] def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Any = Csv(encoding="""utf-8""" ,sep=""",""" ,converters={"""int_list""": lambda snake_case_ : [int(snake_case_ ) for i in x.split()]} ) UpperCamelCase : Dict = csv._generate_tables([[csv_file_with_int_list]] ) UpperCamelCase : Union[str, Any] = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field("""int_list""" ).type ) UpperCamelCase : Union[str, Any] = pa_table.to_pydict()["""int_list"""] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
350
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A : int = { '''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = [ '''GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTBigCodeForSequenceClassification''', '''GPTBigCodeForTokenClassification''', '''GPTBigCodeForCausalLM''', '''GPTBigCodeModel''', '''GPTBigCodePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
0
"""simple docstring""" from collections import defaultdict from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst def A_ ( ): '''simple docstring''' UpperCamelCase : Dict = 9, 1_4 # noqa: F841 UpperCamelCase : Union[str, Any] = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 1_4], [3, 4, 9], [5, 4, 1_0], [1, 7, 1_1], ] UpperCamelCase : List[Any] = defaultdict(snake_case_ ) for nodea, nodea, cost in edges: adjancency[nodea].append([nodea, cost] ) adjancency[nodea].append([nodea, cost] ) UpperCamelCase : Tuple = mst(snake_case_ ) UpperCamelCase : Tuple = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] for answer in expected: UpperCamelCase : Any = tuple(answer[:2] ) UpperCamelCase : Optional[int] = tuple(edge[::-1] ) assert edge in result or reverse in result
351
"""simple docstring""" import torch from transformers import AutoModel class lowerCamelCase ( torch.nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_="sayef/fsner-bert-base-uncased" ): super(SCREAMING_SNAKE_CASE_ , self ).__init__() UpperCamelCase : int = AutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.nn.CosineSimilarity(3 , 1e-08 ) UpperCamelCase : Any = torch.nn.Softmax(dim=1 ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return self.bert(**SCREAMING_SNAKE_CASE_ ).last_hidden_state def a_ ( self , SCREAMING_SNAKE_CASE_ ): return token_embeddings.sum(2 , keepdim=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1 ): return self.softmax(T * self.cos(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = W_supports["""sizes"""].tolist() UpperCamelCase : List[str] = W_supports["""start_token_id"""].item() UpperCamelCase : List[Any] = W_supports["""end_token_id"""].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCamelCase : List[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = None UpperCamelCase : Optional[Any] = None UpperCamelCase : Tuple = W_supports["""input_ids"""] == start_token_id UpperCamelCase : Optional[Any] = W_supports["""input_ids"""] == end_token_id for i, size in enumerate(SCREAMING_SNAKE_CASE_ ): if i == 0: UpperCamelCase : int = 0 else: UpperCamelCase : Optional[int] = support_sizes[i - 1] UpperCamelCase : Tuple = S[s : s + size][start_token_masks[s : s + size]] UpperCamelCase : int = S[s : s + size][end_token_masks[s : s + size]] UpperCamelCase : Dict = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCamelCase : Tuple = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCamelCase : List[str] = torch.vstack((p_starts, p_start) ) UpperCamelCase : Optional[Any] = torch.vstack((p_ends, p_end) ) else: UpperCamelCase : Optional[int] = p_start UpperCamelCase : Tuple = p_end return p_starts, p_ends
27
0
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=8 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=36 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase : List[str] = parent UpperCamelCase : Tuple = batch_size UpperCamelCase : Tuple = seq_length UpperCamelCase : str = is_training UpperCamelCase : List[Any] = use_input_mask UpperCamelCase : Optional[Any] = use_token_type_ids UpperCamelCase : Any = use_labels UpperCamelCase : Tuple = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : str = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : str = intermediate_size UpperCamelCase : Optional[Any] = hidden_act UpperCamelCase : Union[str, Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Tuple = type_vocab_size UpperCamelCase : Any = type_sequence_label_size UpperCamelCase : Optional[Any] = initializer_range UpperCamelCase : Optional[int] = num_labels UpperCamelCase : Optional[Any] = num_choices UpperCamelCase : Any = scope def a_ ( self ): UpperCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Optional[int] = None if self.use_input_mask: UpperCamelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : List[Any] = None if self.use_token_type_ids: UpperCamelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase : List[Any] = None UpperCamelCase : List[str] = None UpperCamelCase : Optional[Any] = None if self.use_labels: UpperCamelCase : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : int = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self ): return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , ) def a_ ( self ): UpperCamelCase : List[str] = self.get_config() UpperCamelCase : int = 300 return config def a_ ( self ): ( UpperCamelCase ) : Tuple = self.prepare_config_and_inputs() UpperCamelCase : str = True UpperCamelCase : Any = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = MraModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[Any] = True UpperCamelCase : int = MraModel(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Tuple = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , encoder_attention_mask=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = MraForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = MraForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Any = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = self.num_labels UpperCamelCase : Optional[int] = MraForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.num_labels UpperCamelCase : int = MraForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = self.num_choices UpperCamelCase : Union[str, Any] = MraForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[int] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Optional[int] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : List[str] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : str = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : Any = self.prepare_config_and_inputs() ( UpperCamelCase ) : Any = config_and_inputs UpperCamelCase : Union[str, Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Tuple = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) lowercase : List[str] = False lowercase : List[Any] = False lowercase : List[Any] = False lowercase : Optional[int] = False lowercase : List[Any] = () def a_ ( self ): UpperCamelCase : List[str] = MraModelTester(self ) UpperCamelCase : str = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase : Optional[int] = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Dict = MraModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @unittest.skip(reason="""MRA does not output attentions""" ) def a_ ( self ): return @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : List[str] = MraModel.from_pretrained("""uw-madison/mra-base-512-4""" ) UpperCamelCase : int = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : str = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) ) @slow def a_ ( self ): UpperCamelCase : Union[str, Any] = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-512-4""" ) UpperCamelCase : int = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[Any] = 5_0265 UpperCamelCase : Optional[int] = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) ) @slow def a_ ( self ): UpperCamelCase : Optional[Any] = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-4096-8-d3""" ) UpperCamelCase : List[str] = torch.arange(4096 ).unsqueeze(0 ) with torch.no_grad(): UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[Any] = 5_0265 UpperCamelCase : Any = torch.Size((1, 4096, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
352
"""simple docstring""" from typing import Any class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = data UpperCamelCase : Optional[Any] = None def __repr__( self ): return f'Node({self.data})' class lowerCamelCase : def __init__( self ): UpperCamelCase : Dict = None def __iter__( self ): UpperCamelCase : int = self.head while node: yield node.data UpperCamelCase : Union[str, Any] = node.next def __len__( self ): return sum(1 for _ in self ) def __repr__( self ): return "->".join([str(SCREAMING_SNAKE_CASE_ ) for item in self] ) def __getitem__( self , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) UpperCamelCase : List[Any] = self.head for _ in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = current.next UpperCamelCase : Optional[Any] = data def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(len(self ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(0 , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index <= len(self ): raise IndexError("""list index out of range""" ) UpperCamelCase : Optional[Any] = Node(SCREAMING_SNAKE_CASE_ ) if self.head is None: UpperCamelCase : Dict = new_node elif index == 0: UpperCamelCase : Any = self.head # link new_node to head UpperCamelCase : Any = new_node else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : str = temp.next UpperCamelCase : Any = temp.next UpperCamelCase : Optional[Any] = new_node def a_ ( self ): # print every node data print(self ) def a_ ( self ): return self.delete_nth(0 ) def a_ ( self ): # delete from tail return self.delete_nth(len(self ) - 1 ) def a_ ( self , SCREAMING_SNAKE_CASE_ = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("""List index out of range.""" ) UpperCamelCase : Union[str, Any] = self.head # default first node if index == 0: UpperCamelCase : Optional[Any] = self.head.next else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : int = temp.next UpperCamelCase : Optional[Any] = temp.next UpperCamelCase : Dict = temp.next.next return delete_node.data def a_ ( self ): return self.head is None def a_ ( self ): UpperCamelCase : Optional[Any] = None UpperCamelCase : Union[str, Any] = self.head while current: # Store the current node's next node. UpperCamelCase : Optional[int] = current.next # Make the current node's next point backwards UpperCamelCase : Optional[Any] = prev # Make the previous node be the current node UpperCamelCase : int = current # Make the current node the next node (to progress iteration) UpperCamelCase : Optional[int] = next_node # Return prev in order to put the head at the end UpperCamelCase : Optional[int] = prev def A_ ( ): '''simple docstring''' UpperCamelCase : int = LinkedList() assert linked_list.is_empty() is True assert str(snake_case_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(1_0 ): assert len(snake_case_ ) == i linked_list.insert_nth(snake_case_ ,i + 1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_1 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(1_1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(0 ,1_2 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 1_0 assert linked_list.delete_tail() == 1_1 assert len(snake_case_ ) == 9 assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_0 ) ) assert all(linked_list[i] == i + 1 for i in range(0 ,9 ) ) is True for i in range(0 ,9 ): UpperCamelCase : Optional[Any] = -i assert all(linked_list[i] == -i for i in range(0 ,9 ) ) is True linked_list.reverse() assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(-8 ,1 ) ) def A_ ( ): '''simple docstring''' UpperCamelCase : int = [ -9, 1_0_0, Node(7_7_3_4_5_1_1_2 ), """dlrow olleH""", 7, 5_5_5_5, 0, -192.55555, """Hello, world!""", 77.9, Node(1_0 ), None, None, 12.20, ] UpperCamelCase : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(snake_case_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(snake_case_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head UpperCamelCase : Dict = linked_list.delete_head() assert result == -9 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail UpperCamelCase : int = linked_list.delete_tail() assert result == 12.2 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list UpperCamelCase : Optional[Any] = linked_list.delete_nth(1_0 ) assert result is None assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("""Hello again, world!""" ) ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(snake_case_ ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(snake_case_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def A_ ( ): '''simple docstring''' from doctest import testmod testmod() UpperCamelCase : List[Any] = LinkedList() linked_list.insert_head(input("""Inserting 1st at head """ ).strip() ) linked_list.insert_head(input("""Inserting 2nd at head """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() linked_list.insert_tail(input("""\nInserting 1st at tail """ ).strip() ) linked_list.insert_tail(input("""Inserting 2nd at tail """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() print("""\nDelete head""" ) linked_list.delete_head() print("""Delete tail""" ) linked_list.delete_tail() print("""\nPrint list:""" ) linked_list.print_list() print("""\nReverse linked list""" ) linked_list.reverse() print("""\nPrint list:""" ) linked_list.print_list() print("""\nString representation of linked list:""" ) print(snake_case_ ) print("""\nReading/changing Node data using indexing:""" ) print(f'Element at Position 1: {linked_list[1]}' ) UpperCamelCase : List[Any] = input("""Enter New Value: """ ).strip() print("""New list:""" ) print(snake_case_ ) print(f'length of linked_list is : {len(snake_case_ )}' ) if __name__ == "__main__": main()
27
0
"""simple docstring""" import math class lowerCamelCase : def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = 0.0 UpperCamelCase : Dict = 0.0 for i in range(len(SCREAMING_SNAKE_CASE_ ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): for i in range(len(SCREAMING_SNAKE_CASE_ ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def A_ ( ): '''simple docstring''' UpperCamelCase : Tuple = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) UpperCamelCase : List[Any] = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training UpperCamelCase : Optional[Any] = SelfOrganizingMap() UpperCamelCase : Tuple = 3 UpperCamelCase : int = 0.5 for _ in range(snake_case_ ): for j in range(len(snake_case_ ) ): # training sample UpperCamelCase : int = training_samples[j] # Compute the winning vector UpperCamelCase : List[Any] = self_organizing_map.get_winner(snake_case_ ,snake_case_ ) # Update the winning vector UpperCamelCase : str = self_organizing_map.update(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) # classify test sample UpperCamelCase : List[Any] = [0, 0, 0, 1] UpperCamelCase : Optional[Any] = self_organizing_map.get_winner(snake_case_ ,snake_case_ ) # results print(f'Clusters that the test sample belongs to : {winner}' ) print(f'Weights that have been trained : {weights}' ) # running the main() function if __name__ == "__main__": main()
353
"""simple docstring""" import argparse import os import re __A : Dict = '''src/diffusers''' # Pattern that looks at the indentation in a line. __A : Union[str, Any] = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : Tuple = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Tuple = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Union[str, Any] = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Dict="" ,snake_case_ : Dict=None ,snake_case_ : Any=None ): '''simple docstring''' UpperCamelCase : Optional[int] = 0 UpperCamelCase : List[Any] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Optional[Any] = ["""\n""".join(lines[:index] )] else: UpperCamelCase : int = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Any = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Any = [lines[index + 1]] index += 1 else: UpperCamelCase : List[str] = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' def _inner(snake_case_ : Tuple ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[int]=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Dict ): return x if key is None: UpperCamelCase : int = noop # Constants are all uppercase, they go first. UpperCamelCase : List[Any] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : str = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : List[str] = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Tuple = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : int ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : List[Any] ): UpperCamelCase : Any = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : Union[str, Any] = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[str] = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : str = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : str = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Dict = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : int = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[Any] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : Optional[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[Any] = keys[:-1] UpperCamelCase : int = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Tuple ,snake_case_ : str=True ): '''simple docstring''' with open(snake_case_ ,"""r""" ) as f: UpperCamelCase : int = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : Dict = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Optional[Any] = main_blocks[block_idx] UpperCamelCase : Optional[int] = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : Union[str, Any] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : List[str] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Dict = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Union[str, Any] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : Optional[int] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Union[str, Any] = _re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Union[str, Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Optional[Any] = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : List[Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[Any] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: UpperCamelCase : str = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Any = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Union[str, Any] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : Any = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Any = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : str = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
0
"""simple docstring""" import numpy as np def A_ ( snake_case_ : np.array ): '''simple docstring''' return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
354
"""simple docstring""" def A_ ( snake_case_ : list[int] ): '''simple docstring''' if not numbers: return 0 if not isinstance(snake_case_ ,(list, tuple) ) or not all( isinstance(snake_case_ ,snake_case_ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) UpperCamelCase : int = numbers[0] for i in range(1 ,len(snake_case_ ) ): # update the maximum and minimum subarray products UpperCamelCase : List[str] = numbers[i] if number < 0: UpperCamelCase , UpperCamelCase : Optional[int] = min_till_now, max_till_now UpperCamelCase : Dict = max(snake_case_ ,max_till_now * number ) UpperCamelCase : Union[str, Any] = min(snake_case_ ,min_till_now * number ) # update the maximum product found till now UpperCamelCase : Union[str, Any] = max(snake_case_ ,snake_case_ ) return max_prod
27
0
"""simple docstring""" import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __A : int = logging.get_logger(__name__) __A : Optional[int] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } __A : Optional[int] = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Dict ,snake_case_ : Tuple ,snake_case_ : Optional[int] ,snake_case_ : List[Any] ): '''simple docstring''' for attribute in key.split(""".""" ): UpperCamelCase : str = getattr(snake_case_ ,snake_case_ ) if weight_type is not None: UpperCamelCase : Dict = getattr(snake_case_ ,snake_case_ ).shape else: UpperCamelCase : List[str] = hf_pointer.shape assert hf_shape == value.shape, ( f'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' f' {value.shape} for {full_name}' ) if weight_type == "weight": UpperCamelCase : int = value elif weight_type == "weight_g": UpperCamelCase : str = value elif weight_type == "weight_v": UpperCamelCase : Union[str, Any] = value elif weight_type == "bias": UpperCamelCase : Union[str, Any] = value else: UpperCamelCase : int = value logger.info(f'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def A_ ( snake_case_ : List[str] ,snake_case_ : int ): '''simple docstring''' UpperCamelCase : Optional[Any] = [] UpperCamelCase : str = fairseq_model.state_dict() UpperCamelCase : List[str] = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight UpperCamelCase : str = None for name, value in fairseq_dict.items(): UpperCamelCase : Optional[Any] = False if "conv_layers" in name: load_conv_layer( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,hf_model.config.feat_extract_norm == """group""" ,) UpperCamelCase : List[str] = True elif name.split(""".""" )[0] == "proj": UpperCamelCase : Optional[Any] = fairseq_model.proj UpperCamelCase : Optional[Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: UpperCamelCase : Optional[int] = True if "*" in mapped_key: UpperCamelCase : Optional[Any] = name.split(snake_case_ )[0].split(""".""" )[-2] UpperCamelCase : List[str] = mapped_key.replace("""*""" ,snake_case_ ) if "weight_g" in name: UpperCamelCase : str = """weight_g""" elif "weight_v" in name: UpperCamelCase : Optional[int] = """weight_v""" elif "bias" in name: UpperCamelCase : List[str] = """bias""" elif "weight" in name: UpperCamelCase : List[str] = """weight""" else: UpperCamelCase : int = None set_recursively(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) continue if not is_used: unused_weights.append(snake_case_ ) logger.warning(f'Unused weights: {unused_weights}' ) return proj_weight def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Dict ,snake_case_ : List[str] ,snake_case_ : Any ,snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : List[str] = full_name.split("""conv_layers.""" )[-1] UpperCamelCase : int = name.split(""".""" ) UpperCamelCase : Any = int(items[0] ) UpperCamelCase : Union[str, Any] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) UpperCamelCase : List[Any] = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) UpperCamelCase : List[str] = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was' " found." ) UpperCamelCase : Optional[int] = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) UpperCamelCase : Tuple = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(snake_case_ ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : str = emb.weight.shape UpperCamelCase : Union[str, Any] = nn.Linear(snake_case_ ,snake_case_ ,bias=snake_case_ ) UpperCamelCase : List[str] = emb.weight.data return lin_layer def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' with open(snake_case_ ,"""r""" ,encoding="""utf-8""" ) as f: UpperCamelCase : int = f.readlines() UpperCamelCase : List[Any] = [line.split(""" """ )[0] for line in lines] UpperCamelCase : int = len(snake_case_ ) UpperCamelCase : List[str] = { """<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3, } vocab_dict.update(dict(zip(snake_case_ ,range(4 ,num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def A_ ( snake_case_ : Optional[Any] ,snake_case_ : List[str] ,snake_case_ : Tuple ,snake_case_ : Any ,snake_case_ : Any ,snake_case_ : Optional[Any] ,snake_case_ : Optional[Any] ,): '''simple docstring''' UpperCamelCase : List[Any] = WavaVecaConfig.from_pretrained(snake_case_ ) UpperCamelCase : Tuple = SpeechaTextaConfig.from_pretrained( snake_case_ ,vocab_size=snake_case_ ,decoder_layers=snake_case_ ,do_stable_layer_norm=snake_case_ ) UpperCamelCase : List[str] = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=1_6_0_0_0 ,padding_value=0 ,do_normalize=snake_case_ ,return_attention_mask=snake_case_ ,) UpperCamelCase : Union[str, Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) UpperCamelCase : Any = model[0].eval() # set weights for wav2vec2 encoder UpperCamelCase : Optional[int] = WavaVecaModel(snake_case_ ) UpperCamelCase : List[str] = recursively_load_weights_wavaveca(model.encoder ,snake_case_ ) UpperCamelCase : List[Any] = SpeechaTextaForCausalLM(snake_case_ ) UpperCamelCase : Tuple = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() ,strict=snake_case_ ) # set output linear layer unexpected_keys.remove("""embed_out""" ) UpperCamelCase : Any = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f'The following keys are missing when loading the decoder weights: {missing_keys}' ) logger.warning(f'The following keys are unexpected when loading the decoder weights: {unexpected_keys}' ) UpperCamelCase : Tuple = SpeechEncoderDecoderModel(encoder=snake_case_ ,decoder=snake_case_ ) UpperCamelCase : Dict = False # add projection layer UpperCamelCase : Optional[Any] = nn.Parameter(projection_layer.weight ) UpperCamelCase : int = nn.Parameter(projection_layer.bias ) UpperCamelCase : Optional[Any] = create_vocab_dict(snake_case_ ) with open(os.path.join(snake_case_ ,"""vocab.json""" ) ,"""w""" ) as fp: json.dump(snake_case_ ,snake_case_ ) UpperCamelCase : List[str] = SpeechaTextaTokenizer(os.path.join(snake_case_ ,"""vocab.json""" ) ) tokenizer.save_pretrained(snake_case_ ) UpperCamelCase : Dict = hf_wavavec.config.to_dict() UpperCamelCase : str = tokenizer.pad_token_id UpperCamelCase : List[str] = tokenizer.bos_token_id UpperCamelCase : List[Any] = tokenizer.eos_token_id UpperCamelCase : int = """speech_to_text_2""" UpperCamelCase : Any = """wav2vec2""" UpperCamelCase : str = SpeechEncoderDecoderConfig.from_dict(snake_case_ ) hf_wavavec.save_pretrained(snake_case_ ) feature_extractor.save_pretrained(snake_case_ ) if __name__ == "__main__": __A : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument( '''--encoder_config_path''', default='''facebook/wav2vec2-large-lv60''', type=str, help='''Path to hf encoder wav2vec2 checkpoint config''', ) parser.add_argument( '''--decoder_config_path''', default='''facebook/s2t-small-mustc-en-fr-st''', type=str, help='''Path to hf decoder s2t checkpoint config''', ) parser.add_argument('''--vocab_size''', default=10224, type=int, help='''Vocab size of decoder''') parser.add_argument('''--num_decoder_layers''', default=7, type=int, help='''Number of decoder layers''') __A : List[str] = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
355
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Any = AudioLDMPipeline lowercase : Union[str, Any] = TEXT_TO_AUDIO_PARAMS lowercase : List[str] = TEXT_TO_AUDIO_BATCH_PARAMS lowercase : Tuple = frozenset( [ 'num_inference_steps', 'num_waveforms_per_prompt', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=(32, 64) , class_embed_type="""simple_projection""" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[Any] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , ) torch.manual_seed(0 ) UpperCamelCase : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCamelCase : int = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) UpperCamelCase : Optional[int] = ClapTextModelWithProjection(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta""" , model_max_length=77 ) UpperCamelCase : Tuple = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """vocoder""": vocoder, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Any = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """prompt""": """A hammer hitting a wooden surface""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, } return inputs def a_ ( self ): UpperCamelCase : str = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Any = self.get_dummy_components() UpperCamelCase : int = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Tuple = audio[:10] UpperCamelCase : Dict = np.array( [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[str] = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Optional[int] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) UpperCamelCase : Tuple = prompt_embeds # forward UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : List[str] = self.get_dummy_components() UpperCamelCase : List[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * ["""this is a negative prompt"""] UpperCamelCase : List[Any] = negative_prompt UpperCamelCase : str = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : str = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] UpperCamelCase : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[Any] = [] for p in [prompt, negative_prompt]: UpperCamelCase : int = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Union[str, Any] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = text_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) embeds.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Tuple = embeds # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Optional[int] = self.get_dummy_components() UpperCamelCase : List[str] = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = """egg cracking""" UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Union[str, Any] = audio[:10] UpperCamelCase : Dict = np.array( [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Union[str, Any] = self.get_dummy_components() UpperCamelCase : Tuple = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = """A hammer hitting a wooden surface""" # test num_waveforms_per_prompt=1 (default) UpperCamelCase : List[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts UpperCamelCase : Dict = 2 UpperCamelCase : List[str] = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt UpperCamelCase : List[str] = 2 UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts UpperCamelCase : Any = 2 UpperCamelCase : str = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = audioldm_pipe.vocoder.config.sampling_rate UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe(audio_length_in_s=0.016 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.016 UpperCamelCase : Optional[Any] = audioldm_pipe(audio_length_in_s=0.032 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.032 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Optional[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = ["""hey"""] UpperCamelCase : Dict = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : str = output.audios.shape assert audio_shape == (1, 256) UpperCamelCase : Optional[Any] = audioldm_pipe.vocoder.config config.model_in_dim *= 2 UpperCamelCase : str = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : List[str] = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def a_ ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self._test_inference_batch_single_identical(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def a_ ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @slow class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="cpu" , SCREAMING_SNAKE_CASE_=torch.floataa , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : str = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = np.random.RandomState(SCREAMING_SNAKE_CASE_ ).standard_normal((1, 8, 128, 16) ) UpperCamelCase : int = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = { """prompt""": """A hammer hitting a wooden surface""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 2.5, } return inputs def a_ ( self ): UpperCamelCase : Optional[int] = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = 25 UpperCamelCase : Optional[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[7_7230:7_7240] UpperCamelCase : Optional[Any] = np.array( [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] ) UpperCamelCase : Any = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def a_ ( self ): UpperCamelCase : Any = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : Any = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) UpperCamelCase : str = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[2_7780:2_7790] UpperCamelCase : Tuple = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] ) UpperCamelCase : Tuple = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
27
0
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def A_ ( snake_case_ : int ): # picklable for multiprocessing '''simple docstring''' return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def A_ ( ): '''simple docstring''' with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" UpperCamelCase : Optional[Any] = [1, 2, 3] with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=2 ) with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" ,[2, -1] ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : List[Any] = [1, 2] UpperCamelCase : List[Any] = {"""a""": 1, """b""": 2} UpperCamelCase : List[str] = {"""a""": [1, 2], """b""": [3, 4]} UpperCamelCase : Tuple = {"""a""": {"""1""": 1}, """b""": 2} UpperCamelCase : Any = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} UpperCamelCase : Optional[int] = [2, 3] UpperCamelCase : List[str] = {"""a""": 2, """b""": 3} UpperCamelCase : Any = {"""a""": [2, 3], """b""": [4, 5]} UpperCamelCase : Tuple = {"""a""": {"""1""": 2}, """b""": 3} UpperCamelCase : List[str] = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa
356
"""simple docstring""" import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def A_ ( snake_case_ : Dataset ,snake_case_ : Dict[str, str] ): '''simple docstring''' UpperCamelCase : List[str] = args.log_outputs UpperCamelCase : Tuple = """_""".join(args.dataset.split("""/""" ) + [args.config, args.split] ) # load metric UpperCamelCase : List[Any] = load_metric("""wer""" ) UpperCamelCase : Any = load_metric("""cer""" ) # compute metrics UpperCamelCase : str = wer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) UpperCamelCase : Dict = cer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) # print & log results UpperCamelCase : Optional[int] = f'WER: {wer_result}\nCER: {cer_result}' print(snake_case_ ) with open(f'{dataset_id}_eval_results.txt' ,"""w""" ) as f: f.write(snake_case_ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: UpperCamelCase : Optional[Any] = f'log_{dataset_id}_predictions.txt' UpperCamelCase : str = f'log_{dataset_id}_targets.txt' with open(snake_case_ ,"""w""" ) as p, open(snake_case_ ,"""w""" ) as t: # mapping function to write output def write_to_file(snake_case_ : Union[str, Any] ,snake_case_ : Tuple ): p.write(f'{i}' + """\n""" ) p.write(batch["""prediction"""] + """\n""" ) t.write(f'{i}' + """\n""" ) t.write(batch["""target"""] + """\n""" ) result.map(snake_case_ ,with_indices=snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Dict = """[,?.!\-\;\:\"“%‘”�—’…–]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training UpperCamelCase : str = re.sub(snake_case_ ,"""""" ,text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! UpperCamelCase : List[str] = ["""\n\n""", """\n""", """ """, """ """] for t in token_sequences_to_ignore: UpperCamelCase : Tuple = """ """.join(text.split(snake_case_ ) ) return text def A_ ( snake_case_ : str ): '''simple docstring''' # load dataset UpperCamelCase : Union[str, Any] = load_dataset(args.dataset ,args.config ,split=args.split ,use_auth_token=snake_case_ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor UpperCamelCase : List[Any] = AutoFeatureExtractor.from_pretrained(args.model_id ) UpperCamelCase : Dict = feature_extractor.sampling_rate # resample audio UpperCamelCase : Optional[Any] = dataset.cast_column("""audio""" ,Audio(sampling_rate=snake_case_ ) ) # load eval pipeline if args.device is None: UpperCamelCase : int = 0 if torch.cuda.is_available() else -1 UpperCamelCase : Union[str, Any] = pipeline("""automatic-speech-recognition""" ,model=args.model_id ,device=args.device ) # map function to decode audio def map_to_pred(snake_case_ : Union[str, Any] ): UpperCamelCase : List[Any] = asr( batch["""audio"""]["""array"""] ,chunk_length_s=args.chunk_length_s ,stride_length_s=args.stride_length_s ) UpperCamelCase : Union[str, Any] = prediction["""text"""] UpperCamelCase : Optional[Any] = normalize_text(batch["""sentence"""] ) return batch # run inference on all examples UpperCamelCase : Any = dataset.map(snake_case_ ,remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(snake_case_ ,snake_case_ ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() parser.add_argument( '''--model_id''', type=str, required=True, help='''Model identifier. Should be loadable with 🤗 Transformers''' ) parser.add_argument( '''--dataset''', type=str, required=True, help='''Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets''', ) parser.add_argument( '''--config''', type=str, required=True, help='''Config of the dataset. *E.g.* `\'en\'` for Common Voice''' ) parser.add_argument('''--split''', type=str, required=True, help='''Split of the dataset. *E.g.* `\'test\'`''') parser.add_argument( '''--chunk_length_s''', type=float, default=None, help='''Chunk length in seconds. Defaults to 5 seconds.''' ) parser.add_argument( '''--stride_length_s''', type=float, default=None, help='''Stride of the audio chunks. Defaults to 1 second.''' ) parser.add_argument( '''--log_outputs''', action='''store_true''', help='''If defined, write outputs to log file for analysis.''' ) parser.add_argument( '''--device''', type=int, default=None, help='''The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.''', ) __A : Optional[Any] = parser.parse_args() main(args)
27
0
import contextlib from multiprocessing import Pool, RLock from tqdm.auto import tqdm from ..utils import experimental, logging __A : Optional[int] = logging.get_logger(__name__) class lowerCamelCase : lowercase : List[str] = None @experimental def A_ ( snake_case_ : Dict ,snake_case_ : Tuple ,snake_case_ : Any ,snake_case_ : str ,snake_case_ : Union[str, Any] ,snake_case_ : List[Any] ,snake_case_ : Optional[int] ): '''simple docstring''' if ParallelBackendConfig.backend_name is None: return _map_with_multiprocessing_pool( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) return _map_with_joblib(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) def A_ ( snake_case_ : List[str] ,snake_case_ : str ,snake_case_ : str ,snake_case_ : List[str] ,snake_case_ : Optional[int] ,snake_case_ : Optional[Any] ,snake_case_ : Union[str, Any] ): '''simple docstring''' UpperCamelCase : Optional[int] = num_proc if num_proc <= len(snake_case_ ) else len(snake_case_ ) UpperCamelCase : List[Any] = [] # We organize the splits ourselve (contiguous splits) for index in range(snake_case_ ): UpperCamelCase : Union[str, Any] = len(snake_case_ ) // num_proc UpperCamelCase : Optional[Any] = len(snake_case_ ) % num_proc UpperCamelCase : str = div * index + min(snake_case_ ,snake_case_ ) UpperCamelCase : int = start + div + (1 if index < mod else 0) split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc) ) if len(snake_case_ ) != sum(len(i[1] ) for i in split_kwds ): raise ValueError( f'Error dividing inputs iterable among processes. ' f'Total number of objects {len(snake_case_ )}, ' f'length: {sum(len(i[1] ) for i in split_kwds )}' ) logger.info( f'Spawning {num_proc} processes for {len(snake_case_ )} objects in slices of {[len(i[1] ) for i in split_kwds]}' ) UpperCamelCase : Optional[int] = None, None if not disable_tqdm: UpperCamelCase : List[str] = (RLock(),), tqdm.set_lock with Pool(snake_case_ ,initargs=snake_case_ ,initializer=snake_case_ ) as pool: UpperCamelCase : Optional[int] = pool.map(snake_case_ ,snake_case_ ) logger.info(f'Finished {num_proc} processes' ) UpperCamelCase : Optional[int] = [obj for proc_res in mapped for obj in proc_res] logger.info(f'Unpacked {len(snake_case_ )} objects' ) return mapped def A_ ( snake_case_ : Tuple ,snake_case_ : int ,snake_case_ : str ,snake_case_ : List[Any] ,snake_case_ : Any ,snake_case_ : Tuple ,snake_case_ : int ): '''simple docstring''' import joblib with joblib.parallel_backend(ParallelBackendConfig.backend_name ,n_jobs=snake_case_ ): return joblib.Parallel()( joblib.delayed(snake_case_ )((function, obj, types, None, True, None) ) for obj in iterable ) @experimental @contextlib.contextmanager def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : List[str] = backend_name if backend_name == "spark": from joblibspark import register_spark register_spark() # TODO: call create_cache_and_write_probe if "download" in steps # TODO: raise NotImplementedError when Dataset.map etc is called try: yield finally: UpperCamelCase : List[Any] = None
357
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'EncodecFeatureExtractor' lowercase : List[Any] = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.feature_extractor UpperCamelCase : Any = False def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True ): return self.tokenizer.get_decoder_prompt_ids(task=SCREAMING_SNAKE_CASE_ , language=SCREAMING_SNAKE_CASE_ , no_timestamps=SCREAMING_SNAKE_CASE_ ) def __call__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = kwargs.pop("""sampling_rate""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Any = args[0] UpperCamelCase : str = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if text is not None: UpperCamelCase : Optional[int] = self.tokenizer(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is not None: UpperCamelCase : str = self.feature_extractor(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is None: return inputs elif text is None: return audio_inputs else: UpperCamelCase : int = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: UpperCamelCase : Optional[Any] = audio_inputs["""padding_mask"""] return inputs def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = kwargs.pop("""padding_mask""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Optional[int] = args[0] UpperCamelCase : Any = args[1:] if audio_values is not None: return self._decode_audio(SCREAMING_SNAKE_CASE_ , padding_mask=SCREAMING_SNAKE_CASE_ ) else: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = to_numpy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase : int = audio_values.shape if padding_mask is None: return list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = to_numpy(SCREAMING_SNAKE_CASE_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) UpperCamelCase : List[str] = seq_len - padding_mask.shape[-1] UpperCamelCase : Optional[int] = 1 - self.feature_extractor.padding_value UpperCamelCase : Any = np.pad(SCREAMING_SNAKE_CASE_ , ((0, 0), (0, difference)) , """constant""" , constant_values=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audio_values.tolist() for i in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] UpperCamelCase : Optional[Any] = sliced_audio.reshape(SCREAMING_SNAKE_CASE_ , -1 ) return audio_values
27
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import DistilBertConfig, 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.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : List[str] = parent UpperCamelCase : Tuple = 13 UpperCamelCase : Optional[Any] = 7 UpperCamelCase : List[Any] = True UpperCamelCase : List[str] = True UpperCamelCase : str = False UpperCamelCase : Dict = True UpperCamelCase : Tuple = 99 UpperCamelCase : int = 32 UpperCamelCase : Any = 2 UpperCamelCase : Union[str, Any] = 4 UpperCamelCase : Optional[int] = 37 UpperCamelCase : Any = """gelu""" UpperCamelCase : Any = 0.1 UpperCamelCase : Any = 0.1 UpperCamelCase : Optional[int] = 512 UpperCamelCase : List[Any] = 16 UpperCamelCase : Any = 2 UpperCamelCase : List[Any] = 0.02 UpperCamelCase : List[str] = 3 UpperCamelCase : int = 4 UpperCamelCase : str = None def a_ ( self ): UpperCamelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Any = None if self.use_input_mask: UpperCamelCase : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Tuple = None UpperCamelCase : List[str] = None UpperCamelCase : Any = None if self.use_labels: UpperCamelCase : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : str = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : List[Any] = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = TFDistilBertModel(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = {"""input_ids""": input_ids, """attention_mask""": input_mask} UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = [input_ids, input_mask] UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = TFDistilBertForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = {"""input_ids""": input_ids, """attention_mask""": input_mask} UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = TFDistilBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """input_ids""": input_ids, """attention_mask""": input_mask, } UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = self.num_labels UpperCamelCase : Tuple = TFDistilBertForSequenceClassification(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = {"""input_ids""": input_ids, """attention_mask""": input_mask} UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.num_choices UpperCamelCase : Tuple = TFDistilBertForMultipleChoice(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase : Tuple = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase : Union[str, Any] = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, } UpperCamelCase : str = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = self.num_labels UpperCamelCase : str = TFDistilBertForTokenClassification(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self ): UpperCamelCase : int = self.prepare_config_and_inputs() (UpperCamelCase) : int = config_and_inputs UpperCamelCase : str = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Tuple = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) lowercase : Tuple = ( { 'feature-extraction': TFDistilBertModel, 'fill-mask': TFDistilBertForMaskedLM, 'question-answering': TFDistilBertForQuestionAnswering, 'text-classification': TFDistilBertForSequenceClassification, 'token-classification': TFDistilBertForTokenClassification, 'zero-shot': TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) lowercase : Any = False lowercase : int = False def a_ ( self ): UpperCamelCase : Any = TFDistilBertModelTester(self ) UpperCamelCase : Optional[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): UpperCamelCase : Optional[int] = TFDistilBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_tf class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : List[str] = TFDistilBertModel.from_pretrained("""distilbert-base-uncased""" ) UpperCamelCase : Union[str, Any] = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : List[Any] = [1, 6, 768] self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = tf.constant( [ [ [0.19261885, -0.13732955, 0.4119799], [0.22150156, -0.07422661, 0.39037204], [0.22756018, -0.0896414, 0.3701467], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 )
358
"""simple docstring""" import requests from bsa import BeautifulSoup def A_ ( snake_case_ : str = "https://www.worldometers.info/coronavirus" ): '''simple docstring''' UpperCamelCase : Any = BeautifulSoup(requests.get(snake_case_ ).text ,"""html.parser""" ) UpperCamelCase : Optional[int] = soup.findAll("""h1""" ) UpperCamelCase : List[Any] = soup.findAll("""div""" ,{"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" ,{"""class""": """panel-title"""} ) values += soup.findAll("""div""" ,{"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(snake_case_ ,snake_case_ )} if __name__ == "__main__": print('''\033[1m''' + '''COVID-19 Status of the World''' + '''\033[0m\n''') for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
27
0
import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py __A : Tuple = '''src/diffusers''' # Matches is_xxx_available() __A : List[str] = re.compile(R'''is\_([a-z_]*)_available\(\)''') # Matches from xxx import bla __A : Union[str, Any] = re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') __A : List[str] = ''' {0} = None ''' __A : Dict = ''' class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, {1}) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, {1}) ''' __A : List[str] = ''' def {0}(*args, **kwargs): requires_backends({0}, {1}) ''' def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Any = _re_backend.findall(snake_case_ ) if len(snake_case_ ) == 0: return None return "_and_".join(snake_case_ ) def A_ ( ): '''simple docstring''' with open(os.path.join(snake_case_ ,"""__init__.py""" ) ,"""r""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: UpperCamelCase : Tuple = f.readlines() # Get to the point we do the actual imports for type checking UpperCamelCase : Dict = 0 UpperCamelCase : Dict = {} # Go through the end of the file while line_index < len(snake_case_ ): # If the line contains is_backend_available, we grab all objects associated with the `else` block UpperCamelCase : Dict = find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith("""else:""" ): line_index += 1 line_index += 1 UpperCamelCase : List[str] = [] # Until we unindent, add backend objects to the list while line_index < len(snake_case_ ) and len(lines[line_index] ) > 1: UpperCamelCase : List[Any] = lines[line_index] UpperCamelCase : Dict = _re_single_line_import.search(snake_case_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(snake_case_ ) > 0: UpperCamelCase : Dict = objects else: line_index += 1 return backend_specific_objects def A_ ( snake_case_ : Tuple ,snake_case_ : str ): '''simple docstring''' if name.isupper(): return DUMMY_CONSTANT.format(snake_case_ ) elif name.islower(): return DUMMY_FUNCTION.format(snake_case_ ,snake_case_ ) else: return DUMMY_CLASS.format(snake_case_ ,snake_case_ ) def A_ ( snake_case_ : Union[str, Any]=None ): '''simple docstring''' if backend_specific_objects is None: UpperCamelCase : Optional[Any] = read_init() # For special correspondence backend to module name as used in the function requires_modulename UpperCamelCase : str = {} for backend, objects in backend_specific_objects.items(): UpperCamelCase : Optional[int] = """[""" + """, """.join(f'"{b}"' for b in backend.split("""_and_""" ) ) + """]""" UpperCamelCase : Tuple = """# This file is autogenerated by the command `make fix-copies`, do not edit.\n""" dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(snake_case_ ,snake_case_ ) for o in objects] ) UpperCamelCase : str = dummy_file return dummy_files def A_ ( snake_case_ : Tuple=False ): '''simple docstring''' UpperCamelCase : int = create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py UpperCamelCase : Any = {"""torch""": """pt"""} # Locate actual dummy modules and read their content. UpperCamelCase : Any = os.path.join(snake_case_ ,"""utils""" ) UpperCamelCase : str = { backend: os.path.join(snake_case_ ,f'dummy_{short_names.get(snake_case_ ,snake_case_ )}_objects.py' ) for backend in dummy_files.keys() } UpperCamelCase : Dict = {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(snake_case_ ): with open(snake_case_ ,"""r""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: UpperCamelCase : int = f.read() else: UpperCamelCase : str = """""" for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( f'Updating diffusers.utils.dummy_{short_names.get(snake_case_ ,snake_case_ )}_objects.py as the main ' """__init__ has new objects.""" ) with open(dummy_file_paths[backend] ,"""w""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: f.write(dummy_files[backend] ) else: raise ValueError( """The main __init__ has objects that are not present in """ f'diffusers.utils.dummy_{short_names.get(snake_case_ ,snake_case_ )}_objects.py. Run `make fix-copies` ' """to fix this.""" ) if __name__ == "__main__": __A : Dict = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') __A : Tuple = parser.parse_args() check_dummies(args.fix_and_overwrite)
359
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=1 , ): UpperCamelCase : Tuple = parent UpperCamelCase : Optional[int] = batch_size UpperCamelCase : Optional[Any] = seq_length UpperCamelCase : int = is_training UpperCamelCase : Union[str, Any] = use_input_mask UpperCamelCase : Union[str, Any] = use_token_type_ids UpperCamelCase : Dict = use_labels UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : Tuple = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : int = intermediate_size UpperCamelCase : str = hidden_act UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Optional[Any] = type_vocab_size UpperCamelCase : int = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : Dict = num_labels UpperCamelCase : Tuple = num_choices UpperCamelCase : Optional[int] = scope UpperCamelCase : List[Any] = q_groups UpperCamelCase : Tuple = k_groups UpperCamelCase : Any = v_groups UpperCamelCase : List[str] = post_attention_groups UpperCamelCase : Tuple = intermediate_groups UpperCamelCase : int = output_groups def a_ ( self ): UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Tuple = None if self.use_input_mask: UpperCamelCase : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Optional[int] = None UpperCamelCase : List[Any] = None UpperCamelCase : Dict = None if self.use_labels: UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self ): return SqueezeBertConfig( embedding_size=self.hidden_size , vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = SqueezeBertModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = SqueezeBertForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = SqueezeBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : str = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.num_labels UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.num_labels UpperCamelCase : str = SqueezeBertForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = self.num_choices UpperCamelCase : Tuple = SqueezeBertForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = config_and_inputs UpperCamelCase : Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) lowercase : Dict = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) lowercase : Dict = False lowercase : str = True lowercase : str = False def a_ ( self ): UpperCamelCase : Any = SqueezeBertModelTester(self ) UpperCamelCase : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Optional[Any] = SqueezeBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_sentencepiece @require_tokenizers @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification.from_pretrained("""squeezebert/squeezebert-mnli""" ) UpperCamelCase : Dict = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]] ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[Any] = torch.Size((1, 3) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
27
0
"""simple docstring""" import math import os import sys def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Union[str, Any] = """""" try: with open(snake_case_ ,"""rb""" ) as binary_file: UpperCamelCase : Any = binary_file.read() for dat in data: UpperCamelCase : int = f'{dat:08b}' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def A_ ( snake_case_ : dict[str, str] ,snake_case_ : str ,snake_case_ : int ,snake_case_ : str ): '''simple docstring''' lexicon.pop(snake_case_ ) UpperCamelCase : Union[str, Any] = last_match_id if math.loga(snake_case_ ).is_integer(): for curr_key in lexicon: UpperCamelCase : Any = """0""" + lexicon[curr_key] UpperCamelCase : int = bin(snake_case_ )[2:] def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : str = {"""0""": """0""", """1""": """1"""} UpperCamelCase : Dict = """""", """""" UpperCamelCase : Optional[int] = len(snake_case_ ) for i in range(len(snake_case_ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue UpperCamelCase : Tuple = lexicon[curr_string] result += last_match_id add_key_to_lexicon(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) index += 1 UpperCamelCase : Any = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": UpperCamelCase : Dict = lexicon[curr_string] result += last_match_id return result def A_ ( snake_case_ : str ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : str = os.path.getsize(snake_case_ ) UpperCamelCase : Union[str, Any] = bin(snake_case_ )[2:] UpperCamelCase : List[str] = len(snake_case_ ) return "0" * (length_length - 1) + file_length_binary + compressed def A_ ( snake_case_ : str ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : int = 8 try: with open(snake_case_ ,"""wb""" ) as opened_file: UpperCamelCase : Dict = [ to_write[i : i + byte_length] for i in range(0 ,len(snake_case_ ) ,snake_case_ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(snake_case_ ,2 ).to_bytes(1 ,byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def A_ ( snake_case_ : str ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : List[str] = read_file_binary(snake_case_ ) UpperCamelCase : Optional[int] = compress_data(snake_case_ ) UpperCamelCase : Any = add_file_length(snake_case_ ,snake_case_ ) write_file_binary(snake_case_ ,snake_case_ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
360
"""simple docstring""" from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class lowerCamelCase ( nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 88 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "geglu" , SCREAMING_SNAKE_CASE_ = None , ): super().__init__() UpperCamelCase : int = nn.ModuleList( [ TransformeraDModel( num_attention_heads=SCREAMING_SNAKE_CASE_ , attention_head_dim=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , dropout=SCREAMING_SNAKE_CASE_ , norm_num_groups=SCREAMING_SNAKE_CASE_ , cross_attention_dim=SCREAMING_SNAKE_CASE_ , attention_bias=SCREAMING_SNAKE_CASE_ , sample_size=SCREAMING_SNAKE_CASE_ , num_vector_embeds=SCREAMING_SNAKE_CASE_ , activation_fn=SCREAMING_SNAKE_CASE_ , num_embeds_ada_norm=SCREAMING_SNAKE_CASE_ , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference UpperCamelCase : Optional[Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` UpperCamelCase : List[Any] = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` UpperCamelCase : int = [1, 0] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = True , ): UpperCamelCase : Dict = hidden_states UpperCamelCase : Optional[Any] = [] UpperCamelCase : List[Any] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens UpperCamelCase : Optional[int] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] UpperCamelCase : str = self.transformer_index_for_condition[i] UpperCamelCase : Any = self.transformers[transformer_index]( SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , timestep=SCREAMING_SNAKE_CASE_ , cross_attention_kwargs=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] UpperCamelCase : Any = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) UpperCamelCase : List[str] = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=SCREAMING_SNAKE_CASE_ )
27
0
def A_ ( snake_case_ : list[int] ): '''simple docstring''' if not numbers: return 0 if not isinstance(snake_case_ ,(list, tuple) ) or not all( isinstance(snake_case_ ,snake_case_ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) UpperCamelCase : int = numbers[0] for i in range(1 ,len(snake_case_ ) ): # update the maximum and minimum subarray products UpperCamelCase : List[str] = numbers[i] if number < 0: UpperCamelCase : Optional[int] = min_till_now, max_till_now UpperCamelCase : Dict = max(snake_case_ ,max_till_now * number ) UpperCamelCase : Union[str, Any] = min(snake_case_ ,min_till_now * number ) # update the maximum product found till now UpperCamelCase : Union[str, Any] = max(snake_case_ ,snake_case_ ) return max_prod
361
"""simple docstring""" import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : Optional[int] = { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json''', } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[int] = 'mvp' lowercase : Optional[Any] = ['past_key_values'] lowercase : Union[str, Any] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , SCREAMING_SNAKE_CASE_=5_0267 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=100 , SCREAMING_SNAKE_CASE_=800 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Dict = max_position_embeddings UpperCamelCase : Optional[int] = d_model UpperCamelCase : Optional[Any] = encoder_ffn_dim UpperCamelCase : Any = encoder_layers UpperCamelCase : List[Any] = encoder_attention_heads UpperCamelCase : Optional[Any] = decoder_ffn_dim UpperCamelCase : Optional[int] = decoder_layers UpperCamelCase : Dict = decoder_attention_heads UpperCamelCase : List[str] = dropout UpperCamelCase : List[str] = attention_dropout UpperCamelCase : List[Any] = activation_dropout UpperCamelCase : Dict = activation_function UpperCamelCase : List[str] = init_std UpperCamelCase : int = encoder_layerdrop UpperCamelCase : Dict = decoder_layerdrop UpperCamelCase : Any = classifier_dropout UpperCamelCase : Tuple = use_cache UpperCamelCase : Dict = encoder_layers UpperCamelCase : Tuple = scale_embedding # scale factor will be sqrt(d_model) if True UpperCamelCase : Optional[Any] = use_prompt UpperCamelCase : Any = prompt_length UpperCamelCase : List[Any] = prompt_mid_dim super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , forced_eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated""" , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = self.bos_token_id warnings.warn( f'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ' """The config can simply be saved and uploaded again to be fixed.""" )
27
0
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' UpperCamelCase : Optional[Any] = [], [] while len(snake_case_ ) > 1: UpperCamelCase : Optional[Any] = min(snake_case_ ), max(snake_case_ ) start.append(snake_case_ ) end.append(snake_case_ ) collection.remove(snake_case_ ) collection.remove(snake_case_ ) end.reverse() return start + collection + end if __name__ == "__main__": __A : Union[str, Any] = input('''Enter numbers separated by a comma:\n''').strip() __A : Union[str, Any] = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
362
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __A : Optional[Any] = 16 __A : str = 32 def A_ ( snake_case_ : Accelerator ,snake_case_ : int = 1_6 ): '''simple docstring''' UpperCamelCase : Tuple = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCamelCase : Optional[int] = load_dataset("""glue""" ,"""mrpc""" ) def tokenize_function(snake_case_ : List[Any] ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase : Union[str, Any] = tokenizer(examples["""sentence1"""] ,examples["""sentence2"""] ,truncation=snake_case_ ,max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase : Optional[Any] = datasets.map( snake_case_ ,batched=snake_case_ ,remove_columns=["""idx""", """sentence1""", """sentence2"""] ,) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase : str = tokenized_datasets.rename_column("""label""" ,"""labels""" ) def collate_fn(snake_case_ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase : Optional[Any] = 1_6 elif accelerator.mixed_precision != "no": UpperCamelCase : Any = 8 else: UpperCamelCase : Optional[Any] = None return tokenizer.pad( snake_case_ ,padding="""longest""" ,max_length=snake_case_ ,pad_to_multiple_of=snake_case_ ,return_tensors="""pt""" ,) # Instantiate dataloaders. UpperCamelCase : str = DataLoader( tokenized_datasets["""train"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) UpperCamelCase : Dict = DataLoader( tokenized_datasets["""validation"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders __A : int = mocked_dataloaders # noqa: F811 def A_ ( snake_case_ : Tuple ,snake_case_ : Dict ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" ,snake_case_ ) == "1": UpperCamelCase : Union[str, Any] = 2 # New Code # UpperCamelCase : Dict = int(args.gradient_accumulation_steps ) UpperCamelCase : List[Any] = int(args.local_sgd_steps ) # Initialize accelerator UpperCamelCase : str = Accelerator( cpu=args.cpu ,mixed_precision=args.mixed_precision ,gradient_accumulation_steps=snake_case_ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase : Union[str, Any] = config["""lr"""] UpperCamelCase : int = int(config["""num_epochs"""] ) UpperCamelCase : int = int(config["""seed"""] ) UpperCamelCase : List[Any] = int(config["""batch_size"""] ) UpperCamelCase : Optional[int] = evaluate.load("""glue""" ,"""mrpc""" ) set_seed(snake_case_ ) UpperCamelCase , UpperCamelCase : Dict = get_dataloaders(snake_case_ ,snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase : Optional[int] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" ,return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase : Tuple = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase : List[Any] = AdamW(params=model.parameters() ,lr=snake_case_ ) # Instantiate scheduler UpperCamelCase : str = get_linear_schedule_with_warmup( optimizer=snake_case_ ,num_warmup_steps=1_0_0 ,num_training_steps=(len(snake_case_ ) * num_epochs) ,) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Any = accelerator.prepare( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() with LocalSGD( accelerator=snake_case_ ,model=snake_case_ ,local_sgd_steps=snake_case_ ,enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(snake_case_ ): UpperCamelCase : Optional[Any] = model(**snake_case_ ) UpperCamelCase : Optional[int] = output.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase : Any = model(**snake_case_ ) UpperCamelCase : Tuple = outputs.logits.argmax(dim=-1 ) UpperCamelCase , UpperCamelCase : int = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case_ ,references=snake_case_ ,) UpperCamelCase : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' ,snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" ,type=snake_case_ ,default=snake_case_ ,choices=["""no""", """fp16""", """bf16""", """fp8"""] ,help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" ,) # New Code # parser.add_argument( """--gradient_accumulation_steps""" ,type=snake_case_ ,default=1 ,help="""The number of minibatches to be ran before gradients are accumulated.""" ,) parser.add_argument( """--local_sgd_steps""" ,type=snake_case_ ,default=8 ,help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" ,action="""store_true""" ,help="""If passed, will train on the CPU.""" ) UpperCamelCase : Dict = parser.parse_args() UpperCamelCase : List[Any] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(snake_case_ ,snake_case_ ) if __name__ == "__main__": main()
27
0
"""simple docstring""" import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) __A : int = logging.getLogger() def A_ ( snake_case_ : Path ,snake_case_ : list ): '''simple docstring''' UpperCamelCase : int = """\n""".join(snake_case_ ) Path(snake_case_ ).open("""w""" ).writelines(snake_case_ ) __A : Tuple = '''patrickvonplaten/t5-tiny-random''' __A : List[str] = '''sshleifer/bart-tiny-random''' __A : Union[str, Any] = '''sshleifer/tiny-mbart''' __A : Any = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class lowerCamelCase ( _UpperCAmelCase ): def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = Path(self.get_auto_remove_tmp_dir() ) / """utest_input.source""" UpperCamelCase : List[Any] = input_file_name.parent / """utest_output.txt""" assert not output_file_name.exists() UpperCamelCase : Optional[int] = [""" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."""] _dump_articles(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = str(Path(self.get_auto_remove_tmp_dir() ) / """scores.json""" ) UpperCamelCase : Optional[int] = """translation_en_to_de""" if model == T5_TINY else """summarization""" UpperCamelCase : str = f'\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n '.split() with patch.object(SCREAMING_SNAKE_CASE_ , """argv""" , SCREAMING_SNAKE_CASE_ ): run_generate() assert Path(SCREAMING_SNAKE_CASE_ ).exists() # os.remove(Path(output_file_name)) def a_ ( self ): self.run_eval_tester(SCREAMING_SNAKE_CASE_ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.run_eval_tester(SCREAMING_SNAKE_CASE_ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = Path(self.get_auto_remove_tmp_dir() ) / """utest_input.source""" UpperCamelCase : str = input_file_name.parent / """utest_output.txt""" assert not output_file_name.exists() UpperCamelCase : Dict = { """en""": ["""Machine learning is great, isn't it?""", """I like to eat bananas""", """Tomorrow is another great day!"""], """de""": [ """Maschinelles Lernen ist großartig, oder?""", """Ich esse gerne Bananen""", """Morgen ist wieder ein toller Tag!""", ], } UpperCamelCase : List[Any] = Path(self.get_auto_remove_tmp_dir() ) UpperCamelCase : Tuple = str(tmp_dir / """scores.json""" ) UpperCamelCase : Optional[int] = str(tmp_dir / """val.target""" ) _dump_articles(SCREAMING_SNAKE_CASE_ , text["""en"""] ) _dump_articles(SCREAMING_SNAKE_CASE_ , text["""de"""] ) UpperCamelCase : Dict = """translation_en_to_de""" if model == T5_TINY else """summarization""" UpperCamelCase : str = f'\n run_eval_search.py\n {model}\n {str(SCREAMING_SNAKE_CASE_ )}\n {str(SCREAMING_SNAKE_CASE_ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n '.split() testargs.extend(["""--search""", """num_beams=1:2 length_penalty=0.9:1.0"""] ) with patch.object(SCREAMING_SNAKE_CASE_ , """argv""" , SCREAMING_SNAKE_CASE_ ): with CaptureStdout() as cs: run_search() UpperCamelCase : Tuple = [""" num_beams | length_penalty""", model, """Best score args"""] UpperCamelCase : int = ["""Info"""] if "translation" in task: expected_strings.append("""bleu""" ) else: expected_strings.extend(SCREAMING_SNAKE_CASE_ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(SCREAMING_SNAKE_CASE_ ).exists() os.remove(Path(SCREAMING_SNAKE_CASE_ ) )
363
"""simple docstring""" from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer __A : Any = logging.get_logger(__name__) __A : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A : Optional[Any] = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } __A : Any = {'''allegro/herbert-base-cased''': 514} __A : Optional[Any] = {} class lowerCamelCase ( _UpperCAmelCase ): lowercase : Dict = VOCAB_FILES_NAMES lowercase : Any = PRETRAINED_VOCAB_FILES_MAP lowercase : List[str] = PRETRAINED_INIT_CONFIGURATION lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Union[str, Any] = HerbertTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_="</s>" , **SCREAMING_SNAKE_CASE_ , ): super().__init__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = [self.cls_token_id] UpperCamelCase : str = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Tuple = [self.sep_token_id] UpperCamelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Optional[int] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
27
0
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' if number < 0: raise ValueError("""number must not be negative""" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
364
"""simple docstring""" import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=3.6 ): UpperCamelCase : Dict = tokenizer UpperCamelCase : Optional[Any] = tokenizer.bos_token_id UpperCamelCase : Any = dataset UpperCamelCase : List[str] = seq_length UpperCamelCase : Optional[Any] = seq_length * chars_per_token * num_of_sequences def __iter__( self ): UpperCamelCase : Dict = iter(self.dataset ) UpperCamelCase : Union[str, Any] = True while more_examples: UpperCamelCase , UpperCamelCase : Tuple = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(SCREAMING_SNAKE_CASE_ )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: UpperCamelCase : Dict = False break UpperCamelCase : str = tokenizer(SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )["""input_ids"""] UpperCamelCase : str = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , self.seq_length ): UpperCamelCase : List[str] = all_token_ids[i : i + self.seq_length] if len(SCREAMING_SNAKE_CASE_ ) == self.seq_length: yield torch.tensor(SCREAMING_SNAKE_CASE_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Dict = {"""streaming""": True} UpperCamelCase : Optional[int] = load_dataset(args.dataset_name ,split="""train""" ,**snake_case_ ) UpperCamelCase : Optional[int] = ConstantLengthDataset(snake_case_ ,snake_case_ ,seq_length=args.seq_length ) UpperCamelCase : List[Any] = DataLoader(snake_case_ ,batch_size=args.batch_size ) return eval_dataloader def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' model.eval() UpperCamelCase : Dict = [] for step, batch in enumerate(snake_case_ ): with torch.no_grad(): UpperCamelCase : List[Any] = model(snake_case_ ,labels=snake_case_ ) UpperCamelCase : Any = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(snake_case_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break UpperCamelCase : Dict = torch.mean(torch.cat(snake_case_ ) ) try: UpperCamelCase : Dict = torch.exp(snake_case_ ) except OverflowError: UpperCamelCase : Optional[int] = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator __A : List[Any] = Accelerator() # Parse configuration __A : str = HfArgumentParser(EvaluationArguments) __A : List[Any] = parser.parse_args() set_seed(args.seed) # Logging __A : Any = logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer __A : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) __A : List[Any] = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader __A : int = create_dataloader(args) # Prepare everything with our `accelerator`. __A , __A : Optional[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') __A , __A : Tuple = evaluate(args) logger.info(F'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
27
0
from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .multicontrolnet import MultiControlNetModel from .pipeline_controlnet import StableDiffusionControlNetPipeline from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline if is_transformers_available() and is_flax_available(): from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
365
"""simple docstring""" import argparse import os import re __A : Any = '''src/transformers''' # Pattern that looks at the indentation in a line. __A : Tuple = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : List[Any] = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : List[Any] = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : Any = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : str ,snake_case_ : str="" ,snake_case_ : Any=None ,snake_case_ : Union[str, Any]=None ): '''simple docstring''' UpperCamelCase : List[Any] = 0 UpperCamelCase : Optional[int] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Tuple = ["""\n""".join(lines[:index] )] else: UpperCamelCase : Tuple = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Dict = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Optional[Any] = [lines[index + 1]] index += 1 else: UpperCamelCase : str = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : List[Any] ): '''simple docstring''' def _inner(snake_case_ : List[str] ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Tuple=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Optional[int] ): return x if key is None: UpperCamelCase : List[str] = noop # Constants are all uppercase, they go first. UpperCamelCase : List[str] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : Tuple = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : int = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Union[str, Any] = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : Any ): UpperCamelCase : Union[str, Any] = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : int = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : str = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : Optional[int] = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : int = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Tuple = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : List[Any] = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Union[str, Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : List[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : Optional[int] = keys[:-1] UpperCamelCase : Union[str, Any] = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : Any = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : int=True ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : List[str] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : int = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Dict = main_blocks[block_idx] UpperCamelCase : Dict = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : List[str] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : Optional[Any] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Optional[Any] = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Any = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : List[Any] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Optional[Any] = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Optional[Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Any = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : Union[str, Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[str] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: UpperCamelCase : Optional[int] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Optional[int] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : List[Any] = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : Union[str, Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
0
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments @require_tf class lowerCamelCase ( unittest.TestCase ): def a_ ( self , SCREAMING_SNAKE_CASE_ ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result["""bs"""] , model_result["""ss"""] ): UpperCamelCase : int = model_result["""result"""][batch_size][sequence_length] self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = """sshleifer/tiny-gpt2""" UpperCamelCase : Optional[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=SCREAMING_SNAKE_CASE_ , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : int = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def a_ ( self ): UpperCamelCase : Dict = """sgugger/tiny-distilbert-classification""" UpperCamelCase : str = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , only_pretrain_model=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : List[Any] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def a_ ( self ): UpperCamelCase : Optional[Any] = """sshleifer/tiny-gpt2""" UpperCamelCase : Optional[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def a_ ( self ): UpperCamelCase : List[Any] = """sshleifer/tiny-gpt2""" UpperCamelCase : Union[str, Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=SCREAMING_SNAKE_CASE_ , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[int] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ , [config] ) UpperCamelCase : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def a_ ( self ): UpperCamelCase : Any = """sshleifer/tiny-gpt2""" UpperCamelCase : List[Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Union[str, Any] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ , [config] ) UpperCamelCase : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def a_ ( self ): UpperCamelCase : Any = """sshleifer/tiny-gpt2""" UpperCamelCase : Tuple = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Dict = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def a_ ( self ): UpperCamelCase : str = """sshleifer/tiny-gpt2""" UpperCamelCase : Dict = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ , [config] ) UpperCamelCase : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def a_ ( self ): UpperCamelCase : Tuple = """patrickvonplaten/t5-tiny-random""" UpperCamelCase : Any = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Dict = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ , configs=[config] ) UpperCamelCase : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , """Cannot do xla on CPU.""" ) def a_ ( self ): UpperCamelCase : Tuple = """sshleifer/tiny-gpt2""" UpperCamelCase : List[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , use_xla=SCREAMING_SNAKE_CASE_ , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : List[str] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def a_ ( self ): UpperCamelCase : str = """sshleifer/tiny-gpt2""" with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase : List[str] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=SCREAMING_SNAKE_CASE_ , save_to_csv=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(SCREAMING_SNAKE_CASE_ , """inf_time.csv""" ) , inference_memory_csv_file=os.path.join(SCREAMING_SNAKE_CASE_ , """inf_mem.csv""" ) , env_info_csv_file=os.path.join(SCREAMING_SNAKE_CASE_ , """env.csv""" ) , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) benchmark.run() self.assertTrue(Path(os.path.join(SCREAMING_SNAKE_CASE_ , """inf_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(SCREAMING_SNAKE_CASE_ , """inf_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(SCREAMING_SNAKE_CASE_ , """env.csv""" ) ).exists() ) def a_ ( self ): UpperCamelCase : List[str] = """sshleifer/tiny-gpt2""" def _check_summary_is_not_empty(SCREAMING_SNAKE_CASE_ ): self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """sequential""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """cumulative""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """current""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """total""" ) ) with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase : Tuple = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(SCREAMING_SNAKE_CASE_ , """log.txt""" ) , log_print=SCREAMING_SNAKE_CASE_ , trace_memory_line_by_line=SCREAMING_SNAKE_CASE_ , eager_mode=SCREAMING_SNAKE_CASE_ , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : List[str] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) self.assertTrue(Path(os.path.join(SCREAMING_SNAKE_CASE_ , """log.txt""" ) ).exists() )
366
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' if number < 0: raise ValueError("""number must not be negative""" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
27
0
"""simple docstring""" import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process __A : str = logging.getLogger(__name__) __A : List[Any] = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) __A : Tuple = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class lowerCamelCase : lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={ 'help': ( 'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.' ) } , ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(_UpperCAmelCase )} , ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={ 'help': ( 'Override some existing default config settings when a model is trained from scratch. Example: ' 'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index' ) } , ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) lowercase : bool = field( default=_UpperCAmelCase , metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'} , ) lowercase : str = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) lowercase : bool = field( default=_UpperCAmelCase , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) def a_ ( self ): if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( """--config_overrides can't be used in combination with --config_name or --model_name_or_path""" ) @dataclass class lowerCamelCase : lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'The name of the dataset to use (via the datasets library).'} ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) lowercase : Optional[str] = field(default=_UpperCAmelCase , metadata={'help': 'The input training data file (a text file).'} ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'} , ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'An optional input train ref data file for whole word masking in Chinese.'} , ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'An optional input validation ref data file for whole word masking in Chinese.'} , ) lowercase : bool = field( default=_UpperCAmelCase , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) lowercase : Optional[int] = field( default=5 , metadata={ 'help': 'The percentage of the train set used as validation set in case there\'s no validation split' } , ) lowercase : Optional[int] = field( default=_UpperCAmelCase , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated. Default to the max input length of the model.' ) } , ) lowercase : Optional[int] = field( default=_UpperCAmelCase , metadata={'help': 'The number of processes to use for the preprocessing.'} , ) lowercase : float = field( default=0.15 , metadata={'help': 'Ratio of tokens to mask for masked language modeling loss'} ) lowercase : bool = field( default=_UpperCAmelCase , metadata={ 'help': ( 'Whether to pad all samples to `max_seq_length`. ' 'If False, will pad the samples dynamically when batching to the maximum length in the batch.' ) } , ) def a_ ( self ): if self.train_file is not None: UpperCamelCase : List[Any] = self.train_file.split(""".""" )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: UpperCamelCase : str = self.validation_file.split(""".""" )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def A_ ( snake_case_ : List[str] ,snake_case_ : Tuple ): '''simple docstring''' with open(snake_case_ ,"""r""" ,encoding="""utf-8""" ) as f: UpperCamelCase : Optional[int] = [json.loads(snake_case_ ) for line in f.read().splitlines() if (len(snake_case_ ) > 0 and not line.isspace())] assert len(snake_case_ ) == len(snake_case_ ) UpperCamelCase : Tuple = {c: dataset[c] for c in dataset.column_names} UpperCamelCase : int = refs return Dataset.from_dict(snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : List[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. UpperCamelCase : Optional[int] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCamelCase : Dict = parser.parse_args_into_dataclasses() # Detecting last checkpoint. UpperCamelCase : int = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: UpperCamelCase : List[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None: logger.info( f'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,datefmt="""%m/%d/%Y %H:%M:%S""" ,handlers=[logging.StreamHandler(sys.stdout )] ,) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + f'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" ,snake_case_ ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. UpperCamelCase : List[str] = load_dataset(data_args.dataset_name ,data_args.dataset_config_name ) if "validation" not in datasets.keys(): UpperCamelCase : List[str] = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=f'train[:{data_args.validation_split_percentage}%]' ,) UpperCamelCase : List[str] = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=f'train[{data_args.validation_split_percentage}%:]' ,) else: UpperCamelCase : List[str] = {} if data_args.train_file is not None: UpperCamelCase : Any = data_args.train_file if data_args.validation_file is not None: UpperCamelCase : Dict = data_args.validation_file UpperCamelCase : Any = data_args.train_file.split(""".""" )[-1] if extension == "txt": UpperCamelCase : int = """text""" UpperCamelCase : List[Any] = load_dataset(snake_case_ ,data_files=snake_case_ ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. UpperCamelCase : Dict = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: UpperCamelCase : Tuple = AutoConfig.from_pretrained(model_args.config_name ,**snake_case_ ) elif model_args.model_name_or_path: UpperCamelCase : Any = AutoConfig.from_pretrained(model_args.model_name_or_path ,**snake_case_ ) else: UpperCamelCase : str = CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(f'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(f'New config: {config}' ) UpperCamelCase : Dict = { """cache_dir""": model_args.cache_dir, """use_fast""": model_args.use_fast_tokenizer, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: UpperCamelCase : int = AutoTokenizer.from_pretrained(model_args.tokenizer_name ,**snake_case_ ) elif model_args.model_name_or_path: UpperCamelCase : Optional[Any] = AutoTokenizer.from_pretrained(model_args.model_name_or_path ,**snake_case_ ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported by this script.""" """You can do it from another script, save it, and load it from here, using --tokenizer_name.""" ) if model_args.model_name_or_path: UpperCamelCase : Dict = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path ,from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) ,config=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 ,) else: logger.info("""Training new model from scratch""" ) UpperCamelCase : Dict = AutoModelForMaskedLM.from_config(snake_case_ ) model.resize_token_embeddings(len(snake_case_ ) ) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: UpperCamelCase : Tuple = datasets["""train"""].column_names else: UpperCamelCase : Any = datasets["""validation"""].column_names UpperCamelCase : str = """text""" if """text""" in column_names else column_names[0] UpperCamelCase : Optional[Any] = """max_length""" if data_args.pad_to_max_length else False def tokenize_function(snake_case_ : Optional[int] ): # Remove empty lines UpperCamelCase : Optional[Any] = [line for line in examples["""text"""] if len(snake_case_ ) > 0 and not line.isspace()] return tokenizer(examples["""text"""] ,padding=snake_case_ ,truncation=snake_case_ ,max_length=data_args.max_seq_length ) UpperCamelCase : List[str] = datasets.map( snake_case_ ,batched=snake_case_ ,num_proc=data_args.preprocessing_num_workers ,remove_columns=[text_column_name] ,load_from_cache_file=not data_args.overwrite_cache ,) # Add the chinese references if provided if data_args.train_ref_file is not None: UpperCamelCase : List[Any] = add_chinese_references(tokenized_datasets["""train"""] ,data_args.train_ref_file ) if data_args.validation_ref_file is not None: UpperCamelCase : Any = add_chinese_references( tokenized_datasets["""validation"""] ,data_args.validation_ref_file ) # If we have ref files, need to avoid it removed by trainer UpperCamelCase : List[Any] = data_args.train_ref_file or data_args.validation_ref_file if has_ref: UpperCamelCase : List[str] = False # Data collator # This one will take care of randomly masking the tokens. UpperCamelCase : Dict = DataCollatorForWholeWordMask(tokenizer=snake_case_ ,mlm_probability=data_args.mlm_probability ) # Initialize our Trainer UpperCamelCase : Any = Trainer( model=snake_case_ ,args=snake_case_ ,train_dataset=tokenized_datasets["""train"""] if training_args.do_train else None ,eval_dataset=tokenized_datasets["""validation"""] if training_args.do_eval else None ,tokenizer=snake_case_ ,data_collator=snake_case_ ,) # Training if training_args.do_train: if last_checkpoint is not None: UpperCamelCase : List[Any] = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ): UpperCamelCase : Optional[Any] = model_args.model_name_or_path else: UpperCamelCase : int = None UpperCamelCase : Any = trainer.train(resume_from_checkpoint=snake_case_ ) trainer.save_model() # Saves the tokenizer too for easy upload UpperCamelCase : List[str] = os.path.join(training_args.output_dir ,"""train_results.txt""" ) if trainer.is_world_process_zero(): with open(snake_case_ ,"""w""" ) as writer: logger.info("""***** Train results *****""" ) for key, value in sorted(train_result.metrics.items() ): logger.info(f' {key} = {value}' ) writer.write(f'{key} = {value}\n' ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir ,"""trainer_state.json""" ) ) # Evaluation UpperCamelCase : str = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) UpperCamelCase : List[str] = trainer.evaluate() UpperCamelCase : List[str] = math.exp(eval_output["""eval_loss"""] ) UpperCamelCase : Any = perplexity UpperCamelCase : Optional[int] = os.path.join(training_args.output_dir ,"""eval_results_mlm_wwm.txt""" ) if trainer.is_world_process_zero(): with open(snake_case_ ,"""w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in sorted(results.items() ): logger.info(f' {key} = {value}' ) writer.write(f'{key} = {value}\n' ) return results def A_ ( snake_case_ : Dict ): '''simple docstring''' main() if __name__ == "__main__": main()
367
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL __A : Optional[Any] = logging.get_logger(__name__) def A_ ( snake_case_ : np.ndarray ,snake_case_ : Union[int, Iterable[int]] ,snake_case_ : bool ,snake_case_ : int ): '''simple docstring''' def constraint_to_multiple_of(snake_case_ : Optional[Any] ,snake_case_ : Optional[int] ,snake_case_ : List[str]=0 ,snake_case_ : Optional[Any]=None ): UpperCamelCase : List[str] = round(val / multiple ) * multiple if max_val is not None and x > max_val: UpperCamelCase : Optional[Any] = math.floor(val / multiple ) * multiple if x < min_val: UpperCamelCase : Dict = math.ceil(val / multiple ) * multiple return x UpperCamelCase : Any = (output_size, output_size) if isinstance(snake_case_ ,snake_case_ ) else output_size UpperCamelCase , UpperCamelCase : int = get_image_size(snake_case_ ) UpperCamelCase , UpperCamelCase : Union[str, Any] = output_size # determine new height and width UpperCamelCase : List[str] = output_height / input_height UpperCamelCase : List[str] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width UpperCamelCase : int = scale_width else: # fit height UpperCamelCase : Optional[Any] = scale_height UpperCamelCase : int = constraint_to_multiple_of(scale_height * input_height ,multiple=snake_case_ ) UpperCamelCase : Union[str, Any] = constraint_to_multiple_of(scale_width * input_width ,multiple=snake_case_ ) return (new_height, new_width) class lowerCamelCase ( _UpperCAmelCase ): lowercase : str = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = size if size is not None else {"""height""": 384, """width""": 384} UpperCamelCase : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = do_resize UpperCamelCase : Union[str, Any] = size UpperCamelCase : Union[str, Any] = keep_aspect_ratio UpperCamelCase : Any = ensure_multiple_of UpperCamelCase : List[Any] = resample UpperCamelCase : str = do_rescale UpperCamelCase : Optional[Any] = rescale_factor UpperCamelCase : List[str] = do_normalize UpperCamelCase : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCamelCase : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) UpperCamelCase : Dict = get_resize_output_image_size( SCREAMING_SNAKE_CASE_ , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=SCREAMING_SNAKE_CASE_ , multiple=SCREAMING_SNAKE_CASE_ , ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize UpperCamelCase : List[Any] = size if size is not None else self.size UpperCamelCase : Dict = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio UpperCamelCase : Optional[int] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of UpperCamelCase : Tuple = resample if resample is not None else self.resample UpperCamelCase : str = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase : Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase : Any = image_mean if image_mean is not None else self.image_mean UpperCamelCase : List[Any] = image_std if image_std is not None else self.image_std UpperCamelCase : str = make_list_of_images(SCREAMING_SNAKE_CASE_ ) if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. UpperCamelCase : Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase : Union[str, Any] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase : int = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase : List[str] = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Union[str, Any] = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : str = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = target_sizes.numpy() UpperCamelCase : Dict = [] for idx in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase : List[Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : List[Any] = logits.argmax(dim=1 ) UpperCamelCase : Dict = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
27
0
"""simple docstring""" from __future__ import annotations def A_ ( snake_case_ : list[list[int]] ): '''simple docstring''' UpperCamelCase : str = len(snake_case_ ) # We need to create solution object to save path. UpperCamelCase : List[Any] = [[0 for _ in range(snake_case_ )] for _ in range(snake_case_ )] UpperCamelCase : Any = run_maze(snake_case_ ,0 ,0 ,snake_case_ ) if solved: print("""\n""".join(str(snake_case_ ) for row in solutions ) ) else: print("""No solution exists!""" ) return solved def A_ ( snake_case_ : list[list[int]] ,snake_case_ : int ,snake_case_ : int ,snake_case_ : list[list[int]] ): '''simple docstring''' UpperCamelCase : str = len(snake_case_ ) # Final check point. if i == j == (size - 1): UpperCamelCase : Optional[Any] = 1 return True UpperCamelCase : Optional[int] = (not i < 0) and (not j < 0) # Check lower bounds UpperCamelCase : List[Any] = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. UpperCamelCase : List[str] = (not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited UpperCamelCase : Dict = 1 # check for directions if ( run_maze(snake_case_ ,i + 1 ,snake_case_ ,snake_case_ ) or run_maze(snake_case_ ,snake_case_ ,j + 1 ,snake_case_ ) or run_maze(snake_case_ ,i - 1 ,snake_case_ ,snake_case_ ) or run_maze(snake_case_ ,snake_case_ ,j - 1 ,snake_case_ ) ): return True UpperCamelCase : Optional[Any] = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
368
"""simple docstring""" from collections.abc import Callable def A_ ( snake_case_ : Callable[[float], float] ,snake_case_ : float ,snake_case_ : float ): '''simple docstring''' UpperCamelCase : float = a UpperCamelCase : float = b if function(snake_case_ ) == 0: # one of the a or b is a root for the function return a elif function(snake_case_ ) == 0: return b elif ( function(snake_case_ ) * function(snake_case_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("""could not find root in given interval.""" ) else: UpperCamelCase : float = start + (end - start) / 2.0 while abs(start - mid ) > 1_0**-7: # until precisely equals to 10^-7 if function(snake_case_ ) == 0: return mid elif function(snake_case_ ) * function(snake_case_ ) < 0: UpperCamelCase : Dict = mid else: UpperCamelCase : List[str] = mid UpperCamelCase : Tuple = start + (end - start) / 2.0 return mid def A_ ( snake_case_ : float ): '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
27
0
"""simple docstring""" def A_ ( snake_case_ : int ,snake_case_ : int ,snake_case_ : list[list[int]] ): '''simple docstring''' def update_area_of_max_square(snake_case_ : int ,snake_case_ : int ) -> int: # BASE CASE if row >= rows or col >= cols: return 0 UpperCamelCase : Tuple = update_area_of_max_square(snake_case_ ,col + 1 ) UpperCamelCase : Optional[int] = update_area_of_max_square(row + 1 ,col + 1 ) UpperCamelCase : List[str] = update_area_of_max_square(row + 1 ,snake_case_ ) if mat[row][col]: UpperCamelCase : Dict = 1 + min([right, diagonal, down] ) UpperCamelCase : int = max(largest_square_area[0] ,snake_case_ ) return sub_problem_sol else: return 0 UpperCamelCase : Dict = [0] update_area_of_max_square(0 ,0 ) return largest_square_area[0] def A_ ( snake_case_ : int ,snake_case_ : int ,snake_case_ : list[list[int]] ): '''simple docstring''' def update_area_of_max_square_using_dp_array( snake_case_ : int ,snake_case_ : int ,snake_case_ : list[list[int]] ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] UpperCamelCase : Dict = update_area_of_max_square_using_dp_array(snake_case_ ,col + 1 ,snake_case_ ) UpperCamelCase : Union[str, Any] = update_area_of_max_square_using_dp_array(row + 1 ,col + 1 ,snake_case_ ) UpperCamelCase : Dict = update_area_of_max_square_using_dp_array(row + 1 ,snake_case_ ,snake_case_ ) if mat[row][col]: UpperCamelCase : Optional[Any] = 1 + min([right, diagonal, down] ) UpperCamelCase : List[str] = max(largest_square_area[0] ,snake_case_ ) UpperCamelCase : Optional[Any] = sub_problem_sol return sub_problem_sol else: return 0 UpperCamelCase : Tuple = [0] UpperCamelCase : str = [[-1] * cols for _ in range(snake_case_ )] update_area_of_max_square_using_dp_array(0 ,0 ,snake_case_ ) return largest_square_area[0] def A_ ( snake_case_ : int ,snake_case_ : int ,snake_case_ : list[list[int]] ): '''simple docstring''' UpperCamelCase : Any = [[0] * (cols + 1) for _ in range(rows + 1 )] UpperCamelCase : Union[str, Any] = 0 for row in range(rows - 1 ,-1 ,-1 ): for col in range(cols - 1 ,-1 ,-1 ): UpperCamelCase : int = dp_array[row][col + 1] UpperCamelCase : Union[str, Any] = dp_array[row + 1][col + 1] UpperCamelCase : List[str] = dp_array[row + 1][col] if mat[row][col] == 1: UpperCamelCase : List[Any] = 1 + min(snake_case_ ,snake_case_ ,snake_case_ ) UpperCamelCase : Optional[int] = max(dp_array[row][col] ,snake_case_ ) else: UpperCamelCase : Optional[int] = 0 return largest_square_area def A_ ( snake_case_ : int ,snake_case_ : int ,snake_case_ : list[list[int]] ): '''simple docstring''' UpperCamelCase : Dict = [0] * (cols + 1) UpperCamelCase : Union[str, Any] = [0] * (cols + 1) UpperCamelCase : Tuple = 0 for row in range(rows - 1 ,-1 ,-1 ): for col in range(cols - 1 ,-1 ,-1 ): UpperCamelCase : int = current_row[col + 1] UpperCamelCase : int = next_row[col + 1] UpperCamelCase : Union[str, Any] = next_row[col] if mat[row][col] == 1: UpperCamelCase : Dict = 1 + min(snake_case_ ,snake_case_ ,snake_case_ ) UpperCamelCase : List[str] = max(current_row[col] ,snake_case_ ) else: UpperCamelCase : List[Any] = 0 UpperCamelCase : Optional[int] = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
369
"""simple docstring""" import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def a_ ( self ): UpperCamelCase : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) UpperCamelCase : int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) UpperCamelCase : Dict = """xvjiarui/stable-diffusion-2-inpainting""" UpperCamelCase , UpperCamelCase : List[str] = FlaxStableDiffusionInpaintPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = """Face of a yellow cat, high resolution, sitting on a park bench""" UpperCamelCase : List[str] = jax.random.PRNGKey(0 ) UpperCamelCase : Tuple = 50 UpperCamelCase : Dict = jax.device_count() UpperCamelCase : Optional[int] = num_samples * [prompt] UpperCamelCase : int = num_samples * [init_image] UpperCamelCase : List[Any] = num_samples * [mask_image] UpperCamelCase , UpperCamelCase , UpperCamelCase : Optional[Any] = pipeline.prepare_inputs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # shard inputs and rng UpperCamelCase : Optional[int] = replicate(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = jax.random.split(SCREAMING_SNAKE_CASE_ , jax.device_count() ) UpperCamelCase : str = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = pipeline( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , jit=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = output.images.reshape(SCREAMING_SNAKE_CASE_ , 512 , 512 , 3 ) UpperCamelCase : List[Any] = images[0, 253:256, 253:256, -1] UpperCamelCase : List[Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) UpperCamelCase : Dict = jnp.array( [0.3611307, 0.37649736, 0.3757408, 0.38213953, 0.39295167, 0.3841631, 0.41554978, 0.4137475, 0.4217084] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
27
0
import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def A_ ( snake_case_ : Dataset ,snake_case_ : Dict[str, str] ): '''simple docstring''' UpperCamelCase : List[str] = args.log_outputs UpperCamelCase : Tuple = """_""".join(args.dataset.split("""/""" ) + [args.config, args.split] ) # load metric UpperCamelCase : List[Any] = load_metric("""wer""" ) UpperCamelCase : Any = load_metric("""cer""" ) # compute metrics UpperCamelCase : str = wer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) UpperCamelCase : Dict = cer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) # print & log results UpperCamelCase : Optional[int] = f'WER: {wer_result}\nCER: {cer_result}' print(snake_case_ ) with open(f'{dataset_id}_eval_results.txt' ,"""w""" ) as f: f.write(snake_case_ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: UpperCamelCase : Optional[Any] = f'log_{dataset_id}_predictions.txt' UpperCamelCase : str = f'log_{dataset_id}_targets.txt' with open(snake_case_ ,"""w""" ) as p, open(snake_case_ ,"""w""" ) as t: # mapping function to write output def write_to_file(snake_case_ : Union[str, Any] ,snake_case_ : Tuple ): p.write(f'{i}' + """\n""" ) p.write(batch["""prediction"""] + """\n""" ) t.write(f'{i}' + """\n""" ) t.write(batch["""target"""] + """\n""" ) result.map(snake_case_ ,with_indices=snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Dict = """[,?.!\-\;\:\"“%‘”�—’…–]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training UpperCamelCase : str = re.sub(snake_case_ ,"""""" ,text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! UpperCamelCase : List[str] = ["""\n\n""", """\n""", """ """, """ """] for t in token_sequences_to_ignore: UpperCamelCase : Tuple = """ """.join(text.split(snake_case_ ) ) return text def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Union[str, Any] = load_dataset(args.dataset ,args.config ,split=args.split ,use_auth_token=snake_case_ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor UpperCamelCase : List[Any] = AutoFeatureExtractor.from_pretrained(args.model_id ) UpperCamelCase : Dict = feature_extractor.sampling_rate # resample audio UpperCamelCase : Optional[Any] = dataset.cast_column("""audio""" ,Audio(sampling_rate=snake_case_ ) ) # load eval pipeline if args.device is None: UpperCamelCase : int = 0 if torch.cuda.is_available() else -1 UpperCamelCase : Union[str, Any] = pipeline("""automatic-speech-recognition""" ,model=args.model_id ,device=args.device ) # map function to decode audio def map_to_pred(snake_case_ : Union[str, Any] ): UpperCamelCase : List[Any] = asr( batch["""audio"""]["""array"""] ,chunk_length_s=args.chunk_length_s ,stride_length_s=args.stride_length_s ) UpperCamelCase : Union[str, Any] = prediction["""text"""] UpperCamelCase : Optional[Any] = normalize_text(batch["""sentence"""] ) return batch # run inference on all examples UpperCamelCase : Any = dataset.map(snake_case_ ,remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(snake_case_ ,snake_case_ ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() parser.add_argument( '''--model_id''', type=str, required=True, help='''Model identifier. Should be loadable with 🤗 Transformers''' ) parser.add_argument( '''--dataset''', type=str, required=True, help='''Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets''', ) parser.add_argument( '''--config''', type=str, required=True, help='''Config of the dataset. *E.g.* `\'en\'` for Common Voice''' ) parser.add_argument('''--split''', type=str, required=True, help='''Split of the dataset. *E.g.* `\'test\'`''') parser.add_argument( '''--chunk_length_s''', type=float, default=None, help='''Chunk length in seconds. Defaults to 5 seconds.''' ) parser.add_argument( '''--stride_length_s''', type=float, default=None, help='''Stride of the audio chunks. Defaults to 1 second.''' ) parser.add_argument( '''--log_outputs''', action='''store_true''', help='''If defined, write outputs to log file for analysis.''' ) parser.add_argument( '''--device''', type=int, default=None, help='''The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.''', ) __A : Optional[Any] = parser.parse_args() main(args)
370
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def A_ ( snake_case_ : int ): # picklable for multiprocessing '''simple docstring''' return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def A_ ( ): '''simple docstring''' with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" UpperCamelCase : Optional[Any] = [1, 2, 3] with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=2 ) with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" ,[2, -1] ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : List[Any] = [1, 2] UpperCamelCase : List[Any] = {"""a""": 1, """b""": 2} UpperCamelCase : List[str] = {"""a""": [1, 2], """b""": [3, 4]} UpperCamelCase : Tuple = {"""a""": {"""1""": 1}, """b""": 2} UpperCamelCase : Any = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} UpperCamelCase : Optional[int] = [2, 3] UpperCamelCase : List[str] = {"""a""": 2, """b""": 3} UpperCamelCase : Any = {"""a""": [2, 3], """b""": [4, 5]} UpperCamelCase : Tuple = {"""a""": {"""1""": 2}, """b""": 3} UpperCamelCase : List[str] = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa
27
0
"""simple docstring""" import json import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from transformers import OneFormerImageProcessor from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput if is_vision_available(): from PIL import Image def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Union[str, Any]="shi-labs/oneformer_demo" ): '''simple docstring''' with open(hf_hub_download(snake_case_ ,snake_case_ ,repo_type="""dataset""" ) ,"""r""" ) as f: UpperCamelCase : Optional[int] = json.load(snake_case_ ) UpperCamelCase : Any = {} UpperCamelCase : Optional[int] = [] UpperCamelCase : int = [] for key, info in class_info.items(): UpperCamelCase : Optional[int] = info["""name"""] class_names.append(info["""name"""] ) if info["isthing"]: thing_ids.append(int(snake_case_ ) ) UpperCamelCase : Any = thing_ids UpperCamelCase : Any = class_names return metadata class lowerCamelCase ( unittest.TestCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=30 , SCREAMING_SNAKE_CASE_=400 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=255 , SCREAMING_SNAKE_CASE_="shi-labs/oneformer_demo" , SCREAMING_SNAKE_CASE_="ade20k_panoptic.json" , SCREAMING_SNAKE_CASE_=10 , ): UpperCamelCase : Optional[Any] = parent UpperCamelCase : List[str] = batch_size UpperCamelCase : List[Any] = num_channels UpperCamelCase : Any = min_resolution UpperCamelCase : List[str] = max_resolution UpperCamelCase : Tuple = do_resize UpperCamelCase : Optional[int] = {"""shortest_edge""": 32, """longest_edge""": 1333} if size is None else size UpperCamelCase : str = do_normalize UpperCamelCase : Tuple = image_mean UpperCamelCase : str = image_std UpperCamelCase : Optional[int] = class_info_file UpperCamelCase : Dict = prepare_metadata(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = num_text UpperCamelCase : Optional[int] = repo_path # for the post_process_functions UpperCamelCase : str = 2 UpperCamelCase : Union[str, Any] = 10 UpperCamelCase : List[Any] = 10 UpperCamelCase : Dict = 3 UpperCamelCase : str = 4 UpperCamelCase : Any = num_labels UpperCamelCase : Dict = do_reduce_labels UpperCamelCase : Union[str, Any] = ignore_index def a_ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "num_labels": self.num_labels, "do_reduce_labels": self.do_reduce_labels, "ignore_index": self.ignore_index, "class_info_file": self.class_info_file, "metadata": self.metadata, "num_text": self.num_text, } def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): if not batched: UpperCamelCase : int = image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE_ , Image.Image ): UpperCamelCase : Union[str, Any] = image.size else: UpperCamelCase : List[str] = image.shape[1], image.shape[2] if w < h: UpperCamelCase : Tuple = int(self.size["""shortest_edge"""] * h / w ) UpperCamelCase : str = self.size["""shortest_edge"""] elif w > h: UpperCamelCase : Tuple = self.size["""shortest_edge"""] UpperCamelCase : Union[str, Any] = int(self.size["""shortest_edge"""] * w / h ) else: UpperCamelCase : List[Any] = self.size["""shortest_edge"""] UpperCamelCase : str = self.size["""shortest_edge"""] else: UpperCamelCase : int = [] for image in image_inputs: UpperCamelCase : Dict = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) UpperCamelCase : List[Any] = max(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : item[0] )[0] UpperCamelCase : int = max(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : item[1] )[1] return expected_height, expected_width def a_ ( self ): return OneFormerForUniversalSegmentationOutput( # +1 for null class class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1) ) , masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width) ) , ) @require_torch @require_vision class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Union[str, Any] = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None # only for test_image_processing_common.test_image_proc_to_json_string lowercase : str = image_processing_class def a_ ( self ): UpperCamelCase : Optional[Any] = OneFormerImageProcessorTester(self ) @property def a_ ( self ): return self.image_processing_tester.prepare_image_processor_dict() def a_ ( self ): UpperCamelCase : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """image_mean""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """image_std""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_normalize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_resize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """size""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """ignore_index""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """class_info_file""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """num_text""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """repo_path""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """metadata""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_reduce_labels""" ) ) def a_ ( self ): pass def a_ ( self ): # Initialize image_processor UpperCamelCase : Any = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase : int = prepare_image_inputs(self.image_processing_tester , equal_resolution=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , Image.Image ) # Test not batched input UpperCamelCase : List[str] = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values UpperCamelCase : str = self.image_processing_tester.get_expected_values(SCREAMING_SNAKE_CASE_ ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase : Tuple = self.image_processing_tester.get_expected_values(SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = image_processor( SCREAMING_SNAKE_CASE_ , ["""semantic"""] * len(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def a_ ( self ): # Initialize image_processor UpperCamelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase : List[Any] = prepare_image_inputs(self.image_processing_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , numpify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) # Test not batched input UpperCamelCase : Optional[Any] = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values UpperCamelCase : Any = self.image_processing_tester.get_expected_values(SCREAMING_SNAKE_CASE_ ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase : Any = self.image_processing_tester.get_expected_values(SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = image_processor( SCREAMING_SNAKE_CASE_ , ["""semantic"""] * len(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def a_ ( self ): # Initialize image_processor UpperCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase : Dict = prepare_image_inputs(self.image_processing_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , torchify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) # Test not batched input UpperCamelCase : Optional[int] = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values UpperCamelCase : Optional[Any] = self.image_processing_tester.get_expected_values(SCREAMING_SNAKE_CASE_ ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase : Optional[Any] = self.image_processing_tester.get_expected_values(SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = image_processor( SCREAMING_SNAKE_CASE_ , ["""semantic"""] * len(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def a_ ( self , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_="np" ): UpperCamelCase : List[str] = self.image_processing_class(**self.image_processor_dict ) # prepare image and target UpperCamelCase : Union[str, Any] = self.image_processing_tester.num_labels UpperCamelCase : str = None UpperCamelCase : int = None UpperCamelCase : Optional[Any] = prepare_image_inputs(self.image_processing_tester , equal_resolution=SCREAMING_SNAKE_CASE_ ) if with_segmentation_maps: UpperCamelCase : Any = num_labels if is_instance_map: UpperCamelCase : Tuple = list(range(SCREAMING_SNAKE_CASE_ ) ) * 2 UpperCamelCase : List[str] = dict(enumerate(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Optional[Any] = [ np.random.randint(0 , high * 2 , (img.size[1], img.size[0]) ).astype(np.uinta ) for img in image_inputs ] if segmentation_type == "pil": UpperCamelCase : List[Any] = [Image.fromarray(SCREAMING_SNAKE_CASE_ ) for annotation in annotations] UpperCamelCase : List[Any] = image_processor( SCREAMING_SNAKE_CASE_ , ["""semantic"""] * len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , instance_id_to_semantic_id=SCREAMING_SNAKE_CASE_ , pad_and_return_pixel_mask=SCREAMING_SNAKE_CASE_ , ) return inputs def a_ ( self ): pass def a_ ( self ): def common(SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=None ): UpperCamelCase : Dict = self.comm_get_image_processor_inputs( with_segmentation_maps=SCREAMING_SNAKE_CASE_ , is_instance_map=SCREAMING_SNAKE_CASE_ , segmentation_type=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = inputs["""mask_labels"""] UpperCamelCase : Any = inputs["""class_labels"""] UpperCamelCase : Any = inputs["""pixel_values"""] UpperCamelCase : Union[str, Any] = inputs["""text_inputs"""] # check the batch_size for mask_label, class_label, text_input in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(mask_label.shape[0] , class_label.shape[0] ) # this ensure padding has happened self.assertEqual(mask_label.shape[1:] , pixel_values.shape[2:] ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.image_processing_tester.num_text ) common() common(is_instance_map=SCREAMING_SNAKE_CASE_ ) common(is_instance_map=SCREAMING_SNAKE_CASE_ , segmentation_type="""pil""" ) common(is_instance_map=SCREAMING_SNAKE_CASE_ , segmentation_type="""pil""" ) def a_ ( self ): UpperCamelCase : int = np.zeros((20, 50) ) UpperCamelCase : Dict = 1 UpperCamelCase : List[Any] = 1 UpperCamelCase : Optional[int] = 1 UpperCamelCase : Optional[int] = binary_mask_to_rle(SCREAMING_SNAKE_CASE_ ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 4 ) self.assertEqual(rle[0] , 21 ) self.assertEqual(rle[1] , 45 ) def a_ ( self ): UpperCamelCase : Dict = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) UpperCamelCase : List[str] = self.image_processing_tester.get_fake_oneformer_outputs() UpperCamelCase : int = fature_extractor.post_process_semantic_segmentation(SCREAMING_SNAKE_CASE_ ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.image_processing_tester.batch_size ) self.assertEqual( segmentation[0].shape , ( self.image_processing_tester.height, self.image_processing_tester.width, ) , ) UpperCamelCase : Optional[Any] = [(1, 4) for i in range(self.image_processing_tester.batch_size )] UpperCamelCase : Union[str, Any] = fature_extractor.post_process_semantic_segmentation(SCREAMING_SNAKE_CASE_ , target_sizes=SCREAMING_SNAKE_CASE_ ) self.assertEqual(segmentation[0].shape , target_sizes[0] ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) UpperCamelCase : List[str] = self.image_processing_tester.get_fake_oneformer_outputs() UpperCamelCase : Any = image_processor.post_process_instance_segmentation(SCREAMING_SNAKE_CASE_ , threshold=0 ) self.assertTrue(len(SCREAMING_SNAKE_CASE_ ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("""segmentation""" in el ) self.assertTrue("""segments_info""" in el ) self.assertEqual(type(el["""segments_info"""] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual( el["""segmentation"""].shape , (self.image_processing_tester.height, self.image_processing_tester.width) ) def a_ ( self ): UpperCamelCase : List[Any] = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) UpperCamelCase : Union[str, Any] = self.image_processing_tester.get_fake_oneformer_outputs() UpperCamelCase : Dict = image_processor.post_process_panoptic_segmentation(SCREAMING_SNAKE_CASE_ , threshold=0 ) self.assertTrue(len(SCREAMING_SNAKE_CASE_ ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("""segmentation""" in el ) self.assertTrue("""segments_info""" in el ) self.assertEqual(type(el["""segments_info"""] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual( el["""segmentation"""].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
371
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="last" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=0 , ): UpperCamelCase : Union[str, Any] = parent UpperCamelCase : str = batch_size UpperCamelCase : int = seq_length UpperCamelCase : Optional[Any] = is_training UpperCamelCase : Any = use_input_lengths UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : List[Any] = use_labels UpperCamelCase : Union[str, Any] = gelu_activation UpperCamelCase : Dict = sinusoidal_embeddings UpperCamelCase : Optional[int] = causal UpperCamelCase : List[Any] = asm UpperCamelCase : int = n_langs UpperCamelCase : Optional[Any] = vocab_size UpperCamelCase : str = n_special UpperCamelCase : Dict = hidden_size UpperCamelCase : Union[str, Any] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : int = max_position_embeddings UpperCamelCase : Any = type_sequence_label_size UpperCamelCase : str = initializer_range UpperCamelCase : str = num_labels UpperCamelCase : Union[str, Any] = num_choices UpperCamelCase : List[str] = summary_type UpperCamelCase : int = use_proj UpperCamelCase : List[str] = scope UpperCamelCase : Dict = bos_token_id def a_ ( self ): UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Union[str, Any] = None if self.use_input_lengths: UpperCamelCase : str = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase : Tuple = None if self.use_token_type_ids: UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase : int = None UpperCamelCase : Dict = None UpperCamelCase : str = None if self.use_labels: UpperCamelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Dict = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : List[str] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def a_ ( self ): return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[int] = XLMModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , lengths=SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[Any] = XLMWithLMHeadModel(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : List[str] = XLMForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : int = XLMForQuestionAnswering(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , p_mask=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , ) ((UpperCamelCase) , ) : Union[str, Any] = result_with_labels.to_tuple() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , ) : Tuple = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = XLMForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : int = self.num_labels UpperCamelCase : int = XLMForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : List[Any] = self.num_choices UpperCamelCase : Tuple = XLMForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Optional[Any] = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : int = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : List[Any] = config_and_inputs UpperCamelCase : Dict = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) lowercase : List[Any] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable lowercase : Optional[Any] = ( { 'feature-extraction': XLMModel, 'fill-mask': XLMWithLMHeadModel, 'question-answering': XLMForQuestionAnsweringSimple, 'text-classification': XLMForSequenceClassification, 'text-generation': XLMWithLMHeadModel, 'token-classification': XLMForTokenClassification, 'zero-shot': XLMForSequenceClassification, } if is_torch_available() else {} ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": UpperCamelCase : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) return inputs_dict def a_ ( self ): UpperCamelCase : List[Any] = XLMModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , emb_dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_attentions in attentions] , [True] * len(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : int = min_length + idx + 1 UpperCamelCase : Tuple = min_length + idx + 1 UpperCamelCase : Any = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_hidden_states in hidden_states] , [True] * len(SCREAMING_SNAKE_CASE_ ) , ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : List[str] = min_length + idx + 1 UpperCamelCase : Optional[Any] = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) , ) pass @slow def a_ ( self ): for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : str = XLMModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Dict = XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.tensor([[14, 447]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # the president UpperCamelCase : List[Any] = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference UpperCamelCase : Optional[int] = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , SCREAMING_SNAKE_CASE_ )
27
0
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def A_ ( snake_case_ : int ): '''simple docstring''' UpperCamelCase : int = int(number**0.5 ) return number == sq * sq def A_ ( snake_case_ : int ,snake_case_ : int ,snake_case_ : int ,snake_case_ : int ,snake_case_ : int ,snake_case_ : int ): '''simple docstring''' UpperCamelCase : int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den UpperCamelCase : int = x_den * y_den * z_den UpperCamelCase : int = gcd(snake_case_ ,snake_case_ ) top //= hcf bottom //= hcf return top, bottom def A_ ( snake_case_ : int = 3_5 ): '''simple docstring''' UpperCamelCase : set = set() UpperCamelCase : int UpperCamelCase : Fraction = Fraction(0 ) UpperCamelCase : tuple[int, int] for x_num in range(1 ,order + 1 ): for x_den in range(x_num + 1 ,order + 1 ): for y_num in range(1 ,order + 1 ): for y_den in range(y_num + 1 ,order + 1 ): # n=1 UpperCamelCase : Union[str, Any] = x_num * y_den + x_den * y_num UpperCamelCase : Any = x_den * y_den UpperCamelCase : List[str] = gcd(snake_case_ ,snake_case_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase : Union[str, Any] = add_three( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) unique_s.add(snake_case_ ) # n=2 UpperCamelCase : str = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) UpperCamelCase : int = x_den * x_den * y_den * y_den if is_sq(snake_case_ ) and is_sq(snake_case_ ): UpperCamelCase : Optional[Any] = int(sqrt(snake_case_ ) ) UpperCamelCase : int = int(sqrt(snake_case_ ) ) UpperCamelCase : Optional[int] = gcd(snake_case_ ,snake_case_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase : Union[str, Any] = add_three( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) unique_s.add(snake_case_ ) # n=-1 UpperCamelCase : Optional[Any] = x_num * y_num UpperCamelCase : Any = x_den * y_num + x_num * y_den UpperCamelCase : Optional[Any] = gcd(snake_case_ ,snake_case_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase : List[str] = add_three( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) unique_s.add(snake_case_ ) # n=2 UpperCamelCase : Union[str, Any] = x_num * x_num * y_num * y_num UpperCamelCase : List[Any] = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(snake_case_ ) and is_sq(snake_case_ ): UpperCamelCase : List[str] = int(sqrt(snake_case_ ) ) UpperCamelCase : List[str] = int(sqrt(snake_case_ ) ) UpperCamelCase : str = gcd(snake_case_ ,snake_case_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase : Optional[Any] = add_three( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) unique_s.add(snake_case_ ) for num, den in unique_s: total += Fraction(snake_case_ ,snake_case_ ) return total.denominator + total.numerator if __name__ == "__main__": print(F'''{solution() = }''')
350
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A : int = { '''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = [ '''GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTBigCodeForSequenceClassification''', '''GPTBigCodeForTokenClassification''', '''GPTBigCodeForCausalLM''', '''GPTBigCodeModel''', '''GPTBigCodePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
0
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : Optional[Any] = { '''configuration_informer''': [ '''INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''InformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = [ '''INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''InformerForPrediction''', '''InformerModel''', '''InformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
351
"""simple docstring""" import torch from transformers import AutoModel class lowerCamelCase ( torch.nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_="sayef/fsner-bert-base-uncased" ): super(SCREAMING_SNAKE_CASE_ , self ).__init__() UpperCamelCase : int = AutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.nn.CosineSimilarity(3 , 1e-08 ) UpperCamelCase : Any = torch.nn.Softmax(dim=1 ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return self.bert(**SCREAMING_SNAKE_CASE_ ).last_hidden_state def a_ ( self , SCREAMING_SNAKE_CASE_ ): return token_embeddings.sum(2 , keepdim=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1 ): return self.softmax(T * self.cos(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = W_supports["""sizes"""].tolist() UpperCamelCase : List[str] = W_supports["""start_token_id"""].item() UpperCamelCase : List[Any] = W_supports["""end_token_id"""].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCamelCase : List[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = None UpperCamelCase : Optional[Any] = None UpperCamelCase : Tuple = W_supports["""input_ids"""] == start_token_id UpperCamelCase : Optional[Any] = W_supports["""input_ids"""] == end_token_id for i, size in enumerate(SCREAMING_SNAKE_CASE_ ): if i == 0: UpperCamelCase : int = 0 else: UpperCamelCase : Optional[int] = support_sizes[i - 1] UpperCamelCase : Tuple = S[s : s + size][start_token_masks[s : s + size]] UpperCamelCase : int = S[s : s + size][end_token_masks[s : s + size]] UpperCamelCase : Dict = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCamelCase : Tuple = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCamelCase : List[str] = torch.vstack((p_starts, p_start) ) UpperCamelCase : Optional[Any] = torch.vstack((p_ends, p_end) ) else: UpperCamelCase : Optional[int] = p_start UpperCamelCase : Tuple = p_end return p_starts, p_ends
27
0
"""simple docstring""" import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() __A : List[str] = logging.get_logger(__name__) def A_ ( snake_case_ : Any ,snake_case_ : int ,snake_case_ : Any ): '''simple docstring''' UpperCamelCase : str = UniSpeechSatForSequenceClassification.from_pretrained(snake_case_ ,config=snake_case_ ) UpperCamelCase : List[Any] = downstream_dict["""projector.weight"""] UpperCamelCase : Tuple = downstream_dict["""projector.bias"""] UpperCamelCase : List[str] = downstream_dict["""model.post_net.linear.weight"""] UpperCamelCase : int = downstream_dict["""model.post_net.linear.bias"""] return model def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Tuple ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : Union[str, Any] = UniSpeechSatForAudioFrameClassification.from_pretrained(snake_case_ ,config=snake_case_ ) UpperCamelCase : str = downstream_dict["""model.linear.weight"""] UpperCamelCase : int = downstream_dict["""model.linear.bias"""] return model def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Dict ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : Union[str, Any] = UniSpeechSatForXVector.from_pretrained(snake_case_ ,config=snake_case_ ) UpperCamelCase : Union[str, Any] = downstream_dict["""connector.weight"""] UpperCamelCase : Optional[Any] = downstream_dict["""connector.bias"""] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): UpperCamelCase : Optional[int] = downstream_dict[ f'model.framelevel_feature_extractor.module.{i}.kernel.weight' ] UpperCamelCase : int = downstream_dict[f'model.framelevel_feature_extractor.module.{i}.kernel.bias'] UpperCamelCase : Optional[Any] = downstream_dict["""model.utterancelevel_feature_extractor.linear1.weight"""] UpperCamelCase : List[Any] = downstream_dict["""model.utterancelevel_feature_extractor.linear1.bias"""] UpperCamelCase : Union[str, Any] = downstream_dict["""model.utterancelevel_feature_extractor.linear2.weight"""] UpperCamelCase : str = downstream_dict["""model.utterancelevel_feature_extractor.linear2.bias"""] UpperCamelCase : Optional[int] = downstream_dict["""objective.W"""] return model @torch.no_grad() def A_ ( snake_case_ : Optional[int] ,snake_case_ : Dict ,snake_case_ : Optional[int] ,snake_case_ : Optional[Any] ): '''simple docstring''' UpperCamelCase : Optional[Any] = torch.load(snake_case_ ,map_location="""cpu""" ) UpperCamelCase : List[str] = checkpoint["""Downstream"""] UpperCamelCase : List[Any] = UniSpeechSatConfig.from_pretrained(snake_case_ ) UpperCamelCase : List[Any] = WavaVecaFeatureExtractor.from_pretrained( snake_case_ ,return_attention_mask=snake_case_ ,do_normalize=snake_case_ ) UpperCamelCase : str = hf_config.architectures[0] if arch.endswith("""ForSequenceClassification""" ): UpperCamelCase : List[Any] = convert_classification(snake_case_ ,snake_case_ ,snake_case_ ) elif arch.endswith("""ForAudioFrameClassification""" ): UpperCamelCase : int = convert_diarization(snake_case_ ,snake_case_ ,snake_case_ ) elif arch.endswith("""ForXVector""" ): UpperCamelCase : List[str] = convert_xvector(snake_case_ ,snake_case_ ,snake_case_ ) else: raise NotImplementedError(f'S3PRL weights conversion is not supported for {arch}' ) if hf_config.use_weighted_layer_sum: UpperCamelCase : str = checkpoint["""Featurizer"""]["""weights"""] hf_feature_extractor.save_pretrained(snake_case_ ) hf_model.save_pretrained(snake_case_ ) if __name__ == "__main__": __A : str = argparse.ArgumentParser() parser.add_argument( '''--base_model_name''', default=None, type=str, help='''Name of the huggingface pretrained base model.''' ) parser.add_argument('''--config_path''', default=None, type=str, help='''Path to the huggingface classifier config.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to the s3prl checkpoint.''') parser.add_argument('''--model_dump_path''', default=None, type=str, help='''Path to the final converted model.''') __A : Tuple = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
352
"""simple docstring""" from typing import Any class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = data UpperCamelCase : Optional[Any] = None def __repr__( self ): return f'Node({self.data})' class lowerCamelCase : def __init__( self ): UpperCamelCase : Dict = None def __iter__( self ): UpperCamelCase : int = self.head while node: yield node.data UpperCamelCase : Union[str, Any] = node.next def __len__( self ): return sum(1 for _ in self ) def __repr__( self ): return "->".join([str(SCREAMING_SNAKE_CASE_ ) for item in self] ) def __getitem__( self , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) UpperCamelCase : List[Any] = self.head for _ in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = current.next UpperCamelCase : Optional[Any] = data def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(len(self ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(0 , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index <= len(self ): raise IndexError("""list index out of range""" ) UpperCamelCase : Optional[Any] = Node(SCREAMING_SNAKE_CASE_ ) if self.head is None: UpperCamelCase : Dict = new_node elif index == 0: UpperCamelCase : Any = self.head # link new_node to head UpperCamelCase : Any = new_node else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : str = temp.next UpperCamelCase : Any = temp.next UpperCamelCase : Optional[Any] = new_node def a_ ( self ): # print every node data print(self ) def a_ ( self ): return self.delete_nth(0 ) def a_ ( self ): # delete from tail return self.delete_nth(len(self ) - 1 ) def a_ ( self , SCREAMING_SNAKE_CASE_ = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("""List index out of range.""" ) UpperCamelCase : Union[str, Any] = self.head # default first node if index == 0: UpperCamelCase : Optional[Any] = self.head.next else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : int = temp.next UpperCamelCase : Optional[Any] = temp.next UpperCamelCase : Dict = temp.next.next return delete_node.data def a_ ( self ): return self.head is None def a_ ( self ): UpperCamelCase : Optional[Any] = None UpperCamelCase : Union[str, Any] = self.head while current: # Store the current node's next node. UpperCamelCase : Optional[int] = current.next # Make the current node's next point backwards UpperCamelCase : Optional[Any] = prev # Make the previous node be the current node UpperCamelCase : int = current # Make the current node the next node (to progress iteration) UpperCamelCase : Optional[int] = next_node # Return prev in order to put the head at the end UpperCamelCase : Optional[int] = prev def A_ ( ): '''simple docstring''' UpperCamelCase : int = LinkedList() assert linked_list.is_empty() is True assert str(snake_case_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(1_0 ): assert len(snake_case_ ) == i linked_list.insert_nth(snake_case_ ,i + 1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_1 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(1_1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(0 ,1_2 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 1_0 assert linked_list.delete_tail() == 1_1 assert len(snake_case_ ) == 9 assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_0 ) ) assert all(linked_list[i] == i + 1 for i in range(0 ,9 ) ) is True for i in range(0 ,9 ): UpperCamelCase : Optional[Any] = -i assert all(linked_list[i] == -i for i in range(0 ,9 ) ) is True linked_list.reverse() assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(-8 ,1 ) ) def A_ ( ): '''simple docstring''' UpperCamelCase : int = [ -9, 1_0_0, Node(7_7_3_4_5_1_1_2 ), """dlrow olleH""", 7, 5_5_5_5, 0, -192.55555, """Hello, world!""", 77.9, Node(1_0 ), None, None, 12.20, ] UpperCamelCase : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(snake_case_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(snake_case_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head UpperCamelCase : Dict = linked_list.delete_head() assert result == -9 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail UpperCamelCase : int = linked_list.delete_tail() assert result == 12.2 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list UpperCamelCase : Optional[Any] = linked_list.delete_nth(1_0 ) assert result is None assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("""Hello again, world!""" ) ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(snake_case_ ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(snake_case_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def A_ ( ): '''simple docstring''' from doctest import testmod testmod() UpperCamelCase : List[Any] = LinkedList() linked_list.insert_head(input("""Inserting 1st at head """ ).strip() ) linked_list.insert_head(input("""Inserting 2nd at head """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() linked_list.insert_tail(input("""\nInserting 1st at tail """ ).strip() ) linked_list.insert_tail(input("""Inserting 2nd at tail """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() print("""\nDelete head""" ) linked_list.delete_head() print("""Delete tail""" ) linked_list.delete_tail() print("""\nPrint list:""" ) linked_list.print_list() print("""\nReverse linked list""" ) linked_list.reverse() print("""\nPrint list:""" ) linked_list.print_list() print("""\nString representation of linked list:""" ) print(snake_case_ ) print("""\nReading/changing Node data using indexing:""" ) print(f'Element at Position 1: {linked_list[1]}' ) UpperCamelCase : List[Any] = input("""Enter New Value: """ ).strip() print("""New list:""" ) print(snake_case_ ) print(f'length of linked_list is : {len(snake_case_ )}' ) if __name__ == "__main__": main()
27
0
"""simple docstring""" from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool __A : str = { '''Acehnese Arabic''': '''ace_Arab''', '''Acehnese Latin''': '''ace_Latn''', '''Mesopotamian Arabic''': '''acm_Arab''', '''Ta\'izzi-Adeni Arabic''': '''acq_Arab''', '''Tunisian Arabic''': '''aeb_Arab''', '''Afrikaans''': '''afr_Latn''', '''South Levantine Arabic''': '''ajp_Arab''', '''Akan''': '''aka_Latn''', '''Amharic''': '''amh_Ethi''', '''North Levantine Arabic''': '''apc_Arab''', '''Modern Standard Arabic''': '''arb_Arab''', '''Modern Standard Arabic Romanized''': '''arb_Latn''', '''Najdi Arabic''': '''ars_Arab''', '''Moroccan Arabic''': '''ary_Arab''', '''Egyptian Arabic''': '''arz_Arab''', '''Assamese''': '''asm_Beng''', '''Asturian''': '''ast_Latn''', '''Awadhi''': '''awa_Deva''', '''Central Aymara''': '''ayr_Latn''', '''South Azerbaijani''': '''azb_Arab''', '''North Azerbaijani''': '''azj_Latn''', '''Bashkir''': '''bak_Cyrl''', '''Bambara''': '''bam_Latn''', '''Balinese''': '''ban_Latn''', '''Belarusian''': '''bel_Cyrl''', '''Bemba''': '''bem_Latn''', '''Bengali''': '''ben_Beng''', '''Bhojpuri''': '''bho_Deva''', '''Banjar Arabic''': '''bjn_Arab''', '''Banjar Latin''': '''bjn_Latn''', '''Standard Tibetan''': '''bod_Tibt''', '''Bosnian''': '''bos_Latn''', '''Buginese''': '''bug_Latn''', '''Bulgarian''': '''bul_Cyrl''', '''Catalan''': '''cat_Latn''', '''Cebuano''': '''ceb_Latn''', '''Czech''': '''ces_Latn''', '''Chokwe''': '''cjk_Latn''', '''Central Kurdish''': '''ckb_Arab''', '''Crimean Tatar''': '''crh_Latn''', '''Welsh''': '''cym_Latn''', '''Danish''': '''dan_Latn''', '''German''': '''deu_Latn''', '''Southwestern Dinka''': '''dik_Latn''', '''Dyula''': '''dyu_Latn''', '''Dzongkha''': '''dzo_Tibt''', '''Greek''': '''ell_Grek''', '''English''': '''eng_Latn''', '''Esperanto''': '''epo_Latn''', '''Estonian''': '''est_Latn''', '''Basque''': '''eus_Latn''', '''Ewe''': '''ewe_Latn''', '''Faroese''': '''fao_Latn''', '''Fijian''': '''fij_Latn''', '''Finnish''': '''fin_Latn''', '''Fon''': '''fon_Latn''', '''French''': '''fra_Latn''', '''Friulian''': '''fur_Latn''', '''Nigerian Fulfulde''': '''fuv_Latn''', '''Scottish Gaelic''': '''gla_Latn''', '''Irish''': '''gle_Latn''', '''Galician''': '''glg_Latn''', '''Guarani''': '''grn_Latn''', '''Gujarati''': '''guj_Gujr''', '''Haitian Creole''': '''hat_Latn''', '''Hausa''': '''hau_Latn''', '''Hebrew''': '''heb_Hebr''', '''Hindi''': '''hin_Deva''', '''Chhattisgarhi''': '''hne_Deva''', '''Croatian''': '''hrv_Latn''', '''Hungarian''': '''hun_Latn''', '''Armenian''': '''hye_Armn''', '''Igbo''': '''ibo_Latn''', '''Ilocano''': '''ilo_Latn''', '''Indonesian''': '''ind_Latn''', '''Icelandic''': '''isl_Latn''', '''Italian''': '''ita_Latn''', '''Javanese''': '''jav_Latn''', '''Japanese''': '''jpn_Jpan''', '''Kabyle''': '''kab_Latn''', '''Jingpho''': '''kac_Latn''', '''Kamba''': '''kam_Latn''', '''Kannada''': '''kan_Knda''', '''Kashmiri Arabic''': '''kas_Arab''', '''Kashmiri Devanagari''': '''kas_Deva''', '''Georgian''': '''kat_Geor''', '''Central Kanuri Arabic''': '''knc_Arab''', '''Central Kanuri Latin''': '''knc_Latn''', '''Kazakh''': '''kaz_Cyrl''', '''Kabiyè''': '''kbp_Latn''', '''Kabuverdianu''': '''kea_Latn''', '''Khmer''': '''khm_Khmr''', '''Kikuyu''': '''kik_Latn''', '''Kinyarwanda''': '''kin_Latn''', '''Kyrgyz''': '''kir_Cyrl''', '''Kimbundu''': '''kmb_Latn''', '''Northern Kurdish''': '''kmr_Latn''', '''Kikongo''': '''kon_Latn''', '''Korean''': '''kor_Hang''', '''Lao''': '''lao_Laoo''', '''Ligurian''': '''lij_Latn''', '''Limburgish''': '''lim_Latn''', '''Lingala''': '''lin_Latn''', '''Lithuanian''': '''lit_Latn''', '''Lombard''': '''lmo_Latn''', '''Latgalian''': '''ltg_Latn''', '''Luxembourgish''': '''ltz_Latn''', '''Luba-Kasai''': '''lua_Latn''', '''Ganda''': '''lug_Latn''', '''Luo''': '''luo_Latn''', '''Mizo''': '''lus_Latn''', '''Standard Latvian''': '''lvs_Latn''', '''Magahi''': '''mag_Deva''', '''Maithili''': '''mai_Deva''', '''Malayalam''': '''mal_Mlym''', '''Marathi''': '''mar_Deva''', '''Minangkabau Arabic ''': '''min_Arab''', '''Minangkabau Latin''': '''min_Latn''', '''Macedonian''': '''mkd_Cyrl''', '''Plateau Malagasy''': '''plt_Latn''', '''Maltese''': '''mlt_Latn''', '''Meitei Bengali''': '''mni_Beng''', '''Halh Mongolian''': '''khk_Cyrl''', '''Mossi''': '''mos_Latn''', '''Maori''': '''mri_Latn''', '''Burmese''': '''mya_Mymr''', '''Dutch''': '''nld_Latn''', '''Norwegian Nynorsk''': '''nno_Latn''', '''Norwegian Bokmål''': '''nob_Latn''', '''Nepali''': '''npi_Deva''', '''Northern Sotho''': '''nso_Latn''', '''Nuer''': '''nus_Latn''', '''Nyanja''': '''nya_Latn''', '''Occitan''': '''oci_Latn''', '''West Central Oromo''': '''gaz_Latn''', '''Odia''': '''ory_Orya''', '''Pangasinan''': '''pag_Latn''', '''Eastern Panjabi''': '''pan_Guru''', '''Papiamento''': '''pap_Latn''', '''Western Persian''': '''pes_Arab''', '''Polish''': '''pol_Latn''', '''Portuguese''': '''por_Latn''', '''Dari''': '''prs_Arab''', '''Southern Pashto''': '''pbt_Arab''', '''Ayacucho Quechua''': '''quy_Latn''', '''Romanian''': '''ron_Latn''', '''Rundi''': '''run_Latn''', '''Russian''': '''rus_Cyrl''', '''Sango''': '''sag_Latn''', '''Sanskrit''': '''san_Deva''', '''Santali''': '''sat_Olck''', '''Sicilian''': '''scn_Latn''', '''Shan''': '''shn_Mymr''', '''Sinhala''': '''sin_Sinh''', '''Slovak''': '''slk_Latn''', '''Slovenian''': '''slv_Latn''', '''Samoan''': '''smo_Latn''', '''Shona''': '''sna_Latn''', '''Sindhi''': '''snd_Arab''', '''Somali''': '''som_Latn''', '''Southern Sotho''': '''sot_Latn''', '''Spanish''': '''spa_Latn''', '''Tosk Albanian''': '''als_Latn''', '''Sardinian''': '''srd_Latn''', '''Serbian''': '''srp_Cyrl''', '''Swati''': '''ssw_Latn''', '''Sundanese''': '''sun_Latn''', '''Swedish''': '''swe_Latn''', '''Swahili''': '''swh_Latn''', '''Silesian''': '''szl_Latn''', '''Tamil''': '''tam_Taml''', '''Tatar''': '''tat_Cyrl''', '''Telugu''': '''tel_Telu''', '''Tajik''': '''tgk_Cyrl''', '''Tagalog''': '''tgl_Latn''', '''Thai''': '''tha_Thai''', '''Tigrinya''': '''tir_Ethi''', '''Tamasheq Latin''': '''taq_Latn''', '''Tamasheq Tifinagh''': '''taq_Tfng''', '''Tok Pisin''': '''tpi_Latn''', '''Tswana''': '''tsn_Latn''', '''Tsonga''': '''tso_Latn''', '''Turkmen''': '''tuk_Latn''', '''Tumbuka''': '''tum_Latn''', '''Turkish''': '''tur_Latn''', '''Twi''': '''twi_Latn''', '''Central Atlas Tamazight''': '''tzm_Tfng''', '''Uyghur''': '''uig_Arab''', '''Ukrainian''': '''ukr_Cyrl''', '''Umbundu''': '''umb_Latn''', '''Urdu''': '''urd_Arab''', '''Northern Uzbek''': '''uzn_Latn''', '''Venetian''': '''vec_Latn''', '''Vietnamese''': '''vie_Latn''', '''Waray''': '''war_Latn''', '''Wolof''': '''wol_Latn''', '''Xhosa''': '''xho_Latn''', '''Eastern Yiddish''': '''ydd_Hebr''', '''Yoruba''': '''yor_Latn''', '''Yue Chinese''': '''yue_Hant''', '''Chinese Simplified''': '''zho_Hans''', '''Chinese Traditional''': '''zho_Hant''', '''Standard Malay''': '''zsm_Latn''', '''Zulu''': '''zul_Latn''', } class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[str] = 'facebook/nllb-200-distilled-600M' lowercase : Union[str, Any] = ( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) lowercase : List[str] = 'translator' lowercase : Union[str, Any] = AutoTokenizer lowercase : List[str] = AutoModelForSeqaSeqLM lowercase : List[str] = LANGUAGE_CODES lowercase : int = ['text', 'text', 'text'] lowercase : List[str] = ['text'] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) UpperCamelCase : str = self.lang_to_code[src_lang] UpperCamelCase : Optional[int] = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , src_lang=SCREAMING_SNAKE_CASE_ , tgt_lang=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.model.generate(**SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
353
"""simple docstring""" import argparse import os import re __A : Dict = '''src/diffusers''' # Pattern that looks at the indentation in a line. __A : Union[str, Any] = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : Tuple = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Tuple = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Union[str, Any] = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Dict="" ,snake_case_ : Dict=None ,snake_case_ : Any=None ): '''simple docstring''' UpperCamelCase : Optional[int] = 0 UpperCamelCase : List[Any] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Optional[Any] = ["""\n""".join(lines[:index] )] else: UpperCamelCase : int = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Any = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Any = [lines[index + 1]] index += 1 else: UpperCamelCase : List[str] = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' def _inner(snake_case_ : Tuple ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[int]=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Dict ): return x if key is None: UpperCamelCase : int = noop # Constants are all uppercase, they go first. UpperCamelCase : List[Any] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : str = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : List[str] = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Tuple = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : int ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : List[Any] ): UpperCamelCase : Any = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : Union[str, Any] = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[str] = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : str = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : str = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Dict = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : int = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[Any] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : Optional[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[Any] = keys[:-1] UpperCamelCase : int = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Tuple ,snake_case_ : str=True ): '''simple docstring''' with open(snake_case_ ,"""r""" ) as f: UpperCamelCase : int = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : Dict = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Optional[Any] = main_blocks[block_idx] UpperCamelCase : Optional[int] = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : Union[str, Any] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : List[str] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Dict = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Union[str, Any] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : Optional[int] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Union[str, Any] = _re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Union[str, Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Optional[Any] = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : List[Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[Any] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: UpperCamelCase : str = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Any = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Union[str, Any] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : Any = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Any = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : str = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
0
"""simple docstring""" from collections import defaultdict class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = total # total no of tasks (N) # DP table will have a dimension of (2^M)*N # initially all values are set to -1 UpperCamelCase : int = [ [-1 for i in range(total + 1 )] for j in range(2 ** len(SCREAMING_SNAKE_CASE_ ) ) ] UpperCamelCase : Optional[int] = defaultdict(SCREAMING_SNAKE_CASE_ ) # stores the list of persons for each task # final_mask is used to check if all persons are included by setting all bits # to 1 UpperCamelCase : Dict = (1 << len(SCREAMING_SNAKE_CASE_ )) - 1 def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): # if mask == self.finalmask all persons are distributed tasks, return 1 if mask == self.final_mask: return 1 # if not everyone gets the task and no more tasks are available, return 0 if task_no > self.total_tasks: return 0 # if case already considered if self.dp[mask][task_no] != -1: return self.dp[mask][task_no] # Number of ways when we don't this task in the arrangement UpperCamelCase : str = self.count_ways_until(SCREAMING_SNAKE_CASE_ , task_no + 1 ) # now assign the tasks one by one to all possible persons and recursively # assign for the remaining tasks. if task_no in self.task: for p in self.task[task_no]: # if p is already given a task if mask & (1 << p): continue # assign this task to p and change the mask value. And recursively # assign tasks with the new mask value. total_ways_util += self.count_ways_until(mask | (1 << p) , task_no + 1 ) # save the value. UpperCamelCase : List[str] = total_ways_util return self.dp[mask][task_no] def a_ ( self , SCREAMING_SNAKE_CASE_ ): # Store the list of persons for each task for i in range(len(SCREAMING_SNAKE_CASE_ ) ): for j in task_performed[i]: self.task[j].append(SCREAMING_SNAKE_CASE_ ) # call the function to fill the DP table, final answer is stored in dp[0][1] return self.count_ways_until(0 , 1 ) if __name__ == "__main__": __A : int = 5 # total no of tasks (the value of N) # the list of tasks that can be done by M persons. __A : Optional[int] = [[1, 3, 4], [1, 2, 5], [3, 4]] print( AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( task_performed ) )
354
"""simple docstring""" def A_ ( snake_case_ : list[int] ): '''simple docstring''' if not numbers: return 0 if not isinstance(snake_case_ ,(list, tuple) ) or not all( isinstance(snake_case_ ,snake_case_ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) UpperCamelCase : int = numbers[0] for i in range(1 ,len(snake_case_ ) ): # update the maximum and minimum subarray products UpperCamelCase : List[str] = numbers[i] if number < 0: UpperCamelCase , UpperCamelCase : Optional[int] = min_till_now, max_till_now UpperCamelCase : Dict = max(snake_case_ ,max_till_now * number ) UpperCamelCase : Union[str, Any] = min(snake_case_ ,min_till_now * number ) # update the maximum product found till now UpperCamelCase : Union[str, Any] = max(snake_case_ ,snake_case_ ) return max_prod
27
0
"""simple docstring""" import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): UpperCamelCase : Optional[int] = torch.nn.Linear(10 , 10 ) UpperCamelCase : Tuple = torch.optim.SGD(model.parameters() , 0.1 ) UpperCamelCase : str = Accelerator() UpperCamelCase : Union[str, Any] = accelerator.prepare(SCREAMING_SNAKE_CASE_ ) try: pickle.loads(pickle.dumps(SCREAMING_SNAKE_CASE_ ) ) except Exception as e: self.fail(f'Accelerated optimizer pickling failed with {e}' ) AcceleratorState._reset_state()
355
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Any = AudioLDMPipeline lowercase : Union[str, Any] = TEXT_TO_AUDIO_PARAMS lowercase : List[str] = TEXT_TO_AUDIO_BATCH_PARAMS lowercase : Tuple = frozenset( [ 'num_inference_steps', 'num_waveforms_per_prompt', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=(32, 64) , class_embed_type="""simple_projection""" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[Any] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , ) torch.manual_seed(0 ) UpperCamelCase : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCamelCase : int = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) UpperCamelCase : Optional[int] = ClapTextModelWithProjection(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta""" , model_max_length=77 ) UpperCamelCase : Tuple = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """vocoder""": vocoder, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Any = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """prompt""": """A hammer hitting a wooden surface""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, } return inputs def a_ ( self ): UpperCamelCase : str = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Any = self.get_dummy_components() UpperCamelCase : int = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Tuple = audio[:10] UpperCamelCase : Dict = np.array( [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[str] = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Optional[int] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) UpperCamelCase : Tuple = prompt_embeds # forward UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : List[str] = self.get_dummy_components() UpperCamelCase : List[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * ["""this is a negative prompt"""] UpperCamelCase : List[Any] = negative_prompt UpperCamelCase : str = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : str = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] UpperCamelCase : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[Any] = [] for p in [prompt, negative_prompt]: UpperCamelCase : int = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Union[str, Any] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = text_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) embeds.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Tuple = embeds # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Optional[int] = self.get_dummy_components() UpperCamelCase : List[str] = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = """egg cracking""" UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Union[str, Any] = audio[:10] UpperCamelCase : Dict = np.array( [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Union[str, Any] = self.get_dummy_components() UpperCamelCase : Tuple = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = """A hammer hitting a wooden surface""" # test num_waveforms_per_prompt=1 (default) UpperCamelCase : List[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts UpperCamelCase : Dict = 2 UpperCamelCase : List[str] = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt UpperCamelCase : List[str] = 2 UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts UpperCamelCase : Any = 2 UpperCamelCase : str = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = audioldm_pipe.vocoder.config.sampling_rate UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe(audio_length_in_s=0.016 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.016 UpperCamelCase : Optional[Any] = audioldm_pipe(audio_length_in_s=0.032 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.032 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Optional[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = ["""hey"""] UpperCamelCase : Dict = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : str = output.audios.shape assert audio_shape == (1, 256) UpperCamelCase : Optional[Any] = audioldm_pipe.vocoder.config config.model_in_dim *= 2 UpperCamelCase : str = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : List[str] = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def a_ ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self._test_inference_batch_single_identical(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def a_ ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @slow class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="cpu" , SCREAMING_SNAKE_CASE_=torch.floataa , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : str = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = np.random.RandomState(SCREAMING_SNAKE_CASE_ ).standard_normal((1, 8, 128, 16) ) UpperCamelCase : int = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = { """prompt""": """A hammer hitting a wooden surface""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 2.5, } return inputs def a_ ( self ): UpperCamelCase : Optional[int] = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = 25 UpperCamelCase : Optional[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[7_7230:7_7240] UpperCamelCase : Optional[Any] = np.array( [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] ) UpperCamelCase : Any = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def a_ ( self ): UpperCamelCase : Any = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : Any = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) UpperCamelCase : str = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[2_7780:2_7790] UpperCamelCase : Tuple = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] ) UpperCamelCase : Tuple = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
27
0
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Tuple = LayoutLMTokenizer lowercase : List[str] = LayoutLMTokenizerFast lowercase : List[str] = True lowercase : str = True def a_ ( self ): super().setUp() UpperCamelCase : Union[str, Any] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] UpperCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = """UNwant\u00E9d,running""" UpperCamelCase : Dict = """unwanted, running""" return input_text, output_text def a_ ( self ): UpperCamelCase : int = self.tokenizer_class(self.vocab_file ) UpperCamelCase : Any = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [7, 4, 5, 10, 8, 9] ) def a_ ( self ): pass
356
"""simple docstring""" import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def A_ ( snake_case_ : Dataset ,snake_case_ : Dict[str, str] ): '''simple docstring''' UpperCamelCase : List[str] = args.log_outputs UpperCamelCase : Tuple = """_""".join(args.dataset.split("""/""" ) + [args.config, args.split] ) # load metric UpperCamelCase : List[Any] = load_metric("""wer""" ) UpperCamelCase : Any = load_metric("""cer""" ) # compute metrics UpperCamelCase : str = wer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) UpperCamelCase : Dict = cer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) # print & log results UpperCamelCase : Optional[int] = f'WER: {wer_result}\nCER: {cer_result}' print(snake_case_ ) with open(f'{dataset_id}_eval_results.txt' ,"""w""" ) as f: f.write(snake_case_ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: UpperCamelCase : Optional[Any] = f'log_{dataset_id}_predictions.txt' UpperCamelCase : str = f'log_{dataset_id}_targets.txt' with open(snake_case_ ,"""w""" ) as p, open(snake_case_ ,"""w""" ) as t: # mapping function to write output def write_to_file(snake_case_ : Union[str, Any] ,snake_case_ : Tuple ): p.write(f'{i}' + """\n""" ) p.write(batch["""prediction"""] + """\n""" ) t.write(f'{i}' + """\n""" ) t.write(batch["""target"""] + """\n""" ) result.map(snake_case_ ,with_indices=snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Dict = """[,?.!\-\;\:\"“%‘”�—’…–]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training UpperCamelCase : str = re.sub(snake_case_ ,"""""" ,text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! UpperCamelCase : List[str] = ["""\n\n""", """\n""", """ """, """ """] for t in token_sequences_to_ignore: UpperCamelCase : Tuple = """ """.join(text.split(snake_case_ ) ) return text def A_ ( snake_case_ : str ): '''simple docstring''' # load dataset UpperCamelCase : Union[str, Any] = load_dataset(args.dataset ,args.config ,split=args.split ,use_auth_token=snake_case_ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor UpperCamelCase : List[Any] = AutoFeatureExtractor.from_pretrained(args.model_id ) UpperCamelCase : Dict = feature_extractor.sampling_rate # resample audio UpperCamelCase : Optional[Any] = dataset.cast_column("""audio""" ,Audio(sampling_rate=snake_case_ ) ) # load eval pipeline if args.device is None: UpperCamelCase : int = 0 if torch.cuda.is_available() else -1 UpperCamelCase : Union[str, Any] = pipeline("""automatic-speech-recognition""" ,model=args.model_id ,device=args.device ) # map function to decode audio def map_to_pred(snake_case_ : Union[str, Any] ): UpperCamelCase : List[Any] = asr( batch["""audio"""]["""array"""] ,chunk_length_s=args.chunk_length_s ,stride_length_s=args.stride_length_s ) UpperCamelCase : Union[str, Any] = prediction["""text"""] UpperCamelCase : Optional[Any] = normalize_text(batch["""sentence"""] ) return batch # run inference on all examples UpperCamelCase : Any = dataset.map(snake_case_ ,remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(snake_case_ ,snake_case_ ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() parser.add_argument( '''--model_id''', type=str, required=True, help='''Model identifier. Should be loadable with 🤗 Transformers''' ) parser.add_argument( '''--dataset''', type=str, required=True, help='''Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets''', ) parser.add_argument( '''--config''', type=str, required=True, help='''Config of the dataset. *E.g.* `\'en\'` for Common Voice''' ) parser.add_argument('''--split''', type=str, required=True, help='''Split of the dataset. *E.g.* `\'test\'`''') parser.add_argument( '''--chunk_length_s''', type=float, default=None, help='''Chunk length in seconds. Defaults to 5 seconds.''' ) parser.add_argument( '''--stride_length_s''', type=float, default=None, help='''Stride of the audio chunks. Defaults to 1 second.''' ) parser.add_argument( '''--log_outputs''', action='''store_true''', help='''If defined, write outputs to log file for analysis.''' ) parser.add_argument( '''--device''', type=int, default=None, help='''The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.''', ) __A : Optional[Any] = parser.parse_args() main(args)
27
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __A : int = { '''configuration_graphormer''': ['''GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GraphormerConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = [ '''GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GraphormerForGraphClassification''', '''GraphormerModel''', '''GraphormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
357
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'EncodecFeatureExtractor' lowercase : List[Any] = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.feature_extractor UpperCamelCase : Any = False def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True ): return self.tokenizer.get_decoder_prompt_ids(task=SCREAMING_SNAKE_CASE_ , language=SCREAMING_SNAKE_CASE_ , no_timestamps=SCREAMING_SNAKE_CASE_ ) def __call__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = kwargs.pop("""sampling_rate""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Any = args[0] UpperCamelCase : str = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if text is not None: UpperCamelCase : Optional[int] = self.tokenizer(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is not None: UpperCamelCase : str = self.feature_extractor(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is None: return inputs elif text is None: return audio_inputs else: UpperCamelCase : int = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: UpperCamelCase : Optional[Any] = audio_inputs["""padding_mask"""] return inputs def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = kwargs.pop("""padding_mask""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Optional[int] = args[0] UpperCamelCase : Any = args[1:] if audio_values is not None: return self._decode_audio(SCREAMING_SNAKE_CASE_ , padding_mask=SCREAMING_SNAKE_CASE_ ) else: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = to_numpy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase : int = audio_values.shape if padding_mask is None: return list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = to_numpy(SCREAMING_SNAKE_CASE_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) UpperCamelCase : List[str] = seq_len - padding_mask.shape[-1] UpperCamelCase : Optional[int] = 1 - self.feature_extractor.padding_value UpperCamelCase : Any = np.pad(SCREAMING_SNAKE_CASE_ , ((0, 0), (0, difference)) , """constant""" , constant_values=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audio_values.tolist() for i in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] UpperCamelCase : Optional[Any] = sliced_audio.reshape(SCREAMING_SNAKE_CASE_ , -1 ) return audio_values
27
0
"""simple docstring""" from typing import Any class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = data UpperCamelCase : Optional[Any] = None def __repr__( self ): return f'Node({self.data})' class lowerCamelCase : def __init__( self ): UpperCamelCase : Dict = None def __iter__( self ): UpperCamelCase : int = self.head while node: yield node.data UpperCamelCase : Union[str, Any] = node.next def __len__( self ): return sum(1 for _ in self ) def __repr__( self ): return "->".join([str(SCREAMING_SNAKE_CASE_ ) for item in self] ) def __getitem__( self , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) UpperCamelCase : List[Any] = self.head for _ in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = current.next UpperCamelCase : Optional[Any] = data def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(len(self ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(0 , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index <= len(self ): raise IndexError("""list index out of range""" ) UpperCamelCase : Optional[Any] = Node(SCREAMING_SNAKE_CASE_ ) if self.head is None: UpperCamelCase : Dict = new_node elif index == 0: UpperCamelCase : Any = self.head # link new_node to head UpperCamelCase : Any = new_node else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : str = temp.next UpperCamelCase : Any = temp.next UpperCamelCase : Optional[Any] = new_node def a_ ( self ): # print every node data print(self ) def a_ ( self ): return self.delete_nth(0 ) def a_ ( self ): # delete from tail return self.delete_nth(len(self ) - 1 ) def a_ ( self , SCREAMING_SNAKE_CASE_ = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("""List index out of range.""" ) UpperCamelCase : Union[str, Any] = self.head # default first node if index == 0: UpperCamelCase : Optional[Any] = self.head.next else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : int = temp.next UpperCamelCase : Optional[Any] = temp.next UpperCamelCase : Dict = temp.next.next return delete_node.data def a_ ( self ): return self.head is None def a_ ( self ): UpperCamelCase : Optional[Any] = None UpperCamelCase : Union[str, Any] = self.head while current: # Store the current node's next node. UpperCamelCase : Optional[int] = current.next # Make the current node's next point backwards UpperCamelCase : Optional[Any] = prev # Make the previous node be the current node UpperCamelCase : int = current # Make the current node the next node (to progress iteration) UpperCamelCase : Optional[int] = next_node # Return prev in order to put the head at the end UpperCamelCase : Optional[int] = prev def A_ ( ): '''simple docstring''' UpperCamelCase : int = LinkedList() assert linked_list.is_empty() is True assert str(snake_case_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(1_0 ): assert len(snake_case_ ) == i linked_list.insert_nth(snake_case_ ,i + 1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_1 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(1_1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(0 ,1_2 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 1_0 assert linked_list.delete_tail() == 1_1 assert len(snake_case_ ) == 9 assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_0 ) ) assert all(linked_list[i] == i + 1 for i in range(0 ,9 ) ) is True for i in range(0 ,9 ): UpperCamelCase : Optional[Any] = -i assert all(linked_list[i] == -i for i in range(0 ,9 ) ) is True linked_list.reverse() assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(-8 ,1 ) ) def A_ ( ): '''simple docstring''' UpperCamelCase : int = [ -9, 1_0_0, Node(7_7_3_4_5_1_1_2 ), """dlrow olleH""", 7, 5_5_5_5, 0, -192.55555, """Hello, world!""", 77.9, Node(1_0 ), None, None, 12.20, ] UpperCamelCase : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(snake_case_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(snake_case_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head UpperCamelCase : Dict = linked_list.delete_head() assert result == -9 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail UpperCamelCase : int = linked_list.delete_tail() assert result == 12.2 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list UpperCamelCase : Optional[Any] = linked_list.delete_nth(1_0 ) assert result is None assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("""Hello again, world!""" ) ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(snake_case_ ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(snake_case_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def A_ ( ): '''simple docstring''' from doctest import testmod testmod() UpperCamelCase : List[Any] = LinkedList() linked_list.insert_head(input("""Inserting 1st at head """ ).strip() ) linked_list.insert_head(input("""Inserting 2nd at head """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() linked_list.insert_tail(input("""\nInserting 1st at tail """ ).strip() ) linked_list.insert_tail(input("""Inserting 2nd at tail """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() print("""\nDelete head""" ) linked_list.delete_head() print("""Delete tail""" ) linked_list.delete_tail() print("""\nPrint list:""" ) linked_list.print_list() print("""\nReverse linked list""" ) linked_list.reverse() print("""\nPrint list:""" ) linked_list.print_list() print("""\nString representation of linked list:""" ) print(snake_case_ ) print("""\nReading/changing Node data using indexing:""" ) print(f'Element at Position 1: {linked_list[1]}' ) UpperCamelCase : List[Any] = input("""Enter New Value: """ ).strip() print("""New list:""" ) print(snake_case_ ) print(f'length of linked_list is : {len(snake_case_ )}' ) if __name__ == "__main__": main()
358
"""simple docstring""" import requests from bsa import BeautifulSoup def A_ ( snake_case_ : str = "https://www.worldometers.info/coronavirus" ): '''simple docstring''' UpperCamelCase : Any = BeautifulSoup(requests.get(snake_case_ ).text ,"""html.parser""" ) UpperCamelCase : Optional[int] = soup.findAll("""h1""" ) UpperCamelCase : List[Any] = soup.findAll("""div""" ,{"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" ,{"""class""": """panel-title"""} ) values += soup.findAll("""div""" ,{"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(snake_case_ ,snake_case_ )} if __name__ == "__main__": print('''\033[1m''' + '''COVID-19 Status of the World''' + '''\033[0m\n''') for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
27
0
from __future__ import annotations import math import random from typing import Any class lowerCamelCase : def __init__( self ): UpperCamelCase : list[Any] = [] UpperCamelCase : int = 0 UpperCamelCase : int = 0 def a_ ( self ): return self.head == self.tail def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.data.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.tail + 1 def a_ ( self ): UpperCamelCase : List[str] = self.data[self.head] UpperCamelCase : Optional[Any] = self.head + 1 return ret def a_ ( self ): return self.tail - self.head def a_ ( self ): print(self.data ) print("""**************""" ) print(self.data[self.head : self.tail] ) class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = data UpperCamelCase : MyNode | None = None UpperCamelCase : MyNode | None = None UpperCamelCase : int = 1 def a_ ( self ): return self.data def a_ ( self ): return self.left def a_ ( self ): return self.right def a_ ( self ): return self.height def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = data def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = node def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = node def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = height def A_ ( snake_case_ : MyNode | None ): '''simple docstring''' if node is None: return 0 return node.get_height() def A_ ( snake_case_ : int ,snake_case_ : int ): '''simple docstring''' if a > b: return a return b def A_ ( snake_case_ : MyNode ): '''simple docstring''' print("""left rotation node:""" ,node.get_data() ) UpperCamelCase : Optional[int] = node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(snake_case_ ) UpperCamelCase : int = my_max(get_height(node.get_right() ) ,get_height(node.get_left() ) ) + 1 node.set_height(snake_case_ ) UpperCamelCase : List[Any] = my_max(get_height(ret.get_right() ) ,get_height(ret.get_left() ) ) + 1 ret.set_height(snake_case_ ) return ret def A_ ( snake_case_ : MyNode ): '''simple docstring''' print("""right rotation node:""" ,node.get_data() ) UpperCamelCase : Tuple = node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(snake_case_ ) UpperCamelCase : Union[str, Any] = my_max(get_height(node.get_right() ) ,get_height(node.get_left() ) ) + 1 node.set_height(snake_case_ ) UpperCamelCase : Optional[int] = my_max(get_height(ret.get_right() ) ,get_height(ret.get_left() ) ) + 1 ret.set_height(snake_case_ ) return ret def A_ ( snake_case_ : MyNode ): '''simple docstring''' UpperCamelCase : Any = node.get_left() assert left_child is not None node.set_left(left_rotation(snake_case_ ) ) return right_rotation(snake_case_ ) def A_ ( snake_case_ : MyNode ): '''simple docstring''' UpperCamelCase : List[Any] = node.get_right() assert right_child is not None node.set_right(right_rotation(snake_case_ ) ) return left_rotation(snake_case_ ) def A_ ( snake_case_ : MyNode | None ,snake_case_ : Any ): '''simple docstring''' if node is None: return MyNode(snake_case_ ) if data < node.get_data(): node.set_left(insert_node(node.get_left() ,snake_case_ ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected UpperCamelCase : Any = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child UpperCamelCase : Optional[int] = right_rotation(snake_case_ ) else: UpperCamelCase : str = lr_rotation(snake_case_ ) else: node.set_right(insert_node(node.get_right() ,snake_case_ ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: UpperCamelCase : int = node.get_right() assert right_child is not None if data < right_child.get_data(): UpperCamelCase : str = rl_rotation(snake_case_ ) else: UpperCamelCase : Union[str, Any] = left_rotation(snake_case_ ) UpperCamelCase : str = my_max(get_height(node.get_right() ) ,get_height(node.get_left() ) ) + 1 node.set_height(snake_case_ ) return node def A_ ( snake_case_ : MyNode ): '''simple docstring''' while True: UpperCamelCase : List[str] = root.get_right() if right_child is None: break UpperCamelCase : int = right_child return root.get_data() def A_ ( snake_case_ : MyNode ): '''simple docstring''' while True: UpperCamelCase : str = root.get_left() if left_child is None: break UpperCamelCase : str = left_child return root.get_data() def A_ ( snake_case_ : MyNode ,snake_case_ : Any ): '''simple docstring''' UpperCamelCase : Any = root.get_left() UpperCamelCase : str = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: UpperCamelCase : Tuple = get_left_most(snake_case_ ) root.set_data(snake_case_ ) root.set_right(del_node(snake_case_ ,snake_case_ ) ) elif left_child is not None: UpperCamelCase : List[str] = left_child elif right_child is not None: UpperCamelCase : Optional[Any] = right_child else: return None elif root.get_data() > data: if left_child is None: print("""No such data""" ) return root else: root.set_left(del_node(snake_case_ ,snake_case_ ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(snake_case_ ,snake_case_ ) ) if get_height(snake_case_ ) - get_height(snake_case_ ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): UpperCamelCase : str = left_rotation(snake_case_ ) else: UpperCamelCase : List[Any] = rl_rotation(snake_case_ ) elif get_height(snake_case_ ) - get_height(snake_case_ ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): UpperCamelCase : Optional[Any] = right_rotation(snake_case_ ) else: UpperCamelCase : str = lr_rotation(snake_case_ ) UpperCamelCase : Any = my_max(get_height(root.get_right() ) ,get_height(root.get_left() ) ) + 1 root.set_height(snake_case_ ) return root class lowerCamelCase : def __init__( self ): UpperCamelCase : MyNode | None = None def a_ ( self ): return get_height(self.root ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): print("""insert:""" + str(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Any = insert_node(self.root , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): print("""delete:""" + str(SCREAMING_SNAKE_CASE_ ) ) if self.root is None: print("""Tree is empty!""" ) return UpperCamelCase : Tuple = del_node(self.root , SCREAMING_SNAKE_CASE_ ) def __str__( self , ): # a level traversale, gives a more intuitive look on the tree UpperCamelCase : Union[str, Any] = """""" UpperCamelCase : Any = MyQueue() q.push(self.root ) UpperCamelCase : str = self.get_height() if layer == 0: return output UpperCamelCase : Any = 0 while not q.is_empty(): UpperCamelCase : Tuple = q.pop() UpperCamelCase : List[str] = """ """ * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(SCREAMING_SNAKE_CASE_ ) q.push(SCREAMING_SNAKE_CASE_ ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space UpperCamelCase : str = cnt + 1 for i in range(100 ): if cnt == math.pow(2 , SCREAMING_SNAKE_CASE_ ) - 1: UpperCamelCase : Tuple = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def A_ ( ): '''simple docstring''' import doctest doctest.testmod() if __name__ == "__main__": _test() __A : str = AVLtree() __A : List[str] = list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
359
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=1 , ): UpperCamelCase : Tuple = parent UpperCamelCase : Optional[int] = batch_size UpperCamelCase : Optional[Any] = seq_length UpperCamelCase : int = is_training UpperCamelCase : Union[str, Any] = use_input_mask UpperCamelCase : Union[str, Any] = use_token_type_ids UpperCamelCase : Dict = use_labels UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : Tuple = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : int = intermediate_size UpperCamelCase : str = hidden_act UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Optional[Any] = type_vocab_size UpperCamelCase : int = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : Dict = num_labels UpperCamelCase : Tuple = num_choices UpperCamelCase : Optional[int] = scope UpperCamelCase : List[Any] = q_groups UpperCamelCase : Tuple = k_groups UpperCamelCase : Any = v_groups UpperCamelCase : List[str] = post_attention_groups UpperCamelCase : Tuple = intermediate_groups UpperCamelCase : int = output_groups def a_ ( self ): UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Tuple = None if self.use_input_mask: UpperCamelCase : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Optional[int] = None UpperCamelCase : List[Any] = None UpperCamelCase : Dict = None if self.use_labels: UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self ): return SqueezeBertConfig( embedding_size=self.hidden_size , vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = SqueezeBertModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = SqueezeBertForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = SqueezeBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : str = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.num_labels UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.num_labels UpperCamelCase : str = SqueezeBertForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = self.num_choices UpperCamelCase : Tuple = SqueezeBertForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = config_and_inputs UpperCamelCase : Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) lowercase : Dict = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) lowercase : Dict = False lowercase : str = True lowercase : str = False def a_ ( self ): UpperCamelCase : Any = SqueezeBertModelTester(self ) UpperCamelCase : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Optional[Any] = SqueezeBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_sentencepiece @require_tokenizers @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification.from_pretrained("""squeezebert/squeezebert-mnli""" ) UpperCamelCase : Dict = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]] ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[Any] = torch.Size((1, 3) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
27
0
"""simple docstring""" import warnings from functools import wraps from typing import Callable def A_ ( snake_case_ : Callable ): '''simple docstring''' @wraps(snake_case_ ) def _inner_fn(*snake_case_ : Dict ,**snake_case_ : int ): warnings.warn( (f'\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.') ,snake_case_ ,) return fn(*snake_case_ ,**snake_case_ ) return _inner_fn
360
"""simple docstring""" from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class lowerCamelCase ( nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 88 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "geglu" , SCREAMING_SNAKE_CASE_ = None , ): super().__init__() UpperCamelCase : int = nn.ModuleList( [ TransformeraDModel( num_attention_heads=SCREAMING_SNAKE_CASE_ , attention_head_dim=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , dropout=SCREAMING_SNAKE_CASE_ , norm_num_groups=SCREAMING_SNAKE_CASE_ , cross_attention_dim=SCREAMING_SNAKE_CASE_ , attention_bias=SCREAMING_SNAKE_CASE_ , sample_size=SCREAMING_SNAKE_CASE_ , num_vector_embeds=SCREAMING_SNAKE_CASE_ , activation_fn=SCREAMING_SNAKE_CASE_ , num_embeds_ada_norm=SCREAMING_SNAKE_CASE_ , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference UpperCamelCase : Optional[Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` UpperCamelCase : List[Any] = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` UpperCamelCase : int = [1, 0] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = True , ): UpperCamelCase : Dict = hidden_states UpperCamelCase : Optional[Any] = [] UpperCamelCase : List[Any] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens UpperCamelCase : Optional[int] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] UpperCamelCase : str = self.transformer_index_for_condition[i] UpperCamelCase : Any = self.transformers[transformer_index]( SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , timestep=SCREAMING_SNAKE_CASE_ , cross_attention_kwargs=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] UpperCamelCase : Any = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) UpperCamelCase : List[str] = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=SCREAMING_SNAKE_CASE_ )
27
0
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) __A : Dict = '''\ Text data. Second line of data.''' __A : Optional[Any] = '''file''' @pytest.fixture(scope="""session""" ) def A_ ( snake_case_ : Any ): '''simple docstring''' UpperCamelCase : str = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") UpperCamelCase : List[Any] = bytes(snake_case_ ,"""utf-8""" ) with zstd.open(snake_case_ ,"""wb""" ) as f: f.write(snake_case_ ) return path @pytest.fixture def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' with open(os.path.join(tmpfs.local_root_dir ,snake_case_ ) ,"""w""" ) as f: f.write(snake_case_ ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" ,["""gzip""", """xz""", """zstd"""] ) def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Optional[int] ,snake_case_ : Optional[int] ,snake_case_ : List[Any] ,snake_case_ : str ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : Optional[Any] = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} UpperCamelCase : str = input_paths[compression_format] UpperCamelCase : Union[str, Any] = tmp_path / """cache""" UpperCamelCase : List[Any] = DownloadConfig(cache_dir=snake_case_ ,extract_compressed_file=snake_case_ ) UpperCamelCase : Tuple = cached_path(snake_case_ ,download_config=snake_case_ ) with open(snake_case_ ) as f: UpperCamelCase : Dict = f.read() with open(snake_case_ ) as f: UpperCamelCase : Optional[int] = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" ,[True, False] ) @pytest.mark.parametrize("""default_cache_dir""" ,[True, False] ) def A_ ( snake_case_ : Optional[Any] ,snake_case_ : List[Any] ,snake_case_ : Optional[int] ,snake_case_ : Dict ,snake_case_ : int ): '''simple docstring''' UpperCamelCase : Union[str, Any] = """custom_cache""" UpperCamelCase : str = """custom_extracted_dir""" UpperCamelCase : Optional[Any] = tmp_path / """custom_extracted_path""" if default_extracted: UpperCamelCase : Optional[Any] = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" ,snake_case_ ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" ,str(snake_case_ ) ) UpperCamelCase : str = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) UpperCamelCase : int = xz_file UpperCamelCase : List[str] = ( DownloadConfig(extract_compressed_file=snake_case_ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir ,extract_compressed_file=snake_case_ ) ) UpperCamelCase : List[Any] = cached_path(snake_case_ ,download_config=snake_case_ ) assert Path(snake_case_ ).parent.parts[-2:] == expected def A_ ( snake_case_ : int ): '''simple docstring''' UpperCamelCase : Tuple = str(Path(snake_case_ ).resolve() ) assert cached_path(snake_case_ ) == text_file # relative path UpperCamelCase : str = str(Path(snake_case_ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(snake_case_ ) == text_file def A_ ( snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : Any = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(snake_case_ ): cached_path(snake_case_ ) # relative path UpperCamelCase : Any = """./__missing_file__.txt""" with pytest.raises(snake_case_ ): cached_path(snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : str = get_from_cache(f'tmp://{tmpfs_file}' ) with open(snake_case_ ) as f: UpperCamelCase : Any = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" ,snake_case_ ) def A_ ( ): '''simple docstring''' with pytest.raises(snake_case_ ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" ,snake_case_ ) def A_ ( snake_case_ : Any ): '''simple docstring''' UpperCamelCase : Any = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(snake_case_ ): http_get("""https://huggingface.co""" ,temp_file=snake_case_ ) with pytest.raises(snake_case_ ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" ,snake_case_ ) def A_ ( snake_case_ : Union[str, Any] ): '''simple docstring''' UpperCamelCase : List[Any] = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(snake_case_ ): ftp_get("""ftp://huggingface.co""" ,temp_file=snake_case_ ) with pytest.raises(snake_case_ ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" ,snake_case_ ) def A_ ( snake_case_ : Any ): '''simple docstring''' UpperCamelCase : Any = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(snake_case_ ): fsspec_get("""s3://huggingface.co""" ,temp_file=snake_case_ ) with pytest.raises(snake_case_ ): fsspec_head("""s3://huggingface.co""" )
361
"""simple docstring""" import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : Optional[int] = { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json''', } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[int] = 'mvp' lowercase : Optional[Any] = ['past_key_values'] lowercase : Union[str, Any] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , SCREAMING_SNAKE_CASE_=5_0267 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=100 , SCREAMING_SNAKE_CASE_=800 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Dict = max_position_embeddings UpperCamelCase : Optional[int] = d_model UpperCamelCase : Optional[Any] = encoder_ffn_dim UpperCamelCase : Any = encoder_layers UpperCamelCase : List[Any] = encoder_attention_heads UpperCamelCase : Optional[Any] = decoder_ffn_dim UpperCamelCase : Optional[int] = decoder_layers UpperCamelCase : Dict = decoder_attention_heads UpperCamelCase : List[str] = dropout UpperCamelCase : List[str] = attention_dropout UpperCamelCase : List[Any] = activation_dropout UpperCamelCase : Dict = activation_function UpperCamelCase : List[str] = init_std UpperCamelCase : int = encoder_layerdrop UpperCamelCase : Dict = decoder_layerdrop UpperCamelCase : Any = classifier_dropout UpperCamelCase : Tuple = use_cache UpperCamelCase : Dict = encoder_layers UpperCamelCase : Tuple = scale_embedding # scale factor will be sqrt(d_model) if True UpperCamelCase : Optional[Any] = use_prompt UpperCamelCase : Any = prompt_length UpperCamelCase : List[Any] = prompt_mid_dim super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , forced_eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated""" , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = self.bos_token_id warnings.warn( f'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ' """The config can simply be saved and uploaded again to be fixed.""" )
27
0
"""simple docstring""" import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 __A : Union[str, Any] = { '''return_dict''': False, '''output_hidden_states''': True, '''output_attentions''': True, '''torchscript''': True, '''torch_dtype''': '''float16''', '''use_bfloat16''': True, '''tf_legacy_loss''': True, '''pruned_heads''': {'''a''': 1}, '''tie_word_embeddings''': False, '''is_decoder''': True, '''cross_attention_hidden_size''': 128, '''add_cross_attention''': True, '''tie_encoder_decoder''': True, '''max_length''': 50, '''min_length''': 3, '''do_sample''': True, '''early_stopping''': True, '''num_beams''': 3, '''num_beam_groups''': 3, '''diversity_penalty''': 0.5, '''temperature''': 2.0, '''top_k''': 10, '''top_p''': 0.7, '''typical_p''': 0.2, '''repetition_penalty''': 0.8, '''length_penalty''': 0.8, '''no_repeat_ngram_size''': 5, '''encoder_no_repeat_ngram_size''': 5, '''bad_words_ids''': [1, 2, 3], '''num_return_sequences''': 3, '''chunk_size_feed_forward''': 5, '''output_scores''': True, '''return_dict_in_generate''': True, '''forced_bos_token_id''': 2, '''forced_eos_token_id''': 3, '''remove_invalid_values''': True, '''architectures''': ['''BertModel'''], '''finetuning_task''': '''translation''', '''id2label''': {0: '''label'''}, '''label2id''': {'''label''': '''0'''}, '''tokenizer_class''': '''BertTokenizerFast''', '''prefix''': '''prefix''', '''bos_token_id''': 6, '''pad_token_id''': 7, '''eos_token_id''': 8, '''sep_token_id''': 9, '''decoder_start_token_id''': 10, '''exponential_decay_length_penalty''': (5, 1.01), '''suppress_tokens''': [0, 1], '''begin_suppress_tokens''': 2, '''task_specific_params''': {'''translation''': '''some_params'''}, '''problem_type''': '''regression''', } @is_staging_test class lowerCamelCase ( unittest.TestCase ): @classmethod def a_ ( cls ): UpperCamelCase : List[Any] = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE_ ) @classmethod def a_ ( cls ): try: delete_repo(token=cls._token , repo_id="""test-config""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-config-org""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""test-dynamic-config""" ) except HTTPError: pass def a_ ( self ): UpperCamelCase : Any = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("""test-config""" , use_auth_token=self._token ) UpperCamelCase : str = BertConfig.from_pretrained(f'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id="""test-config""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE_ , repo_id="""test-config""" , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) UpperCamelCase : Optional[int] = BertConfig.from_pretrained(f'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self ): UpperCamelCase : int = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("""valid_org/test-config-org""" , use_auth_token=self._token ) UpperCamelCase : Optional[int] = BertConfig.from_pretrained("""valid_org/test-config-org""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id="""valid_org/test-config-org""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id="""valid_org/test-config-org""" , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) UpperCamelCase : Union[str, Any] = BertConfig.from_pretrained("""valid_org/test-config-org""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self ): CustomConfig.register_for_auto_class() UpperCamelCase : Any = CustomConfig(attribute=42 ) config.push_to_hub("""test-dynamic-config""" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {"""AutoConfig""": """custom_configuration.CustomConfig"""} ) UpperCamelCase : Dict = AutoConfig.from_pretrained(f'{USER}/test-dynamic-config' , trust_remote_code=SCREAMING_SNAKE_CASE_ ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , """CustomConfig""" ) self.assertEqual(new_config.attribute , 42 ) class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): UpperCamelCase : str = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated UpperCamelCase : Dict = c.n_embd + 1 # int UpperCamelCase : Dict = c.resid_pdrop + 1.0 # float UpperCamelCase : Union[str, Any] = not c.scale_attn_weights # bool UpperCamelCase : Tuple = c.summary_type + """foo""" # str c.update_from_string( f'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' ) self.assertEqual(SCREAMING_SNAKE_CASE_ , c.n_embd , """mismatch for key: n_embd""" ) self.assertEqual(SCREAMING_SNAKE_CASE_ , c.resid_pdrop , """mismatch for key: resid_pdrop""" ) self.assertEqual(SCREAMING_SNAKE_CASE_ , c.scale_attn_weights , """mismatch for key: scale_attn_weights""" ) self.assertEqual(SCREAMING_SNAKE_CASE_ , c.summary_type , """mismatch for key: summary_type""" ) def a_ ( self ): UpperCamelCase : Union[str, Any] = PretrainedConfig() UpperCamelCase : int = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( SCREAMING_SNAKE_CASE_ , ["""is_encoder_decoder""", """_name_or_path""", """_commit_hash""", """transformers_version"""] ) UpperCamelCase : Tuple = [key for key, value in config_common_kwargs.items() if value == getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )] if len(SCREAMING_SNAKE_CASE_ ) > 0: raise ValueError( """The following keys are set with the default values in""" """ `test_configuration_common.config_common_kwargs` pick another value for them:""" f' {", ".join(SCREAMING_SNAKE_CASE_ )}.' ) def a_ ( self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): # config is in subfolder, the following should not work without specifying the subfolder UpperCamelCase : List[Any] = BertConfig.from_pretrained("""hf-internal-testing/tiny-random-bert-subfolder""" ) UpperCamelCase : Dict = BertConfig.from_pretrained("""hf-internal-testing/tiny-random-bert-subfolder""" , subfolder="""bert""" ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def a_ ( self ): # A mock response for an HTTP head request to emulate server down UpperCamelCase : str = mock.Mock() UpperCamelCase : Union[str, Any] = 500 UpperCamelCase : Optional[int] = {} UpperCamelCase : List[Any] = HTTPError UpperCamelCase : Union[str, Any] = {} # Download this model to make sure it's in the cache. UpperCamelCase : Optional[Any] = BertConfig.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("""requests.Session.request""" , return_value=SCREAMING_SNAKE_CASE_ ) as mock_head: UpperCamelCase : Tuple = BertConfig.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) # This check we did call the fake head request mock_head.assert_called() def a_ ( self ): # This test is for deprecated behavior and can be removed in v5 UpperCamelCase : int = BertConfig.from_pretrained( """https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json""" ) def a_ ( self ): UpperCamelCase : Union[str, Any] = AutoConfig.from_pretrained("""bert-base-cased""" ) UpperCamelCase : Optional[Any] = ["""config.4.0.0.json"""] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = 2 json.dump(configuration.to_dict() , open(os.path.join(SCREAMING_SNAKE_CASE_ , """config.4.0.0.json""" ) , """w""" ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 UpperCamelCase : Union[str, Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 UpperCamelCase : List[Any] = ["""config.42.0.0.json"""] UpperCamelCase : Optional[int] = 768 configuration.save_pretrained(SCREAMING_SNAKE_CASE_ ) shutil.move(os.path.join(SCREAMING_SNAKE_CASE_ , """config.4.0.0.json""" ) , os.path.join(SCREAMING_SNAKE_CASE_ , """config.42.0.0.json""" ) ) UpperCamelCase : List[str] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertEqual(new_configuration.hidden_size , 768 ) def a_ ( self ): # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. UpperCamelCase : List[Any] = """hf-internal-testing/test-two-configs""" import transformers as new_transformers UpperCamelCase : Optional[Any] = """v4.0.0""" UpperCamelCase : Union[str, Any] = new_transformers.models.auto.AutoConfig.from_pretrained( SCREAMING_SNAKE_CASE_ , return_unused_kwargs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(SCREAMING_SNAKE_CASE_ , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers UpperCamelCase : Dict = """v3.0.0""" UpperCamelCase : int = old_transformers.models.auto.AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertEqual(old_configuration.hidden_size , 768 )
362
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __A : Optional[Any] = 16 __A : str = 32 def A_ ( snake_case_ : Accelerator ,snake_case_ : int = 1_6 ): '''simple docstring''' UpperCamelCase : Tuple = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCamelCase : Optional[int] = load_dataset("""glue""" ,"""mrpc""" ) def tokenize_function(snake_case_ : List[Any] ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase : Union[str, Any] = tokenizer(examples["""sentence1"""] ,examples["""sentence2"""] ,truncation=snake_case_ ,max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase : Optional[Any] = datasets.map( snake_case_ ,batched=snake_case_ ,remove_columns=["""idx""", """sentence1""", """sentence2"""] ,) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase : str = tokenized_datasets.rename_column("""label""" ,"""labels""" ) def collate_fn(snake_case_ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase : Optional[Any] = 1_6 elif accelerator.mixed_precision != "no": UpperCamelCase : Any = 8 else: UpperCamelCase : Optional[Any] = None return tokenizer.pad( snake_case_ ,padding="""longest""" ,max_length=snake_case_ ,pad_to_multiple_of=snake_case_ ,return_tensors="""pt""" ,) # Instantiate dataloaders. UpperCamelCase : str = DataLoader( tokenized_datasets["""train"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) UpperCamelCase : Dict = DataLoader( tokenized_datasets["""validation"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders __A : int = mocked_dataloaders # noqa: F811 def A_ ( snake_case_ : Tuple ,snake_case_ : Dict ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" ,snake_case_ ) == "1": UpperCamelCase : Union[str, Any] = 2 # New Code # UpperCamelCase : Dict = int(args.gradient_accumulation_steps ) UpperCamelCase : List[Any] = int(args.local_sgd_steps ) # Initialize accelerator UpperCamelCase : str = Accelerator( cpu=args.cpu ,mixed_precision=args.mixed_precision ,gradient_accumulation_steps=snake_case_ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase : Union[str, Any] = config["""lr"""] UpperCamelCase : int = int(config["""num_epochs"""] ) UpperCamelCase : int = int(config["""seed"""] ) UpperCamelCase : List[Any] = int(config["""batch_size"""] ) UpperCamelCase : Optional[int] = evaluate.load("""glue""" ,"""mrpc""" ) set_seed(snake_case_ ) UpperCamelCase , UpperCamelCase : Dict = get_dataloaders(snake_case_ ,snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase : Optional[int] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" ,return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase : Tuple = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase : List[Any] = AdamW(params=model.parameters() ,lr=snake_case_ ) # Instantiate scheduler UpperCamelCase : str = get_linear_schedule_with_warmup( optimizer=snake_case_ ,num_warmup_steps=1_0_0 ,num_training_steps=(len(snake_case_ ) * num_epochs) ,) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Any = accelerator.prepare( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() with LocalSGD( accelerator=snake_case_ ,model=snake_case_ ,local_sgd_steps=snake_case_ ,enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(snake_case_ ): UpperCamelCase : Optional[Any] = model(**snake_case_ ) UpperCamelCase : Optional[int] = output.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase : Any = model(**snake_case_ ) UpperCamelCase : Tuple = outputs.logits.argmax(dim=-1 ) UpperCamelCase , UpperCamelCase : int = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case_ ,references=snake_case_ ,) UpperCamelCase : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' ,snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" ,type=snake_case_ ,default=snake_case_ ,choices=["""no""", """fp16""", """bf16""", """fp8"""] ,help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" ,) # New Code # parser.add_argument( """--gradient_accumulation_steps""" ,type=snake_case_ ,default=1 ,help="""The number of minibatches to be ran before gradients are accumulated.""" ,) parser.add_argument( """--local_sgd_steps""" ,type=snake_case_ ,default=8 ,help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" ,action="""store_true""" ,help="""If passed, will train on the CPU.""" ) UpperCamelCase : Dict = parser.parse_args() UpperCamelCase : List[Any] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(snake_case_ ,snake_case_ ) if __name__ == "__main__": main()
27
0
"""simple docstring""" from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class lowerCamelCase : lowercase : int lowercase : int class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : list[list[Edge]] = [[] for _ in range(SCREAMING_SNAKE_CASE_ )] UpperCamelCase : str = size def __getitem__( self , SCREAMING_SNAKE_CASE_ ): return iter(self._graph[vertex] ) @property def a_ ( self ): return self._size def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if weight not in (0, 1): raise ValueError("""Edge weight must be either 0 or 1.""" ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("""Vertex indexes must be in [0; size).""" ) self._graph[from_vertex].append(Edge(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = deque([start_vertex] ) UpperCamelCase : list[int | None] = [None] * self.size UpperCamelCase : str = 0 while queue: UpperCamelCase : str = queue.popleft() UpperCamelCase : Optional[Any] = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: UpperCamelCase : Dict = current_distance + edge.weight UpperCamelCase : Dict = distances[edge.destination_vertex] if ( isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and new_distance >= dest_vertex_distance ): continue UpperCamelCase : int = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("""No path from start_vertex to finish_vertex.""" ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
363
"""simple docstring""" from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer __A : Any = logging.get_logger(__name__) __A : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A : Optional[Any] = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } __A : Any = {'''allegro/herbert-base-cased''': 514} __A : Optional[Any] = {} class lowerCamelCase ( _UpperCAmelCase ): lowercase : Dict = VOCAB_FILES_NAMES lowercase : Any = PRETRAINED_VOCAB_FILES_MAP lowercase : List[str] = PRETRAINED_INIT_CONFIGURATION lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Union[str, Any] = HerbertTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_="</s>" , **SCREAMING_SNAKE_CASE_ , ): super().__init__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = [self.cls_token_id] UpperCamelCase : str = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Tuple = [self.sep_token_id] UpperCamelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Optional[int] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
27
0
"""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 __A : Optional[int] = Mapping[str, np.ndarray] __A : Optional[Any] = Mapping[str, Any] # Is a nested dict. __A : List[Any] = 0.01 @dataclasses.dataclass(frozen=_UpperCAmelCase ) class lowerCamelCase : lowercase : np.ndarray # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. lowercase : np.ndarray # [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. lowercase : np.ndarray # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. lowercase : np.ndarray # [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. lowercase : np.ndarray # [num_res, num_atom_type] # Chain indices for multi-chain predictions lowercase : Optional[np.ndarray] = None # Optional remark about the protein. Included as a comment in output PDB # files lowercase : Optional[str] = None # Templates used to generate this protein (prediction-only) lowercase : Optional[Sequence[str]] = None # Chain corresponding to each parent lowercase : Optional[Sequence[int]] = None def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Optional[Any] = R"""(\[[A-Z]+\]\n)""" UpperCamelCase : List[str] = [tag.strip() for tag in re.split(snake_case_ ,snake_case_ ) if len(snake_case_ ) > 0] UpperCamelCase : Iterator[Tuple[str, List[str]]] = zip(tags[0::2] ,[l.split("""\n""" ) for l in tags[1::2]] ) UpperCamelCase : List[str] = ["N", "CA", "C"] UpperCamelCase : List[str] = None UpperCamelCase : Optional[int] = None UpperCamelCase : Any = None for g in groups: if "[PRIMARY]" == g[0]: UpperCamelCase : str = g[1][0].strip() for i in range(len(snake_case_ ) ): if seq[i] not in residue_constants.restypes: UpperCamelCase : Dict = """X""" # FIXME: strings are immutable UpperCamelCase : str = np.array( [residue_constants.restype_order.get(snake_case_ ,residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: UpperCamelCase : List[List[float]] = [] for axis in range(3 ): tertiary.append(list(map(snake_case_ ,g[1][axis].split() ) ) ) UpperCamelCase : Dict = np.array(snake_case_ ) UpperCamelCase : Tuple = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(snake_case_ ): UpperCamelCase : str = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: UpperCamelCase : Any = np.array(list(map({"""-""": 0, """+""": 1}.get ,g[1][0].strip() ) ) ) UpperCamelCase : Tuple = np.zeros( ( len(snake_case_ ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(snake_case_ ): UpperCamelCase : List[Any] = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=snake_case_ ,atom_mask=snake_case_ ,aatype=snake_case_ ,residue_index=np.arange(len(snake_case_ ) ) ,b_factors=snake_case_ ,) def A_ ( snake_case_ : Protein ,snake_case_ : int = 0 ): '''simple docstring''' UpperCamelCase : List[str] = [] UpperCamelCase : Dict = prot.remark if remark is not None: pdb_headers.append(f'REMARK {remark}' ) UpperCamelCase : Optional[int] = prot.parents UpperCamelCase : List[Any] = prot.parents_chain_index if parents is not None and parents_chain_index is not None: UpperCamelCase : List[Any] = [p for i, p in zip(snake_case_ ,snake_case_ ) if i == chain_id] if parents is None or len(snake_case_ ) == 0: UpperCamelCase : Any = ["""N/A"""] pdb_headers.append(f'PARENT {" ".join(snake_case_ )}' ) return pdb_headers def A_ ( snake_case_ : Protein ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : List[str] = [] UpperCamelCase : Dict = pdb_str.split("""\n""" ) UpperCamelCase : Optional[int] = prot.remark if remark is not None: out_pdb_lines.append(f'REMARK {remark}' ) UpperCamelCase : List[List[str]] if prot.parents is not None and len(prot.parents ) > 0: UpperCamelCase : Optional[int] = [] if prot.parents_chain_index is not None: UpperCamelCase : Dict[str, List[str]] = {} for p, i in zip(prot.parents ,prot.parents_chain_index ): parent_dict.setdefault(str(snake_case_ ) ,[] ) parent_dict[str(snake_case_ )].append(snake_case_ ) UpperCamelCase : str = max([int(snake_case_ ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): UpperCamelCase : Optional[int] = parent_dict.get(str(snake_case_ ) ,["""N/A"""] ) parents_per_chain.append(snake_case_ ) else: parents_per_chain.append(list(prot.parents ) ) else: UpperCamelCase : List[str] = [["""N/A"""]] def make_parent_line(snake_case_ : Sequence[str] ) -> str: return f'PARENT {" ".join(snake_case_ )}' out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) UpperCamelCase : Any = 0 for i, l in enumerate(snake_case_ ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(snake_case_ ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(snake_case_ ): UpperCamelCase : str = parents_per_chain[chain_counter] else: UpperCamelCase : Tuple = ["""N/A"""] out_pdb_lines.append(make_parent_line(snake_case_ ) ) return "\n".join(snake_case_ ) def A_ ( snake_case_ : Protein ): '''simple docstring''' UpperCamelCase : Dict = residue_constants.restypes + ["""X"""] def res_atoa(snake_case_ : int ) -> str: return residue_constants.restype_atoa.get(restypes[r] ,"""UNK""" ) UpperCamelCase : Dict = residue_constants.atom_types UpperCamelCase : List[str] = [] UpperCamelCase : int = prot.atom_mask UpperCamelCase : str = prot.aatype UpperCamelCase : Tuple = prot.atom_positions UpperCamelCase : List[str] = prot.residue_index.astype(np.intaa ) UpperCamelCase : int = prot.b_factors UpperCamelCase : Union[str, Any] = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError("""Invalid aatypes.""" ) UpperCamelCase : int = get_pdb_headers(snake_case_ ) if len(snake_case_ ) > 0: pdb_lines.extend(snake_case_ ) UpperCamelCase : Dict = aatype.shape[0] UpperCamelCase : int = 1 UpperCamelCase : Optional[int] = 0 UpperCamelCase : Union[str, Any] = string.ascii_uppercase UpperCamelCase : List[Any] = None # Add all atom sites. for i in range(snake_case_ ): UpperCamelCase : Any = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(snake_case_ ,atom_positions[i] ,atom_mask[i] ,b_factors[i] ): if mask < 0.5: continue UpperCamelCase : Any = """ATOM""" UpperCamelCase : Union[str, Any] = atom_name if len(snake_case_ ) == 4 else f' {atom_name}' UpperCamelCase : int = """""" UpperCamelCase : Optional[int] = """""" UpperCamelCase : int = 1.00 UpperCamelCase : List[str] = atom_name[0] # Protein supports only C, N, O, S, this works. UpperCamelCase : Optional[int] = """""" UpperCamelCase : List[Any] = """A""" if chain_index is not None: UpperCamelCase : str = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! UpperCamelCase : List[str] = ( 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(snake_case_ ) atom_index += 1 UpperCamelCase : List[str] = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: UpperCamelCase : int = True UpperCamelCase : Dict = chain_index[i + 1] if should_terminate: # Close the chain. UpperCamelCase : Optional[Any] = """TER""" UpperCamelCase : Union[str, Any] = ( f'{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}' ) pdb_lines.append(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(snake_case_ ,snake_case_ ) ) pdb_lines.append("""END""" ) pdb_lines.append("""""" ) return "\n".join(snake_case_ ) def A_ ( snake_case_ : Protein ): '''simple docstring''' return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def A_ ( snake_case_ : FeatureDict ,snake_case_ : ModelOutput ,snake_case_ : Optional[np.ndarray] = None ,snake_case_ : Optional[np.ndarray] = None ,snake_case_ : Optional[str] = None ,snake_case_ : Optional[Sequence[str]] = None ,snake_case_ : Optional[Sequence[int]] = None ,): '''simple docstring''' 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=snake_case_ ,remark=snake_case_ ,parents=snake_case_ ,parents_chain_index=snake_case_ ,)
364
"""simple docstring""" import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=3.6 ): UpperCamelCase : Dict = tokenizer UpperCamelCase : Optional[Any] = tokenizer.bos_token_id UpperCamelCase : Any = dataset UpperCamelCase : List[str] = seq_length UpperCamelCase : Optional[Any] = seq_length * chars_per_token * num_of_sequences def __iter__( self ): UpperCamelCase : Dict = iter(self.dataset ) UpperCamelCase : Union[str, Any] = True while more_examples: UpperCamelCase , UpperCamelCase : Tuple = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(SCREAMING_SNAKE_CASE_ )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: UpperCamelCase : Dict = False break UpperCamelCase : str = tokenizer(SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )["""input_ids"""] UpperCamelCase : str = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , self.seq_length ): UpperCamelCase : List[str] = all_token_ids[i : i + self.seq_length] if len(SCREAMING_SNAKE_CASE_ ) == self.seq_length: yield torch.tensor(SCREAMING_SNAKE_CASE_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Dict = {"""streaming""": True} UpperCamelCase : Optional[int] = load_dataset(args.dataset_name ,split="""train""" ,**snake_case_ ) UpperCamelCase : Optional[int] = ConstantLengthDataset(snake_case_ ,snake_case_ ,seq_length=args.seq_length ) UpperCamelCase : List[Any] = DataLoader(snake_case_ ,batch_size=args.batch_size ) return eval_dataloader def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' model.eval() UpperCamelCase : Dict = [] for step, batch in enumerate(snake_case_ ): with torch.no_grad(): UpperCamelCase : List[Any] = model(snake_case_ ,labels=snake_case_ ) UpperCamelCase : Any = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(snake_case_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break UpperCamelCase : Dict = torch.mean(torch.cat(snake_case_ ) ) try: UpperCamelCase : Dict = torch.exp(snake_case_ ) except OverflowError: UpperCamelCase : Optional[int] = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator __A : List[Any] = Accelerator() # Parse configuration __A : str = HfArgumentParser(EvaluationArguments) __A : List[Any] = parser.parse_args() set_seed(args.seed) # Logging __A : Any = logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer __A : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) __A : List[Any] = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader __A : int = create_dataloader(args) # Prepare everything with our `accelerator`. __A , __A : Optional[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') __A , __A : Tuple = evaluate(args) logger.info(F'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
27
0
import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Tuple = BertTokenizer lowercase : int = BertTokenizerFast lowercase : Any = True lowercase : List[str] = True lowercase : List[Any] = filter_non_english def a_ ( self ): super().setUp() UpperCamelCase : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] UpperCamelCase : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = """UNwant\u00E9d,running""" UpperCamelCase : Tuple = """unwanted, running""" return input_text, output_text def a_ ( self ): UpperCamelCase : List[Any] = self.tokenizer_class(self.vocab_file ) UpperCamelCase : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [9, 6, 7, 12, 10, 11] ) def a_ ( self ): if not self.test_rust_tokenizer: return UpperCamelCase : Any = self.get_tokenizer() UpperCamelCase : Dict = self.get_rust_tokenizer() UpperCamelCase : List[str] = """UNwant\u00E9d,running""" UpperCamelCase : Union[str, Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.get_rust_tokenizer() UpperCamelCase : Tuple = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # With lower casing UpperCamelCase : List[str] = self.get_tokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.get_rust_tokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = """UNwant\u00E9d,running""" UpperCamelCase : List[str] = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = self.get_rust_tokenizer() UpperCamelCase : Any = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def a_ ( self ): UpperCamelCase : Any = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def a_ ( self ): UpperCamelCase : Any = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def a_ ( self ): UpperCamelCase : Optional[Any] = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def a_ ( self ): UpperCamelCase : Union[str, Any] = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def a_ ( self ): UpperCamelCase : Tuple = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def a_ ( self ): UpperCamelCase : Any = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def a_ ( self ): UpperCamelCase : Any = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def a_ ( self ): UpperCamelCase : List[Any] = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def a_ ( self ): UpperCamelCase : Any = BasicTokenizer() UpperCamelCase : Any = """a\n'll !!to?'d of, can't.""" UpperCamelCase : Dict = ["""a""", """'""", """ll""", """!""", """!""", """to""", """?""", """'""", """d""", """of""", """,""", """can""", """'""", """t""", """."""] self.assertListEqual(tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] UpperCamelCase : int = {} for i, token in enumerate(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = i UpperCamelCase : Dict = WordpieceTokenizer(vocab=SCREAMING_SNAKE_CASE_ , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] ) def a_ ( self ): self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def a_ ( self ): self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def a_ ( self ): self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) def a_ ( self ): UpperCamelCase : str = self.get_tokenizer() UpperCamelCase : Dict = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) self.assertListEqual( [rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) @slow def a_ ( self ): UpperCamelCase : Union[str, Any] = self.tokenizer_class.from_pretrained("""bert-base-uncased""" ) UpperCamelCase : List[Any] = tokenizer.encode("""sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = tokenizer.encode("""multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def a_ ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): UpperCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = f'A, naïve {tokenizer_r.mask_token} AllenNLP sentence.' UpperCamelCase : Any = tokenizer_r.encode_plus( SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : List[Any] = tokenizer_r.do_lower_case if hasattr(SCREAMING_SNAKE_CASE_ , """do_lower_case""" ) else False UpperCamelCase : Dict = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """A"""), ((1, 2), ""","""), ((3, 5), """na"""), ((5, 6), """##ï"""), ((6, 8), """##ve"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """Allen"""), ((21, 23), """##NL"""), ((23, 24), """##P"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """a"""), ((1, 2), ""","""), ((3, 8), """naive"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """allen"""), ((21, 23), """##nl"""), ((23, 24), """##p"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["""input_ids"""] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["""offset_mapping"""] ) def a_ ( self ): UpperCamelCase : Union[str, Any] = ["""的""", """人""", """有"""] UpperCamelCase : Tuple = """""".join(SCREAMING_SNAKE_CASE_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): UpperCamelCase : List[Any] = True UpperCamelCase : Any = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = tokenizer_p.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tokenizer_r.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = False UpperCamelCase : str = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = tokenizer_r.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tokenizer_p.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) # it is expected that only the first Chinese character is not preceded by "##". UpperCamelCase : Tuple = [ f'##{token}' if idx != 0 else token for idx, token in enumerate(SCREAMING_SNAKE_CASE_ ) ] self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
365
"""simple docstring""" import argparse import os import re __A : Any = '''src/transformers''' # Pattern that looks at the indentation in a line. __A : Tuple = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : List[Any] = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : List[Any] = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : Any = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : str ,snake_case_ : str="" ,snake_case_ : Any=None ,snake_case_ : Union[str, Any]=None ): '''simple docstring''' UpperCamelCase : List[Any] = 0 UpperCamelCase : Optional[int] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Tuple = ["""\n""".join(lines[:index] )] else: UpperCamelCase : Tuple = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Dict = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Optional[Any] = [lines[index + 1]] index += 1 else: UpperCamelCase : str = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : List[Any] ): '''simple docstring''' def _inner(snake_case_ : List[str] ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Tuple=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Optional[int] ): return x if key is None: UpperCamelCase : List[str] = noop # Constants are all uppercase, they go first. UpperCamelCase : List[str] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : Tuple = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : int = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Union[str, Any] = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : Any ): UpperCamelCase : Union[str, Any] = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : int = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : str = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : Optional[int] = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : int = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Tuple = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : List[Any] = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Union[str, Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : List[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : Optional[int] = keys[:-1] UpperCamelCase : Union[str, Any] = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : Any = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : int=True ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : List[str] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : int = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Dict = main_blocks[block_idx] UpperCamelCase : Dict = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : List[str] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : Optional[Any] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Optional[Any] = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Any = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : List[Any] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Optional[Any] = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Optional[Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Any = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : Union[str, Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[str] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: UpperCamelCase : Optional[int] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Optional[int] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : List[Any] = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : Union[str, Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
0
"""simple docstring""" import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'naver-clova-ix/donut-base-finetuned-docvqa' lowercase : str = ( 'This is a tool that answers a question about an document (pdf). It takes an input named `document` which ' 'should be the document containing the information, as well as a `question` that is the question about the ' 'document. It returns a text that contains the answer to the question.' ) lowercase : Dict = 'document_qa' lowercase : Optional[int] = AutoProcessor lowercase : List[Any] = VisionEncoderDecoderModel lowercase : Any = ['image', 'text'] lowercase : Any = ['text'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): if not is_vision_available(): raise ValueError("""Pillow must be installed to use the DocumentQuestionAnsweringTool.""" ) super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" UpperCamelCase : int = task_prompt.replace("""{user_input}""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.pre_processor.tokenizer( SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).input_ids UpperCamelCase : List[Any] = self.pre_processor(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.model.generate( inputs["""pixel_values"""].to(self.device ) , decoder_input_ids=inputs["""decoder_input_ids"""].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=SCREAMING_SNAKE_CASE_ , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=SCREAMING_SNAKE_CASE_ , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=SCREAMING_SNAKE_CASE_ , ).sequences def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.pre_processor.batch_decode(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Dict = sequence.replace(self.pre_processor.tokenizer.eos_token , """""" ) UpperCamelCase : Union[str, Any] = sequence.replace(self.pre_processor.tokenizer.pad_token , """""" ) UpperCamelCase : int = re.sub(r"""<.*?>""" , """""" , SCREAMING_SNAKE_CASE_ , count=1 ).strip() # remove first task start token UpperCamelCase : Optional[Any] = self.pre_processor.tokenajson(SCREAMING_SNAKE_CASE_ ) return sequence["answer"]
366
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' if number < 0: raise ValueError("""number must not be negative""" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
27
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __A : Any = logging.get_logger(__name__) class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = True , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = size if size is not None else {"""height""": 384, """width""": 384} UpperCamelCase : Any = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = do_resize UpperCamelCase : Optional[int] = size UpperCamelCase : List[str] = resample UpperCamelCase : str = do_rescale UpperCamelCase : Any = rescale_factor UpperCamelCase : Tuple = do_normalize UpperCamelCase : List[str] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN UpperCamelCase : str = image_std if image_std is not None else OPENAI_CLIP_STD UpperCamelCase : Any = do_convert_rgb def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}' ) UpperCamelCase : Any = (size["""height"""], size["""width"""]) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Any = do_resize if do_resize is not None else self.do_resize UpperCamelCase : str = resample if resample is not None else self.resample UpperCamelCase : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase : int = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase : List[str] = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase : Any = image_mean if image_mean is not None else self.image_mean UpperCamelCase : Any = image_std if image_std is not None else self.image_std UpperCamelCase : Optional[Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase : Optional[int] = size if size is not None else self.size UpperCamelCase : Any = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = make_list_of_images(SCREAMING_SNAKE_CASE_ ) if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase : Optional[Any] = [convert_to_rgb(SCREAMING_SNAKE_CASE_ ) for image in images] # All transformations expect numpy arrays. UpperCamelCase : Any = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase : Optional[int] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase : str = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase : int = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Optional[Any] = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : List[str] = BatchFeature(data={"""pixel_values""": images} , tensor_type=SCREAMING_SNAKE_CASE_ ) return encoded_outputs
367
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL __A : Optional[Any] = logging.get_logger(__name__) def A_ ( snake_case_ : np.ndarray ,snake_case_ : Union[int, Iterable[int]] ,snake_case_ : bool ,snake_case_ : int ): '''simple docstring''' def constraint_to_multiple_of(snake_case_ : Optional[Any] ,snake_case_ : Optional[int] ,snake_case_ : List[str]=0 ,snake_case_ : Optional[Any]=None ): UpperCamelCase : List[str] = round(val / multiple ) * multiple if max_val is not None and x > max_val: UpperCamelCase : Optional[Any] = math.floor(val / multiple ) * multiple if x < min_val: UpperCamelCase : Dict = math.ceil(val / multiple ) * multiple return x UpperCamelCase : Any = (output_size, output_size) if isinstance(snake_case_ ,snake_case_ ) else output_size UpperCamelCase , UpperCamelCase : int = get_image_size(snake_case_ ) UpperCamelCase , UpperCamelCase : Union[str, Any] = output_size # determine new height and width UpperCamelCase : List[str] = output_height / input_height UpperCamelCase : List[str] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width UpperCamelCase : int = scale_width else: # fit height UpperCamelCase : Optional[Any] = scale_height UpperCamelCase : int = constraint_to_multiple_of(scale_height * input_height ,multiple=snake_case_ ) UpperCamelCase : Union[str, Any] = constraint_to_multiple_of(scale_width * input_width ,multiple=snake_case_ ) return (new_height, new_width) class lowerCamelCase ( _UpperCAmelCase ): lowercase : str = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = size if size is not None else {"""height""": 384, """width""": 384} UpperCamelCase : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = do_resize UpperCamelCase : Union[str, Any] = size UpperCamelCase : Union[str, Any] = keep_aspect_ratio UpperCamelCase : Any = ensure_multiple_of UpperCamelCase : List[Any] = resample UpperCamelCase : str = do_rescale UpperCamelCase : Optional[Any] = rescale_factor UpperCamelCase : List[str] = do_normalize UpperCamelCase : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCamelCase : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) UpperCamelCase : Dict = get_resize_output_image_size( SCREAMING_SNAKE_CASE_ , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=SCREAMING_SNAKE_CASE_ , multiple=SCREAMING_SNAKE_CASE_ , ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize UpperCamelCase : List[Any] = size if size is not None else self.size UpperCamelCase : Dict = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio UpperCamelCase : Optional[int] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of UpperCamelCase : Tuple = resample if resample is not None else self.resample UpperCamelCase : str = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase : Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase : Any = image_mean if image_mean is not None else self.image_mean UpperCamelCase : List[Any] = image_std if image_std is not None else self.image_std UpperCamelCase : str = make_list_of_images(SCREAMING_SNAKE_CASE_ ) if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. UpperCamelCase : Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase : Union[str, Any] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase : int = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase : List[str] = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Union[str, Any] = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : str = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = target_sizes.numpy() UpperCamelCase : Dict = [] for idx in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase : List[Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : List[Any] = logits.argmax(dim=1 ) UpperCamelCase : Dict = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
27
0
"""simple docstring""" import requests __A : List[Any] = '''''' # <-- Put your OpenWeatherMap appid here! __A : Tuple = '''https://api.openweathermap.org/data/2.5/''' def A_ ( snake_case_ : str = "Chicago" ,snake_case_ : str = APPID ): '''simple docstring''' return requests.get(URL_BASE + """weather""" ,params=locals() ).json() def A_ ( snake_case_ : str = "Kolkata, India" ,snake_case_ : str = APPID ): '''simple docstring''' return requests.get(URL_BASE + """forecast""" ,params=locals() ).json() def A_ ( snake_case_ : float = 55.68 ,snake_case_ : float = 12.57 ,snake_case_ : str = APPID ): '''simple docstring''' return requests.get(URL_BASE + """onecall""" ,params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: __A : Optional[int] = input('''Enter a location:''').strip() if location: pprint(current_weather(location)) else: break
368
"""simple docstring""" from collections.abc import Callable def A_ ( snake_case_ : Callable[[float], float] ,snake_case_ : float ,snake_case_ : float ): '''simple docstring''' UpperCamelCase : float = a UpperCamelCase : float = b if function(snake_case_ ) == 0: # one of the a or b is a root for the function return a elif function(snake_case_ ) == 0: return b elif ( function(snake_case_ ) * function(snake_case_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("""could not find root in given interval.""" ) else: UpperCamelCase : float = start + (end - start) / 2.0 while abs(start - mid ) > 1_0**-7: # until precisely equals to 10^-7 if function(snake_case_ ) == 0: return mid elif function(snake_case_ ) * function(snake_case_ ) < 0: UpperCamelCase : Dict = mid else: UpperCamelCase : List[str] = mid UpperCamelCase : Tuple = start + (end - start) / 2.0 return mid def A_ ( snake_case_ : float ): '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
27
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __A : Union[str, Any] = logging.get_logger(__name__) __A : int = { '''google/bit-50''': '''https://huggingface.co/google/bit-50/resolve/main/config.json''', } class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase ): lowercase : Optional[int] = 'bit' lowercase : Any = ['preactivation', 'bottleneck'] lowercase : Any = ['SAME', 'VALID'] def __init__( self , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=[256, 512, 1024, 2048] , SCREAMING_SNAKE_CASE_=[3, 4, 6, 3] , SCREAMING_SNAKE_CASE_="preactivation" , SCREAMING_SNAKE_CASE_="relu" , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) if layer_type not in self.layer_types: raise ValueError(f'layer_type={layer_type} is not one of {",".join(self.layer_types )}' ) if global_padding is not None: if global_padding.upper() in self.supported_padding: UpperCamelCase : str = global_padding.upper() else: raise ValueError(f'Padding strategy {global_padding} not supported' ) UpperCamelCase : Optional[int] = num_channels UpperCamelCase : str = embedding_size UpperCamelCase : List[Any] = hidden_sizes UpperCamelCase : Any = depths UpperCamelCase : Optional[int] = layer_type UpperCamelCase : List[str] = hidden_act UpperCamelCase : Any = global_padding UpperCamelCase : Dict = num_groups UpperCamelCase : Optional[int] = drop_path_rate UpperCamelCase : Dict = embedding_dynamic_padding UpperCamelCase : str = output_stride UpperCamelCase : str = width_factor UpperCamelCase : int = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(SCREAMING_SNAKE_CASE_ ) + 1 )] UpperCamelCase : List[str] = get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE_ , out_indices=SCREAMING_SNAKE_CASE_ , stage_names=self.stage_names )
369
"""simple docstring""" import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def a_ ( self ): UpperCamelCase : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) UpperCamelCase : int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) UpperCamelCase : Dict = """xvjiarui/stable-diffusion-2-inpainting""" UpperCamelCase , UpperCamelCase : List[str] = FlaxStableDiffusionInpaintPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = """Face of a yellow cat, high resolution, sitting on a park bench""" UpperCamelCase : List[str] = jax.random.PRNGKey(0 ) UpperCamelCase : Tuple = 50 UpperCamelCase : Dict = jax.device_count() UpperCamelCase : Optional[int] = num_samples * [prompt] UpperCamelCase : int = num_samples * [init_image] UpperCamelCase : List[Any] = num_samples * [mask_image] UpperCamelCase , UpperCamelCase , UpperCamelCase : Optional[Any] = pipeline.prepare_inputs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # shard inputs and rng UpperCamelCase : Optional[int] = replicate(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = jax.random.split(SCREAMING_SNAKE_CASE_ , jax.device_count() ) UpperCamelCase : str = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = pipeline( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , jit=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = output.images.reshape(SCREAMING_SNAKE_CASE_ , 512 , 512 , 3 ) UpperCamelCase : List[Any] = images[0, 253:256, 253:256, -1] UpperCamelCase : List[Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) UpperCamelCase : Dict = jnp.array( [0.3611307, 0.37649736, 0.3757408, 0.38213953, 0.39295167, 0.3841631, 0.41554978, 0.4137475, 0.4217084] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
27
0
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=32 * 8 , SCREAMING_SNAKE_CASE_=32 * 8 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=64 , ): UpperCamelCase : Union[str, Any] = parent UpperCamelCase : str = batch_size UpperCamelCase : str = is_training UpperCamelCase : List[str] = use_auxiliary_loss UpperCamelCase : List[str] = num_queries UpperCamelCase : str = num_channels UpperCamelCase : Optional[Any] = min_size UpperCamelCase : Optional[int] = max_size UpperCamelCase : Any = num_labels UpperCamelCase : Optional[int] = hidden_dim UpperCamelCase : str = hidden_dim def a_ ( self ): UpperCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE_ ) > 0.5 ).float() UpperCamelCase : Optional[Any] = (torch.rand((self.batch_size, self.num_labels) , device=SCREAMING_SNAKE_CASE_ ) > 0.5).long() UpperCamelCase : Union[str, Any] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def a_ ( self ): UpperCamelCase : str = MaskaFormerConfig( hidden_size=self.hidden_dim , ) UpperCamelCase : int = self.num_queries UpperCamelCase : int = self.num_labels UpperCamelCase : Union[str, Any] = [1, 1, 1, 1] UpperCamelCase : Any = self.num_channels UpperCamelCase : Union[str, Any] = 64 UpperCamelCase : Optional[int] = 128 UpperCamelCase : Optional[Any] = self.hidden_dim UpperCamelCase : List[str] = self.hidden_dim UpperCamelCase : Any = self.hidden_dim return config def a_ ( self ): UpperCamelCase : List[Any] = self.prepare_config_and_inputs() UpperCamelCase : Optional[Any] = {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask} return config, inputs_dict def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = output.encoder_hidden_states UpperCamelCase : List[str] = output.pixel_decoder_hidden_states UpperCamelCase : Dict = output.transformer_decoder_hidden_states self.parent.assertTrue(len(SCREAMING_SNAKE_CASE_ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE_ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE_ ) , config.decoder_layers ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): with torch.no_grad(): UpperCamelCase : Dict = MaskaFormerModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : str = model(pixel_values=SCREAMING_SNAKE_CASE_ , pixel_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = MaskaFormerForUniversalSegmentation(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() def comm_check_on_output(SCREAMING_SNAKE_CASE_ ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): UpperCamelCase : Optional[Any] = model(pixel_values=SCREAMING_SNAKE_CASE_ , pixel_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ ) comm_check_on_output(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model( pixel_values=SCREAMING_SNAKE_CASE_ , pixel_mask=SCREAMING_SNAKE_CASE_ , mask_labels=SCREAMING_SNAKE_CASE_ , class_labels=SCREAMING_SNAKE_CASE_ ) comm_check_on_output(SCREAMING_SNAKE_CASE_ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : int = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () lowercase : List[Any] = {'feature-extraction': MaskaFormerModel} if is_torch_available() else {} lowercase : List[Any] = False lowercase : Any = False lowercase : int = False lowercase : Any = False def a_ ( self ): UpperCamelCase : Dict = MaskaFormerModelTester(self ) UpperCamelCase : List[str] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*SCREAMING_SNAKE_CASE_ ) @unittest.skip(reason="""Mask2Former does not use inputs_embeds""" ) def a_ ( self ): pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""" ) def a_ ( self ): pass @unittest.skip(reason="""Mask2Former is not a generative model""" ) def a_ ( self ): pass @unittest.skip(reason="""Mask2Former does not use token embeddings""" ) def a_ ( self ): pass @require_torch_multi_gpu @unittest.skip( reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" ) def a_ ( self ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def a_ ( self ): pass def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : int = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase : int = [*signature.parameters.keys()] UpperCamelCase : List[Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in ["facebook/mask2former-swin-small-coco-instance"]: UpperCamelCase : str = MaskaFormerModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = (self.model_tester.min_size,) * 2 UpperCamelCase : Any = { """pixel_values""": torch.randn((2, 3, *size) , device=SCREAMING_SNAKE_CASE_ ), """mask_labels""": torch.randn((2, 10, *size) , device=SCREAMING_SNAKE_CASE_ ), """class_labels""": torch.zeros(2 , 10 , device=SCREAMING_SNAKE_CASE_ ).long(), } UpperCamelCase : Optional[Any] = self.model_tester.get_config() UpperCamelCase : List[str] = MaskaFormerForUniversalSegmentation(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(**SCREAMING_SNAKE_CASE_ ) self.assertTrue(outputs.loss is not None ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : List[str] = model_class(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = model(**SCREAMING_SNAKE_CASE_ , output_attentions=SCREAMING_SNAKE_CASE_ ) self.assertTrue(outputs.attentions is not None ) def a_ ( self ): if not self.model_tester.is_training: return UpperCamelCase : int = self.all_model_classes[1] UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() UpperCamelCase : Optional[int] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase : str = model(SCREAMING_SNAKE_CASE_ , mask_labels=SCREAMING_SNAKE_CASE_ , class_labels=SCREAMING_SNAKE_CASE_ ).loss loss.backward() def a_ ( self ): UpperCamelCase : Tuple = self.all_model_classes[1] UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() UpperCamelCase : Optional[int] = True UpperCamelCase : int = True UpperCamelCase : Any = model_class(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , mask_labels=SCREAMING_SNAKE_CASE_ , class_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() UpperCamelCase : List[str] = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() UpperCamelCase : List[str] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() UpperCamelCase : Dict = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) __A : List[str] = 1e-4 def A_ ( ): '''simple docstring''' UpperCamelCase : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class lowerCamelCase ( unittest.TestCase ): @cached_property def a_ ( self ): return "facebook/mask2former-swin-small-coco-instance" @cached_property def a_ ( self ): return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def a_ ( self ): UpperCamelCase : Optional[int] = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.default_image_processor UpperCamelCase : str = prepare_img() UpperCamelCase : Tuple = image_processor(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(SCREAMING_SNAKE_CASE_ , (1, 3, 384, 384) ) with torch.no_grad(): UpperCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = torch.tensor( [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Union[str, Any] = torch.tensor( [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : List[Any] = torch.tensor( [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) def a_ ( self ): UpperCamelCase : Union[str, Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase : List[str] = self.default_image_processor UpperCamelCase : List[Any] = prepare_img() UpperCamelCase : List[str] = image_processor(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(SCREAMING_SNAKE_CASE_ , (1, 3, 384, 384) ) with torch.no_grad(): UpperCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE_ ) # masks_queries_logits UpperCamelCase : str = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) UpperCamelCase : Dict = [ [-8.7839, -9.0056, -8.8121], [-7.4104, -7.0313, -6.5401], [-6.6105, -6.3427, -6.4675], ] UpperCamelCase : Dict = torch.tensor(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) # class_queries_logits UpperCamelCase : Tuple = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) UpperCamelCase : Dict = torch.tensor( [ [1.8324, -8.0835, -4.1922], [0.8450, -9.0050, -3.6053], [0.3045, -7.7293, -3.0275], ] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) def a_ ( self ): UpperCamelCase : Dict = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase : Union[str, Any] = self.default_image_processor UpperCamelCase : Union[str, Any] = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="""pt""" , ) UpperCamelCase : Optional[int] = inputs["""pixel_values"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = [el.to(SCREAMING_SNAKE_CASE_ ) for el in inputs["""mask_labels"""]] UpperCamelCase : Tuple = [el.to(SCREAMING_SNAKE_CASE_ ) for el in inputs["""class_labels"""]] with torch.no_grad(): UpperCamelCase : Dict = model(**SCREAMING_SNAKE_CASE_ ) self.assertTrue(outputs.loss is not None )
370
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def A_ ( snake_case_ : int ): # picklable for multiprocessing '''simple docstring''' return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def A_ ( ): '''simple docstring''' with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" UpperCamelCase : Optional[Any] = [1, 2, 3] with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=2 ) with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" ,[2, -1] ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : List[Any] = [1, 2] UpperCamelCase : List[Any] = {"""a""": 1, """b""": 2} UpperCamelCase : List[str] = {"""a""": [1, 2], """b""": [3, 4]} UpperCamelCase : Tuple = {"""a""": {"""1""": 1}, """b""": 2} UpperCamelCase : Any = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} UpperCamelCase : Optional[int] = [2, 3] UpperCamelCase : List[str] = {"""a""": 2, """b""": 3} UpperCamelCase : Any = {"""a""": [2, 3], """b""": [4, 5]} UpperCamelCase : Tuple = {"""a""": {"""1""": 2}, """b""": 3} UpperCamelCase : List[str] = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa
27
0
"""simple docstring""" from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=36 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=1000 , ): UpperCamelCase : Union[str, Any] = parent UpperCamelCase : Optional[Any] = batch_size UpperCamelCase : List[str] = num_channels UpperCamelCase : Optional[Any] = image_size UpperCamelCase : Tuple = patch_size UpperCamelCase : Union[str, Any] = is_training UpperCamelCase : Dict = use_input_mask UpperCamelCase : Optional[Any] = use_token_type_ids UpperCamelCase : Union[str, Any] = use_labels UpperCamelCase : Optional[Any] = vocab_size UpperCamelCase : str = hidden_size UpperCamelCase : str = num_hidden_layers UpperCamelCase : Optional[int] = num_attention_heads UpperCamelCase : List[Any] = intermediate_size UpperCamelCase : Any = hidden_act UpperCamelCase : Dict = hidden_dropout_prob UpperCamelCase : Tuple = attention_probs_dropout_prob UpperCamelCase : Tuple = max_position_embeddings UpperCamelCase : int = type_vocab_size UpperCamelCase : Tuple = type_sequence_label_size UpperCamelCase : Any = initializer_range UpperCamelCase : List[str] = coordinate_size UpperCamelCase : int = shape_size UpperCamelCase : Tuple = num_labels UpperCamelCase : Union[str, Any] = num_choices UpperCamelCase : Optional[Any] = scope UpperCamelCase : Tuple = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) UpperCamelCase : Dict = text_seq_length UpperCamelCase : Optional[int] = (image_size // patch_size) ** 2 + 1 UpperCamelCase : int = self.text_seq_length + self.image_seq_length def a_ ( self ): UpperCamelCase : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) UpperCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) UpperCamelCase : Optional[Any] = 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]: UpperCamelCase : Optional[Any] = bbox[i, j, 3] UpperCamelCase : Optional[Any] = bbox[i, j, 1] UpperCamelCase : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: UpperCamelCase : Union[str, Any] = bbox[i, j, 2] UpperCamelCase : List[Any] = bbox[i, j, 0] UpperCamelCase : Dict = tmp_coordinate UpperCamelCase : Optional[int] = tf.constant(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase : List[Any] = None if self.use_input_mask: UpperCamelCase : Optional[int] = random_attention_mask([self.batch_size, self.text_seq_length] ) UpperCamelCase : int = None if self.use_token_type_ids: UpperCamelCase : Optional[int] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) UpperCamelCase : List[Any] = None UpperCamelCase : List[Any] = None if self.use_labels: UpperCamelCase : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) UpperCamelCase : Optional[Any] = LayoutLMvaConfig( 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 , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = TFLayoutLMvaModel(config=SCREAMING_SNAKE_CASE_ ) # text + image UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = model( SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only UpperCamelCase : Dict = model({"""pixel_values""": pixel_values} , training=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.num_labels UpperCamelCase : List[Any] = TFLayoutLMvaForSequenceClassification(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = model( SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = self.num_labels UpperCamelCase : Optional[Any] = TFLayoutLMvaForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model( SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = 2 UpperCamelCase : int = TFLayoutLMvaForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = model( SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self ): UpperCamelCase : Dict = self.prepare_config_and_inputs() (UpperCamelCase) : Tuple = config_and_inputs UpperCamelCase : List[Any] = { """input_ids""": input_ids, """bbox""": bbox, """pixel_values""": pixel_values, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_tf class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : List[Any] = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) lowercase : Union[str, Any] = ( {'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel} if is_tf_available() else {} ) lowercase : int = False lowercase : List[str] = False lowercase : int = False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return True def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase : Any = copy.deepcopy(SCREAMING_SNAKE_CASE_ ) if model_class in get_values(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = { k: tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_ , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(SCREAMING_SNAKE_CASE_ , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) UpperCamelCase : Union[str, Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def a_ ( self ): UpperCamelCase : Any = TFLayoutLMvaModelTester(self ) UpperCamelCase : Tuple = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : Optional[int] = model_class(SCREAMING_SNAKE_CASE_ ) if getattr(SCREAMING_SNAKE_CASE_ , """hf_compute_loss""" , SCREAMING_SNAKE_CASE_ ): # The number of elements in the loss should be the same as the number of elements in the label UpperCamelCase : List[Any] = self._prepare_for_class(inputs_dict.copy() , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=SCREAMING_SNAKE_CASE_ )[0] ] UpperCamelCase : str = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs UpperCamelCase : int = self._prepare_for_class(inputs_dict.copy() , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = prepared_for_class.pop("""input_ids""" ) UpperCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions UpperCamelCase : Optional[Any] = self._prepare_for_class(inputs_dict.copy() , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = prepared_for_class.pop("""input_ids""" ) if "labels" in prepared_for_class: UpperCamelCase : Optional[Any] = prepared_for_class["""labels"""].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: UpperCamelCase : Optional[Any] = -100 UpperCamelCase : Any = tf.convert_to_tensor(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict UpperCamelCase : str = self._prepare_for_class(inputs_dict.copy() , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple UpperCamelCase : Any = self._prepare_for_class(inputs_dict.copy() , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) # Get keys that were added with the _prepare_for_class function UpperCamelCase : Tuple = prepared_for_class.keys() - inputs_dict.keys() UpperCamelCase : Optional[Any] = inspect.signature(model.call ).parameters UpperCamelCase : int = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple UpperCamelCase : List[Any] = {0: """input_ids"""} for label_key in label_keys: UpperCamelCase : List[str] = signature_names.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = label_key UpperCamelCase : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple UpperCamelCase : Tuple = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: UpperCamelCase : Dict = prepared_for_class[value] UpperCamelCase : Tuple = tuple(SCREAMING_SNAKE_CASE_ ) # Send to model UpperCamelCase : str = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def a_ ( self ): ( UpperCamelCase ) : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): ( UpperCamelCase ) : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase : str = type self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): ( UpperCamelCase ) : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): ( UpperCamelCase ) : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): ( UpperCamelCase ) : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : int = TFLayoutLMvaModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : Optional[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf class lowerCamelCase ( unittest.TestCase ): @cached_property def a_ ( self ): return LayoutLMvaImageProcessor(apply_ocr=SCREAMING_SNAKE_CASE_ ) if is_vision_available() else None @slow def a_ ( self ): UpperCamelCase : Any = TFLayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base""" ) UpperCamelCase : Optional[int] = self.default_image_processor UpperCamelCase : str = prepare_img() UpperCamelCase : List[str] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors="""tf""" ).pixel_values UpperCamelCase : List[Any] = tf.constant([[1, 2]] ) UpperCamelCase : Dict = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass UpperCamelCase : Union[str, Any] = model(input_ids=SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ ) # verify the logits UpperCamelCase : Union[str, Any] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
371
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="last" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=0 , ): UpperCamelCase : Union[str, Any] = parent UpperCamelCase : str = batch_size UpperCamelCase : int = seq_length UpperCamelCase : Optional[Any] = is_training UpperCamelCase : Any = use_input_lengths UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : List[Any] = use_labels UpperCamelCase : Union[str, Any] = gelu_activation UpperCamelCase : Dict = sinusoidal_embeddings UpperCamelCase : Optional[int] = causal UpperCamelCase : List[Any] = asm UpperCamelCase : int = n_langs UpperCamelCase : Optional[Any] = vocab_size UpperCamelCase : str = n_special UpperCamelCase : Dict = hidden_size UpperCamelCase : Union[str, Any] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : int = max_position_embeddings UpperCamelCase : Any = type_sequence_label_size UpperCamelCase : str = initializer_range UpperCamelCase : str = num_labels UpperCamelCase : Union[str, Any] = num_choices UpperCamelCase : List[str] = summary_type UpperCamelCase : int = use_proj UpperCamelCase : List[str] = scope UpperCamelCase : Dict = bos_token_id def a_ ( self ): UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Union[str, Any] = None if self.use_input_lengths: UpperCamelCase : str = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase : Tuple = None if self.use_token_type_ids: UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase : int = None UpperCamelCase : Dict = None UpperCamelCase : str = None if self.use_labels: UpperCamelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Dict = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : List[str] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def a_ ( self ): return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[int] = XLMModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , lengths=SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[Any] = XLMWithLMHeadModel(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : List[str] = XLMForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : int = XLMForQuestionAnswering(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , p_mask=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , ) ((UpperCamelCase) , ) : Union[str, Any] = result_with_labels.to_tuple() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , ) : Tuple = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = XLMForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : int = self.num_labels UpperCamelCase : int = XLMForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : List[Any] = self.num_choices UpperCamelCase : Tuple = XLMForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Optional[Any] = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : int = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : List[Any] = config_and_inputs UpperCamelCase : Dict = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) lowercase : List[Any] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable lowercase : Optional[Any] = ( { 'feature-extraction': XLMModel, 'fill-mask': XLMWithLMHeadModel, 'question-answering': XLMForQuestionAnsweringSimple, 'text-classification': XLMForSequenceClassification, 'text-generation': XLMWithLMHeadModel, 'token-classification': XLMForTokenClassification, 'zero-shot': XLMForSequenceClassification, } if is_torch_available() else {} ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": UpperCamelCase : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) return inputs_dict def a_ ( self ): UpperCamelCase : List[Any] = XLMModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , emb_dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_attentions in attentions] , [True] * len(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : int = min_length + idx + 1 UpperCamelCase : Tuple = min_length + idx + 1 UpperCamelCase : Any = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_hidden_states in hidden_states] , [True] * len(SCREAMING_SNAKE_CASE_ ) , ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : List[str] = min_length + idx + 1 UpperCamelCase : Optional[Any] = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) , ) pass @slow def a_ ( self ): for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : str = XLMModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Dict = XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.tensor([[14, 447]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # the president UpperCamelCase : List[Any] = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference UpperCamelCase : Optional[int] = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , SCREAMING_SNAKE_CASE_ )
27
0
from __future__ import annotations import time import numpy as np __A : List[Any] = [8, 5, 9, 7] __A : Union[str, Any] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] __A : str = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = claim_vector UpperCamelCase : Dict = allocated_resources_table UpperCamelCase : Tuple = maximum_claim_table def a_ ( self ): return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def a_ ( self ): return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def a_ ( self ): return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(SCREAMING_SNAKE_CASE_ ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def a_ ( self ): return {self.__need().index(SCREAMING_SNAKE_CASE_ ): i for i in self.__need()} def a_ ( self , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = self.__need() UpperCamelCase : Any = self.__allocated_resources_table UpperCamelCase : Tuple = self.__available_resources() UpperCamelCase : Union[str, Any] = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("""_""" * 50 + """\n""" ) while need_list: UpperCamelCase : Optional[Any] = False for each_need in need_list: UpperCamelCase : Any = True for index, need in enumerate(SCREAMING_SNAKE_CASE_ ): if need > available_resources[index]: UpperCamelCase : Any = False break if execution: UpperCamelCase : Dict = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: UpperCamelCase : Tuple = original_need_index print(f'Process {process_number + 1} is executing.' ) # remove the process run from stack need_list.remove(SCREAMING_SNAKE_CASE_ ) # update available/freed resources stack UpperCamelCase : Dict = np.array(SCREAMING_SNAKE_CASE_ ) + np.array( alloc_resources_table[process_number] ) print( """Updated available resource stack for processes: """ + """ """.join([str(SCREAMING_SNAKE_CASE_ ) for x in available_resources] ) ) break if safe: print("""The process is in a safe state.\n""" ) else: print("""System in unsafe state. Aborting...\n""" ) break def a_ ( self ): print(""" """ * 9 + """Allocated Resource Table""" ) for item in self.__allocated_resources_table: print( f'P{self.__allocated_resources_table.index(SCREAMING_SNAKE_CASE_ ) + 1}' + """ """.join(f'{it:>8}' for it in item ) + """\n""" ) print(""" """ * 9 + """System Resource Table""" ) for item in self.__maximum_claim_table: print( f'P{self.__maximum_claim_table.index(SCREAMING_SNAKE_CASE_ ) + 1}' + """ """.join(f'{it:>8}' for it in item ) + """\n""" ) print( """Current Usage by Active Processes: """ + """ """.join(str(SCREAMING_SNAKE_CASE_ ) for x in self.__claim_vector ) ) print( """Initial Available Resources: """ + """ """.join(str(SCREAMING_SNAKE_CASE_ ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
350
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A : int = { '''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = [ '''GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTBigCodeForSequenceClassification''', '''GPTBigCodeForTokenClassification''', '''GPTBigCodeForCausalLM''', '''GPTBigCodeModel''', '''GPTBigCodePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
0
"""simple docstring""" import requests from bsa import BeautifulSoup def A_ ( snake_case_ : str = "https://www.worldometers.info/coronavirus" ): '''simple docstring''' UpperCamelCase : Any = BeautifulSoup(requests.get(snake_case_ ).text ,"""html.parser""" ) UpperCamelCase : Optional[int] = soup.findAll("""h1""" ) UpperCamelCase : List[Any] = soup.findAll("""div""" ,{"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" ,{"""class""": """panel-title"""} ) values += soup.findAll("""div""" ,{"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(snake_case_ ,snake_case_ )} if __name__ == "__main__": print('''\033[1m''' + '''COVID-19 Status of the World''' + '''\033[0m\n''') for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
351
"""simple docstring""" import torch from transformers import AutoModel class lowerCamelCase ( torch.nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_="sayef/fsner-bert-base-uncased" ): super(SCREAMING_SNAKE_CASE_ , self ).__init__() UpperCamelCase : int = AutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.nn.CosineSimilarity(3 , 1e-08 ) UpperCamelCase : Any = torch.nn.Softmax(dim=1 ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return self.bert(**SCREAMING_SNAKE_CASE_ ).last_hidden_state def a_ ( self , SCREAMING_SNAKE_CASE_ ): return token_embeddings.sum(2 , keepdim=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1 ): return self.softmax(T * self.cos(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = W_supports["""sizes"""].tolist() UpperCamelCase : List[str] = W_supports["""start_token_id"""].item() UpperCamelCase : List[Any] = W_supports["""end_token_id"""].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCamelCase : List[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = None UpperCamelCase : Optional[Any] = None UpperCamelCase : Tuple = W_supports["""input_ids"""] == start_token_id UpperCamelCase : Optional[Any] = W_supports["""input_ids"""] == end_token_id for i, size in enumerate(SCREAMING_SNAKE_CASE_ ): if i == 0: UpperCamelCase : int = 0 else: UpperCamelCase : Optional[int] = support_sizes[i - 1] UpperCamelCase : Tuple = S[s : s + size][start_token_masks[s : s + size]] UpperCamelCase : int = S[s : s + size][end_token_masks[s : s + size]] UpperCamelCase : Dict = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCamelCase : Tuple = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCamelCase : List[str] = torch.vstack((p_starts, p_start) ) UpperCamelCase : Optional[Any] = torch.vstack((p_ends, p_end) ) else: UpperCamelCase : Optional[int] = p_start UpperCamelCase : Tuple = p_end return p_starts, p_ends
27
0
"""simple docstring""" import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Any = CpmAntTokenizer lowercase : Optional[Any] = False def a_ ( self ): super().setUp() UpperCamelCase : Union[str, Any] = [ """<d>""", """</d>""", """<s>""", """</s>""", """</_>""", """<unk>""", """<pad>""", """</n>""", """我""", """是""", """C""", """P""", """M""", """A""", """n""", """t""", ] UpperCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) @tooslow def a_ ( self ): UpperCamelCase : Optional[int] = CpmAntTokenizer.from_pretrained("""openbmb/cpm-ant-10b""" ) UpperCamelCase : Union[str, Any] = """今天天气真好!""" UpperCamelCase : int = ["""今天""", """天气""", """真""", """好""", """!"""] UpperCamelCase : Optional[Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = """今天天气真好!""" UpperCamelCase : List[Any] = [tokenizer.bos_token] + tokens UpperCamelCase : Dict = [6, 9802, 1_4962, 2082, 831, 244] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
352
"""simple docstring""" from typing import Any class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = data UpperCamelCase : Optional[Any] = None def __repr__( self ): return f'Node({self.data})' class lowerCamelCase : def __init__( self ): UpperCamelCase : Dict = None def __iter__( self ): UpperCamelCase : int = self.head while node: yield node.data UpperCamelCase : Union[str, Any] = node.next def __len__( self ): return sum(1 for _ in self ) def __repr__( self ): return "->".join([str(SCREAMING_SNAKE_CASE_ ) for item in self] ) def __getitem__( self , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) UpperCamelCase : List[Any] = self.head for _ in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = current.next UpperCamelCase : Optional[Any] = data def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(len(self ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(0 , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index <= len(self ): raise IndexError("""list index out of range""" ) UpperCamelCase : Optional[Any] = Node(SCREAMING_SNAKE_CASE_ ) if self.head is None: UpperCamelCase : Dict = new_node elif index == 0: UpperCamelCase : Any = self.head # link new_node to head UpperCamelCase : Any = new_node else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : str = temp.next UpperCamelCase : Any = temp.next UpperCamelCase : Optional[Any] = new_node def a_ ( self ): # print every node data print(self ) def a_ ( self ): return self.delete_nth(0 ) def a_ ( self ): # delete from tail return self.delete_nth(len(self ) - 1 ) def a_ ( self , SCREAMING_SNAKE_CASE_ = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("""List index out of range.""" ) UpperCamelCase : Union[str, Any] = self.head # default first node if index == 0: UpperCamelCase : Optional[Any] = self.head.next else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : int = temp.next UpperCamelCase : Optional[Any] = temp.next UpperCamelCase : Dict = temp.next.next return delete_node.data def a_ ( self ): return self.head is None def a_ ( self ): UpperCamelCase : Optional[Any] = None UpperCamelCase : Union[str, Any] = self.head while current: # Store the current node's next node. UpperCamelCase : Optional[int] = current.next # Make the current node's next point backwards UpperCamelCase : Optional[Any] = prev # Make the previous node be the current node UpperCamelCase : int = current # Make the current node the next node (to progress iteration) UpperCamelCase : Optional[int] = next_node # Return prev in order to put the head at the end UpperCamelCase : Optional[int] = prev def A_ ( ): '''simple docstring''' UpperCamelCase : int = LinkedList() assert linked_list.is_empty() is True assert str(snake_case_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(1_0 ): assert len(snake_case_ ) == i linked_list.insert_nth(snake_case_ ,i + 1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_1 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(1_1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(0 ,1_2 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 1_0 assert linked_list.delete_tail() == 1_1 assert len(snake_case_ ) == 9 assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_0 ) ) assert all(linked_list[i] == i + 1 for i in range(0 ,9 ) ) is True for i in range(0 ,9 ): UpperCamelCase : Optional[Any] = -i assert all(linked_list[i] == -i for i in range(0 ,9 ) ) is True linked_list.reverse() assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(-8 ,1 ) ) def A_ ( ): '''simple docstring''' UpperCamelCase : int = [ -9, 1_0_0, Node(7_7_3_4_5_1_1_2 ), """dlrow olleH""", 7, 5_5_5_5, 0, -192.55555, """Hello, world!""", 77.9, Node(1_0 ), None, None, 12.20, ] UpperCamelCase : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(snake_case_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(snake_case_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head UpperCamelCase : Dict = linked_list.delete_head() assert result == -9 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail UpperCamelCase : int = linked_list.delete_tail() assert result == 12.2 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list UpperCamelCase : Optional[Any] = linked_list.delete_nth(1_0 ) assert result is None assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("""Hello again, world!""" ) ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(snake_case_ ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(snake_case_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def A_ ( ): '''simple docstring''' from doctest import testmod testmod() UpperCamelCase : List[Any] = LinkedList() linked_list.insert_head(input("""Inserting 1st at head """ ).strip() ) linked_list.insert_head(input("""Inserting 2nd at head """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() linked_list.insert_tail(input("""\nInserting 1st at tail """ ).strip() ) linked_list.insert_tail(input("""Inserting 2nd at tail """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() print("""\nDelete head""" ) linked_list.delete_head() print("""Delete tail""" ) linked_list.delete_tail() print("""\nPrint list:""" ) linked_list.print_list() print("""\nReverse linked list""" ) linked_list.reverse() print("""\nPrint list:""" ) linked_list.print_list() print("""\nString representation of linked list:""" ) print(snake_case_ ) print("""\nReading/changing Node data using indexing:""" ) print(f'Element at Position 1: {linked_list[1]}' ) UpperCamelCase : List[Any] = input("""Enter New Value: """ ).strip() print("""New list:""" ) print(snake_case_ ) print(f'length of linked_list is : {len(snake_case_ )}' ) if __name__ == "__main__": main()
27
0