code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" lowerCamelCase_ : Optional[int] = [ (1_0_0_0, """M"""), (9_0_0, """CM"""), (5_0_0, """D"""), (4_0_0, """CD"""), (1_0_0, """C"""), (9_0, """XC"""), (5_0, """L"""), (4_0, """XL"""), (1_0, """X"""), (9, """IX"""), (5, """V"""), (4, """IV"""), (1, """I"""), ] def _A ( lowercase ): """simple docstring""" a ={'''I''': 1, '''V''': 5, '''X''': 10, '''L''': 50, '''C''': 1_00, '''D''': 5_00, '''M''': 10_00} a =0 a =0 while place < len(lowercase ): if (place + 1 < len(lowercase )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def _A ( lowercase ): """simple docstring""" a =[] for arabic, roman in ROMAN: ((a) , (a)) =divmod(lowercase , lowercase ) result.append(roman * factor ) if number == 0: break return "".join(lowercase ) if __name__ == "__main__": import doctest doctest.testmod()
81
"""simple docstring""" def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =set() # Replace all the whitespace in our sentence a =input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowercase ) == 26 def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =[False] * 26 for char in input_str: if char.islower(): a =True elif char.isupper(): a =True return all(lowercase ) def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _A ( ): """simple docstring""" from timeit import timeit a ='''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowercase ) ) print(timeit('''is_pangram_faster()''' , setup=lowercase ) ) print(timeit('''is_pangram_fastest()''' , setup=lowercase ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
81
1
"""simple docstring""" def _A ( lowercase ): """simple docstring""" return sum(i for i in range(1 , number // 2 + 1 ) if number % i == 0 ) == number if __name__ == "__main__": print("""Program to check whether a number is a Perfect number or not...""") lowerCamelCase_ : str = int(input("""Enter number: """).strip()) print(F'{number} is {"" if perfect(number) else "not "}a Perfect Number.')
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys lowerCamelCase_ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" from bisect import bisect from itertools import accumulate def _A ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =sorted(zip(lowercase , lowercase ) , key=lambda lowercase : x[0] / x[1] , reverse=lowercase ) a , a =[i[0] for i in r], [i[1] for i in r] a =list(accumulate(lowercase ) ) a =bisect(lowercase , lowercase ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
81
"""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 lowerCamelCase_ : Dict = logging.getLogger(__name__) lowerCamelCase_ : Tuple = """pytorch_model.bin""" @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co."}, ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the training data."} ) __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the data to predict on."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "A csv or a json file containing the validation data."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The name of the task to train on."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The list of labels for the task."} ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "The output directory where the model predictions and checkpoints will be written."} ) __lowerCAmelCase = dataclasses.field( default="accuracy", metadata={"help": "The evaluation metric used for the task."} ) __lowerCAmelCase = dataclasses.field( default="no", metadata={ "help": "The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]" }, ) __lowerCAmelCase = dataclasses.field( default=10, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={ "help": "How much the specified evaluation metric must improve to satisfy early stopping conditions." }, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the confidence score."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the validation performance."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to fine-tune on labeled data after pseudo training."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={"help": "Confidence threshold for pseudo-labeled data filtering."}, ) __lowerCAmelCase = dataclasses.field( default=100, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Random seed for initialization."}, ) def _A ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: a =dataset.filter(lambda lowercase : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 a =int(eval_result * len(lowercase ) ) print(lowercase ) a =dataset.sort('''probability''' , reverse=lowercase ) a =dataset.select(range(lowercase ) ) a =dataset.remove_columns(['''label''', '''probability'''] ) a =dataset.rename_column('''prediction''' , '''label''' ) a =dataset.map(lambda lowercase : {"label": idalabel[example["label"]]} ) a =dataset.shuffle(seed=args.seed ) a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(lowercase , index=lowercase ) else: dataset.to_json(lowercase ) def _A ( lowercase , lowercase , lowercase , lowercase , **lowercase ): """simple docstring""" a =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() a =STModelArguments(model_name_or_path=lowercase ) a =STDataArguments(train_file=lowercase , infer_file=lowercase ) a =STTrainingArguments(output_dir=lowercase ) a =argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(lowercase ).items(): setattr(lowercase , lowercase , lowercase ) for key, value in kwargs.items(): if hasattr(lowercase , lowercase ): setattr(lowercase , lowercase , lowercase ) # Sanity checks a ={} a =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 a =args.train_file a =args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None a =args.eval_file for key in data_files: a =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: a =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...''' ) a =f'''{args.output_dir}/self-train_iter-{{}}'''.format a =data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=lowercase ) os.makedirs(lowercase , exist_ok=lowercase ) accelerator.wait_for_everyone() a =None a =None a =0 a =False # Show the progress bar a =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 ) ): a =data_dir_format(lowercase ) assert os.path.exists(lowercase ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 a =os.path.join(lowercase , '''stage-1''' ) a ={ '''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(lowercase , lowercase ): arguments_dict.update({key: value} ) a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 1 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 1.''' , lowercase ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data a =os.path.join(lowercase , '''best-checkpoint''' ) a =os.path.join(lowercase , '''stage-2''' ) # Update arguments_dict a =model_path a =data_files['''train'''] a =current_output_dir a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 2 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 2.''' , lowercase ) a =iteration a =data_dir_format(iteration + 1 ) a =AutoConfig.from_pretrained(os.path.join(lowercase , '''best-checkpoint''' ) ) a =config.idalabel a =os.path.join(lowercase , '''eval_results_best-checkpoint.json''' ) a =os.path.join(lowercase , '''test_results_best-checkpoint.json''' ) assert os.path.exists(lowercase ) with open(lowercase , '''r''' ) as f: a =float(json.load(lowercase )[args.eval_metric] ) a =os.path.join(lowercase , '''infer_output_best-checkpoint.csv''' ) assert os.path.exists(lowercase ) # Loading the dataset from local csv or json files. a =load_dataset(args.data_file_extension , data_files={'''data''': data_files['''infer''']} )['''data'''] a =load_dataset('''csv''' , data_files={'''data''': infer_output_file} )['''data'''] if accelerator.is_main_process: os.makedirs(lowercase , exist_ok=lowercase ) shutil.copy(lowercase , os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(lowercase ): shutil.copy(lowercase , os.path.join(lowercase , f'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) accelerator.wait_for_everyone() a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: a =eval_result if best_iteration is None: a =new_iteration a =new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: a =new_iteration a =new_eval_result a =0 else: if new_eval_result == best_eval_result: a =new_iteration a =new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: a =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''' , lowercase ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) , os.path.join(lowercase , '''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 , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(lowercase , '''eval_results_best-iteration.json''' ) , )
81
1
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) lowerCamelCase_ : int = logging.getLogger(__name__) if __name__ == "__main__": lowerCamelCase_ : Any = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=3_0_5_2_2, type=int) lowerCamelCase_ : int = parser.parse_args() logger.info(F'Loading data from {args.data_file}') with open(args.data_file, """rb""") as fp: lowerCamelCase_ : Optional[int] = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") lowerCamelCase_ : Optional[int] = Counter() for tk_ids in data: counter.update(tk_ids) lowerCamelCase_ : Dict = [0] * args.vocab_size for k, v in counter.items(): lowerCamelCase_ : Any = v logger.info(F'Dump to {args.token_counts_dump}') with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
81
"""simple docstring""" def _A ( ): """simple docstring""" for n in range(1 , 1_00_00_00 ): yield n * (n + 1) // 2 def _A ( lowercase ): """simple docstring""" a =1 a =2 while i * i <= n: a =0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _A ( ): """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(lowercase ) > 5_00 ) if __name__ == "__main__": print(solution())
81
1
"""simple docstring""" import numpy as np def _A ( lowercase , lowercase , lowercase = 1E-12 , lowercase = 1_00 , ): """simple docstring""" assert np.shape(lowercase )[0] == np.shape(lowercase )[1] # Ensure proper dimensionality. assert np.shape(lowercase )[0] == np.shape(lowercase )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(lowercase ) == np.iscomplexobj(lowercase ) a =np.iscomplexobj(lowercase ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(lowercase , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. a =False a =0 a =0 a =1E12 while not convergence: # Multiple matrix by the vector. a =np.dot(lowercase , lowercase ) # Normalize the resulting output vector. a =w / np.linalg.norm(lowercase ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) a =vector.conj().T if is_complex else vector.T a =np.dot(lowercase , np.dot(lowercase , lowercase ) ) # Check convergence. a =np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: a =True a =lambda_ if is_complex: a =np.real(lambda_ ) return lambda_, vector def _A ( ): """simple docstring""" a =np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) a =np.array([41, 4, 20] ) a =real_input_matrix.astype(np.complexaaa ) a =np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T a =np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": a =real_input_matrix a =real_vector elif problem_type == "complex": a =complex_input_matrix a =complex_vector # Our implementation. a , a =power_iteration(lowercase , lowercase ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). a , a =np.linalg.eigh(lowercase ) # Last eigenvalue is the maximum one. a =eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. a =eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(lowercase ) - np.abs(lowercase ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
81
"""simple docstring""" from math import factorial def _A ( lowercase = 1_00 ): """simple docstring""" return sum(int(lowercase ) for x in str(factorial(lowercase ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
81
1
"""simple docstring""" import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print("""Googling.....""") lowerCamelCase_ : List[Any] = """https://www.google.com/search?q=""" + """ """.join(sys.argv[1:]) lowerCamelCase_ : Optional[Any] = requests.get(url, headers={"""UserAgent""": UserAgent().random}) # res.raise_for_status() with open("""project1a.html""", """wb""") as out_file: # only for knowing the class for data in res.iter_content(1_0_0_0_0): out_file.write(data) lowerCamelCase_ : Union[str, Any] = BeautifulSoup(res.text, """html.parser""") lowerCamelCase_ : Union[str, Any] = list(soup.select(""".eZt8xd"""))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get("""href""")) else: webbrowser.open(F'https://google.com{link.get("href")}')
81
"""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, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Optional[Any] = """▁""" lowerCamelCase_ : Union[str, Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : Any = { """vocab_file""": { """xlm-roberta-base""": """https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large""": """https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large-finetuned-conll02-dutch""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll02-spanish""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-english""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-german""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model""" ), } } lowerCamelCase_ : Tuple = { """xlm-roberta-base""": 5_1_2, """xlm-roberta-large""": 5_1_2, """xlm-roberta-large-finetuned-conll02-dutch""": 5_1_2, """xlm-roberta-large-finetuned-conll02-spanish""": 5_1_2, """xlm-roberta-large-finetuned-conll03-english""": 5_1_2, """xlm-roberta-large-finetuned-conll03-german""": 5_1_2, } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a =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 a ={'''<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 a =1 a =len(self.sp_model ) + self.fairseq_offset a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: a =self.__dict__.copy() a =None a =self.sp_model.serialized_model_proto() return state def __setstate__( self , __A ) -> List[Any]: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[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] @property def SCREAMING_SNAKE_CASE ( self ) -> List[str]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> int: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =self.sp_model.PieceToId(__A ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: a =''''''.join(__A ).replace(__A , ''' ''' ).strip() return out_string def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , '''wb''' ) as fi: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
1
"""simple docstring""" def _A ( lowercase ): """simple docstring""" for i in range(len(lowercase ) - 1 , 0 , -1 ): a =False for j in range(lowercase , 0 , -1 ): if unsorted[j] < unsorted[j - 1]: a , a =unsorted[j - 1], unsorted[j] a =True for j in range(lowercase ): if unsorted[j] > unsorted[j + 1]: a , a =unsorted[j + 1], unsorted[j] a =True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase_ : Optional[int] = input("""Enter numbers separated by a comma:\n""").strip() lowerCamelCase_ : List[str] = [int(item) for item in user_input.split(""",""")] print(F'{cocktail_shaker_sort(unsorted) = }')
81
"""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, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Tuple = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : str = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } lowerCamelCase_ : Optional[int] = { """moussaKam/mbarthez""": 1_0_2_4, """moussaKam/barthez""": 1_0_2_4, """moussaKam/barthez-orangesum-title""": 1_0_2_4, } lowerCamelCase_ : Tuple = """▁""" class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =vocab_file a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a ={'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} a =len(self.sp_model ) - 1 a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[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] @property def SCREAMING_SNAKE_CASE ( self ) -> Any: return len(self.sp_model ) def SCREAMING_SNAKE_CASE ( self ) -> int: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Dict: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =self.sp_model.PieceToId(__A ) return spm_id if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Tuple: a =[] a ='''''' a =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__A ) + token a =True a =[] else: current_sub_tokens.append(__A ) a =False out_string += self.sp_model.decode(__A ) return out_string.strip() def __getstate__( self ) -> Tuple: a =self.__dict__.copy() a =None return state def __setstate__( self , __A ) -> Tuple: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , '''wb''' ) as fi: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import MobileBertConfig, is_tf_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_MODEL_FOR_PRETRAINING_MAPPING, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertModel, ) @require_tf class __A ( _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = ( ( TFMobileBertModel, TFMobileBertForMaskedLM, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertForMultipleChoice, ) if is_tf_available() else () ) __lowerCAmelCase = ( { "feature-extraction": TFMobileBertModel, "fill-mask": TFMobileBertForMaskedLM, "question-answering": TFMobileBertForQuestionAnswering, "text-classification": TFMobileBertForSequenceClassification, "token-classification": TFMobileBertForTokenClassification, "zero-shot": TFMobileBertForSequenceClassification, } if is_tf_available() else {} ) __lowerCAmelCase = False __lowerCAmelCase = False def SCREAMING_SNAKE_CASE ( self , __A , __A , __A=False ) -> Union[str, Any]: a =super()._prepare_for_class(__A , __A , return_labels=__A ) if return_labels: if model_class in get_values(__A ): a =tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) return inputs_dict class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , __A , __A=13 , __A=7 , __A=True , __A=True , __A=True , __A=True , __A=99 , __A=32 , __A=32 , __A=2 , __A=4 , __A=37 , __A="gelu" , __A=0.1 , __A=0.1 , __A=512 , __A=16 , __A=2 , __A=0.02 , __A=3 , __A=4 , __A=None , ) -> Optional[int]: a =parent a =batch_size a =seq_length a =is_training a =use_input_mask a =use_token_type_ids a =use_labels a =vocab_size a =hidden_size a =num_hidden_layers a =num_attention_heads a =intermediate_size a =hidden_act a =hidden_dropout_prob a =attention_probs_dropout_prob a =max_position_embeddings a =type_vocab_size a =type_sequence_label_size a =initializer_range a =num_labels a =num_choices a =scope a =embedding_size def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a =None if self.use_input_mask: a =random_attention_mask([self.batch_size, self.seq_length] ) a =None if self.use_token_type_ids: a =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a =None a =None a =None if self.use_labels: a =ids_tensor([self.batch_size] , self.type_sequence_label_size ) a =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a =ids_tensor([self.batch_size] , self.num_choices ) a =MobileBertConfig( 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 , embedding_size=self.embedding_size , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> Any: a =TFMobileBertModel(config=__A ) a ={'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} a =model(__A ) a =[input_ids, input_mask] a =model(__A ) a =model(__A ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> Optional[Any]: a =TFMobileBertForMaskedLM(config=__A ) a ={'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} a =model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> List[Any]: a =TFMobileBertForNextSentencePrediction(config=__A ) a ={'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} a =model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> Optional[Any]: a =TFMobileBertForPreTraining(config=__A ) a ={'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} a =model(__A ) self.parent.assertEqual( result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> Optional[int]: a =self.num_labels a =TFMobileBertForSequenceClassification(config=__A ) a ={'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} a =model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> List[str]: a =self.num_choices a =TFMobileBertForMultipleChoice(config=__A ) a =tf.tile(tf.expand_dims(__A , 1 ) , (1, self.num_choices, 1) ) a =tf.tile(tf.expand_dims(__A , 1 ) , (1, self.num_choices, 1) ) a =tf.tile(tf.expand_dims(__A , 1 ) , (1, self.num_choices, 1) ) a ={ '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } a =model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> List[str]: a =self.num_labels a =TFMobileBertForTokenClassification(config=__A ) a ={'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} a =model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> List[Any]: a =TFMobileBertForQuestionAnswering(config=__A ) a ={'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} a =model(__A ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) =config_and_inputs a ={'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =TFMobileBertModelTest.TFMobileBertModelTester(self ) a =ConfigTester(self , config_class=__A , hidden_size=37 ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self ) -> str: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*__A ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Dict: # for model_name in TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["google/mobilebert-uncased"]: a =TFMobileBertModel.from_pretrained(__A ) self.assertIsNotNone(__A ) @require_tf class __A ( unittest.TestCase ): """simple docstring""" @slow def SCREAMING_SNAKE_CASE ( self ) -> str: a =TFMobileBertForPreTraining.from_pretrained('''google/mobilebert-uncased''' ) a =tf.constant([[0, 1, 2, 3, 4, 5]] ) a =model(__A )[0] a =[1, 6, 3_0522] self.assertEqual(output.shape , __A ) a =tf.constant( [ [ [-4.5_919_547, -9.248_295, -9.645_256], [-6.7_306_175, -6.440_284, -6.6_052_837], [-7.2_743_506, -6.7_847_915, -6.024_673], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , __A , atol=1E-4 )
81
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) lowerCamelCase_ : Tuple = logging.get_logger(__name__) lowerCamelCase_ : str = OrderedDict( [ ("""align""", """EfficientNetImageProcessor"""), ("""beit""", """BeitImageProcessor"""), ("""bit""", """BitImageProcessor"""), ("""blip""", """BlipImageProcessor"""), ("""blip-2""", """BlipImageProcessor"""), ("""bridgetower""", """BridgeTowerImageProcessor"""), ("""chinese_clip""", """ChineseCLIPImageProcessor"""), ("""clip""", """CLIPImageProcessor"""), ("""clipseg""", """ViTImageProcessor"""), ("""conditional_detr""", """ConditionalDetrImageProcessor"""), ("""convnext""", """ConvNextImageProcessor"""), ("""convnextv2""", """ConvNextImageProcessor"""), ("""cvt""", """ConvNextImageProcessor"""), ("""data2vec-vision""", """BeitImageProcessor"""), ("""deformable_detr""", """DeformableDetrImageProcessor"""), ("""deit""", """DeiTImageProcessor"""), ("""deta""", """DetaImageProcessor"""), ("""detr""", """DetrImageProcessor"""), ("""dinat""", """ViTImageProcessor"""), ("""donut-swin""", """DonutImageProcessor"""), ("""dpt""", """DPTImageProcessor"""), ("""efficientformer""", """EfficientFormerImageProcessor"""), ("""efficientnet""", """EfficientNetImageProcessor"""), ("""flava""", """FlavaImageProcessor"""), ("""focalnet""", """BitImageProcessor"""), ("""git""", """CLIPImageProcessor"""), ("""glpn""", """GLPNImageProcessor"""), ("""groupvit""", """CLIPImageProcessor"""), ("""imagegpt""", """ImageGPTImageProcessor"""), ("""instructblip""", """BlipImageProcessor"""), ("""layoutlmv2""", """LayoutLMv2ImageProcessor"""), ("""layoutlmv3""", """LayoutLMv3ImageProcessor"""), ("""levit""", """LevitImageProcessor"""), ("""mask2former""", """Mask2FormerImageProcessor"""), ("""maskformer""", """MaskFormerImageProcessor"""), ("""mgp-str""", """ViTImageProcessor"""), ("""mobilenet_v1""", """MobileNetV1ImageProcessor"""), ("""mobilenet_v2""", """MobileNetV2ImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevitv2""", """MobileViTImageProcessor"""), ("""nat""", """ViTImageProcessor"""), ("""oneformer""", """OneFormerImageProcessor"""), ("""owlvit""", """OwlViTImageProcessor"""), ("""perceiver""", """PerceiverImageProcessor"""), ("""pix2struct""", """Pix2StructImageProcessor"""), ("""poolformer""", """PoolFormerImageProcessor"""), ("""regnet""", """ConvNextImageProcessor"""), ("""resnet""", """ConvNextImageProcessor"""), ("""sam""", """SamImageProcessor"""), ("""segformer""", """SegformerImageProcessor"""), ("""swiftformer""", """ViTImageProcessor"""), ("""swin""", """ViTImageProcessor"""), ("""swin2sr""", """Swin2SRImageProcessor"""), ("""swinv2""", """ViTImageProcessor"""), ("""table-transformer""", """DetrImageProcessor"""), ("""timesformer""", """VideoMAEImageProcessor"""), ("""tvlt""", """TvltImageProcessor"""), ("""upernet""", """SegformerImageProcessor"""), ("""van""", """ConvNextImageProcessor"""), ("""videomae""", """VideoMAEImageProcessor"""), ("""vilt""", """ViltImageProcessor"""), ("""vit""", """ViTImageProcessor"""), ("""vit_hybrid""", """ViTHybridImageProcessor"""), ("""vit_mae""", """ViTImageProcessor"""), ("""vit_msn""", """ViTImageProcessor"""), ("""xclip""", """CLIPImageProcessor"""), ("""yolos""", """YolosImageProcessor"""), ] ) lowerCamelCase_ : Union[str, Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def _A ( lowercase ): """simple docstring""" for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: a =model_type_to_module_name(lowercase ) a =importlib.import_module(f'''.{module_name}''' , '''transformers.models''' ) try: return getattr(lowercase , lowercase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowercase , '''__name__''' , lowercase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. a =importlib.import_module('''transformers''' ) if hasattr(lowercase , lowercase ): return getattr(lowercase , lowercase ) return None def _A ( lowercase , lowercase = None , lowercase = False , lowercase = False , lowercase = None , lowercase = None , lowercase = None , lowercase = False , **lowercase , ): """simple docstring""" a =get_file_from_repo( lowercase , lowercase , cache_dir=lowercase , force_download=lowercase , resume_download=lowercase , proxies=lowercase , use_auth_token=lowercase , revision=lowercase , local_files_only=lowercase , ) if resolved_config_file is None: logger.info( '''Could not locate the image processor configuration file, will try to use the model config instead.''' ) return {} with open(lowercase , encoding='''utf-8''' ) as reader: return json.load(lowercase ) class __A : """simple docstring""" def __init__( self ) -> Optional[Any]: raise EnvironmentError( '''AutoImageProcessor is designed to be instantiated ''' '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__A ) def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> Dict: a =kwargs.pop('''config''' , __A ) a =kwargs.pop('''trust_remote_code''' , __A ) a =True a , a =ImageProcessingMixin.get_image_processor_dict(__A , **__A ) a =config_dict.get('''image_processor_type''' , __A ) a =None if "AutoImageProcessor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoImageProcessor'''] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: a =config_dict.pop('''feature_extractor_type''' , __A ) if feature_extractor_class is not None: logger.warning( '''Could not find image processor class in the image processor config or the model config. Loading''' ''' based on pattern matching with the model\'s feature extractor configuration.''' ) a =feature_extractor_class.replace('''FeatureExtractor''' , '''ImageProcessor''' ) if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoFeatureExtractor'''] a =feature_extractor_auto_map.replace('''FeatureExtractor''' , '''ImageProcessor''' ) logger.warning( '''Could not find image processor auto map in the image processor config or the model config.''' ''' Loading based on pattern matching with the model\'s feature extractor configuration.''' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(__A , __A ): a =AutoConfig.from_pretrained(__A , **__A ) # It could be in `config.image_processor_type`` a =getattr(__A , '''image_processor_type''' , __A ) if hasattr(__A , '''auto_map''' ) and "AutoImageProcessor" in config.auto_map: a =config.auto_map['''AutoImageProcessor'''] if image_processor_class is not None: a =image_processor_class_from_name(__A ) a =image_processor_auto_map is not None a =image_processor_class is not None or type(__A ) in IMAGE_PROCESSOR_MAPPING a =resolve_trust_remote_code( __A , __A , __A , __A ) if has_remote_code and trust_remote_code: a =get_class_from_dynamic_module( __A , __A , **__A ) a =kwargs.pop('''code_revision''' , __A ) if os.path.isdir(__A ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(__A , **__A ) elif image_processor_class is not None: return image_processor_class.from_dict(__A , **__A ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(__A ) in IMAGE_PROCESSOR_MAPPING: a =IMAGE_PROCESSOR_MAPPING[type(__A )] return image_processor_class.from_dict(__A , **__A ) raise ValueError( f'''Unrecognized image processor in {pretrained_model_name_or_path}. Should have a ''' f'''`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def SCREAMING_SNAKE_CASE ( __A , __A ) -> Any: IMAGE_PROCESSOR_MAPPING.register(__A , __A )
81
1
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase_ : str = logging.get_logger(__name__) def _A ( lowercase , lowercase=False ): """simple docstring""" a =[] # fmt: off # stem: rename_keys.append(('''cls_token''', '''vit.embeddings.cls_token''') ) rename_keys.append(('''pos_embed''', '''vit.embeddings.position_embeddings''') ) rename_keys.append(('''patch_embed.proj.weight''', '''vit.embeddings.patch_embeddings.projection.weight''') ) rename_keys.append(('''patch_embed.proj.bias''', '''vit.embeddings.patch_embeddings.projection.bias''') ) # backbone rename_keys.append(('''patch_embed.backbone.stem.conv.weight''', '''vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight''') ) rename_keys.append(('''patch_embed.backbone.stem.norm.weight''', '''vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight''') ) rename_keys.append(('''patch_embed.backbone.stem.norm.bias''', '''vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias''') ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias''') ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''blocks.{i}.norm1.weight''', f'''vit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''blocks.{i}.norm1.bias''', f'''vit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((f'''blocks.{i}.attn.proj.weight''', f'''vit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.attn.proj.bias''', f'''vit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''blocks.{i}.norm2.weight''', f'''vit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''blocks.{i}.norm2.bias''', f'''vit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.weight''', f'''vit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.bias''', f'''vit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.weight''', f'''vit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.bias''', f'''vit.encoder.layer.{i}.output.dense.bias''') ) if base_model: # layernorm + pooler rename_keys.extend( [ ('''norm.weight''', '''layernorm.weight'''), ('''norm.bias''', '''layernorm.bias'''), ('''pre_logits.fc.weight''', '''pooler.dense.weight'''), ('''pre_logits.fc.bias''', '''pooler.dense.bias'''), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" a =[(pair[0], pair[1][4:]) if pair[1].startswith('''vit''' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('''norm.weight''', '''vit.layernorm.weight'''), ('''norm.bias''', '''vit.layernorm.bias'''), ('''head.weight''', '''classifier.weight'''), ('''head.bias''', '''classifier.bias'''), ] ) # fmt: on return rename_keys def _A ( lowercase , lowercase , lowercase=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: a ='''''' else: a ='''vit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) a =state_dict.pop(f'''blocks.{i}.attn.qkv.weight''' ) a =state_dict.pop(f'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict a =in_proj_weight[ : config.hidden_size, : ] a =in_proj_bias[: config.hidden_size] a =in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] a =in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] a =in_proj_weight[ -config.hidden_size :, : ] a =in_proj_bias[-config.hidden_size :] def _A ( lowercase ): """simple docstring""" a =['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(lowercase , lowercase ) def _A ( lowercase , lowercase , lowercase ): """simple docstring""" a =dct.pop(lowercase ) a =val def _A ( ): """simple docstring""" a ='''http://images.cocodataset.org/val2017/000000039769.jpg''' a =Image.open(requests.get(lowercase , stream=lowercase ).raw ) return im @torch.no_grad() def _A ( lowercase , lowercase , lowercase=False ): """simple docstring""" a =BitConfig( global_padding='''same''' , layer_type='''bottleneck''' , depths=(3, 4, 9) , out_features=['''stage3'''] , embedding_dynamic_padding=lowercase , ) a =ViTHybridConfig(backbone_config=lowercase , image_size=3_84 , num_labels=10_00 ) a =False # load original model from timm a =timm.create_model(lowercase , pretrained=lowercase ) timm_model.eval() # load state_dict of original model, remove and rename some keys a =timm_model.state_dict() if base_model: remove_classification_head_(lowercase ) a =create_rename_keys(lowercase , lowercase ) for src, dest in rename_keys: rename_key(lowercase , lowercase , lowercase ) read_in_q_k_v(lowercase , lowercase , lowercase ) a ='''huggingface/label-files''' a ='''imagenet-1k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": a =ViTHybridModel(lowercase ).eval() else: a =ViTHybridForImageClassification(lowercase ).eval() model.load_state_dict(lowercase ) # create image processor a =create_transform(**resolve_data_config({} , model=lowercase ) ) a =transform.transforms a ={ '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } a =ViTHybridImageProcessor( do_resize=lowercase , size={'''shortest_edge''': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=lowercase , crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]} , do_normalize=lowercase , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) a =prepare_img() a =transform(lowercase ).unsqueeze(0 ) a =processor(lowercase , return_tensors='''pt''' ).pixel_values # verify pixel values assert torch.allclose(lowercase , lowercase ) # verify logits with torch.no_grad(): a =model(lowercase ) a =outputs.logits print('''Predicted class:''' , logits.argmax(-1 ).item() ) if base_model: a =timm_model.forward_features(lowercase ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(lowercase , outputs.pooler_output , atol=1E-3 ) else: a =timm_model(lowercase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowercase , outputs.logits , atol=1E-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(lowercase ).mkdir(exist_ok=lowercase ) print(f'''Saving model {vit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(lowercase ) if push_to_hub: print(f'''Pushing model and processor to the hub {vit_name}''' ) model.push_to_hub(f'''ybelkada/{vit_name}''' ) processor.push_to_hub(f'''ybelkada/{vit_name}''' ) if __name__ == "__main__": lowerCamelCase_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( """--vit_name""", default="""vit_base_r50_s16_384""", type=str, help="""Name of the hybrid ViT timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether to upload the model to the HuggingFace hub.""" ) lowerCamelCase_ : str = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
81
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = DistilBertTokenizer __lowerCAmelCase = DistilBertTokenizerFast __lowerCAmelCase = True @slow def SCREAMING_SNAKE_CASE ( self ) -> int: a =DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
81
1
"""simple docstring""" def _A ( lowercase = 10_00 ): """simple docstring""" a =2**power a =0 while n: a , a =r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCamelCase_ : List[str] = { """configuration_speech_to_text""": ["""SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Speech2TextConfig"""], """processing_speech_to_text""": ["""Speech2TextProcessor"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""Speech2TextTokenizer"""] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[Any] = ["""Speech2TextFeatureExtractor"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFSpeech2TextForConditionalGeneration""", """TFSpeech2TextModel""", """TFSpeech2TextPreTrainedModel""", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = [ """SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Speech2TextForConditionalGeneration""", """Speech2TextModel""", """Speech2TextPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() lowerCamelCase_ : Tuple = logging.get_logger(__name__) def _A ( lowercase , lowercase , lowercase ): """simple docstring""" a =WavaVecaForSequenceClassification.from_pretrained(lowercase , config=lowercase ) a =downstream_dict['''projector.weight'''] a =downstream_dict['''projector.bias'''] a =downstream_dict['''model.post_net.linear.weight'''] a =downstream_dict['''model.post_net.linear.bias'''] return model def _A ( lowercase , lowercase , lowercase ): """simple docstring""" a =WavaVecaForAudioFrameClassification.from_pretrained(lowercase , config=lowercase ) a =downstream_dict['''model.linear.weight'''] a =downstream_dict['''model.linear.bias'''] return model def _A ( lowercase , lowercase , lowercase ): """simple docstring""" a =WavaVecaForXVector.from_pretrained(lowercase , config=lowercase ) a =downstream_dict['''connector.weight'''] a =downstream_dict['''connector.bias'''] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): a =downstream_dict[ f'''model.framelevel_feature_extractor.module.{i}.kernel.weight''' ] a =downstream_dict[f'''model.framelevel_feature_extractor.module.{i}.kernel.bias'''] a =downstream_dict['''model.utterancelevel_feature_extractor.linear1.weight'''] a =downstream_dict['''model.utterancelevel_feature_extractor.linear1.bias'''] a =downstream_dict['''model.utterancelevel_feature_extractor.linear2.weight'''] a =downstream_dict['''model.utterancelevel_feature_extractor.linear2.bias'''] a =downstream_dict['''objective.W'''] return model @torch.no_grad() def _A ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =torch.load(lowercase , map_location='''cpu''' ) a =checkpoint['''Downstream'''] a =WavaVecaConfig.from_pretrained(lowercase ) a =WavaVecaFeatureExtractor.from_pretrained( lowercase , return_attention_mask=lowercase , do_normalize=lowercase ) a =hf_config.architectures[0] if arch.endswith('''ForSequenceClassification''' ): a =convert_classification(lowercase , lowercase , lowercase ) elif arch.endswith('''ForAudioFrameClassification''' ): a =convert_diarization(lowercase , lowercase , lowercase ) elif arch.endswith('''ForXVector''' ): a =convert_xvector(lowercase , lowercase , lowercase ) else: raise NotImplementedError(f'''S3PRL weights conversion is not supported for {arch}''' ) if hf_config.use_weighted_layer_sum: a =checkpoint['''Featurizer''']['''weights'''] hf_feature_extractor.save_pretrained(lowercase ) hf_model.save_pretrained(lowercase ) if __name__ == "__main__": lowerCamelCase_ : Union[str, Any] = 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.""") lowerCamelCase_ : Union[str, Any] = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : Union[str, Any] = { """configuration_table_transformer""": [ """TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TableTransformerConfig""", """TableTransformerOnnxConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TableTransformerForObjectDetection""", """TableTransformerModel""", """TableTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class __A ( metaclass=_SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = ["torch", "transformers", "onnx"] def __init__( self , *__A , **__A ) -> List[Any]: requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls , *__A , **__A ) -> Dict: requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls , *__A , **__A ) -> int: requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) class __A ( metaclass=_SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = ["torch", "transformers", "onnx"] def __init__( self , *__A , **__A ) -> Any: requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls , *__A , **__A ) -> Optional[int]: requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls , *__A , **__A ) -> Union[str, Any]: requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) class __A ( metaclass=_SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = ["torch", "transformers", "onnx"] def __init__( self , *__A , **__A ) -> Dict: requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls , *__A , **__A ) -> Dict: requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls , *__A , **__A ) -> Optional[int]: requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) class __A ( metaclass=_SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = ["torch", "transformers", "onnx"] def __init__( self , *__A , **__A ) -> int: requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls , *__A , **__A ) -> List[Any]: requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls , *__A , **__A ) -> List[Any]: requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) class __A ( metaclass=_SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = ["torch", "transformers", "onnx"] def __init__( self , *__A , **__A ) -> str: requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls , *__A , **__A ) -> int: requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls , *__A , **__A ) -> Any: requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) class __A ( metaclass=_SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = ["torch", "transformers", "onnx"] def __init__( self , *__A , **__A ) -> Dict: requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls , *__A , **__A ) -> str: requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls , *__A , **__A ) -> Union[str, Any]: requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] )
81
"""simple docstring""" from __future__ import annotations import math def _A ( lowercase ): """simple docstring""" if num <= 0: a =f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(lowercase ) a =[True] * (num + 1) a =[] a =2 a =int(math.sqrt(lowercase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(lowercase ) # Set multiples of start be False for i in range(start * start , num + 1 , lowercase ): if sieve[i] is True: a =False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(lowercase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
81
1
"""simple docstring""" from dataclasses import dataclass, field from typing import Optional @dataclass class __A : """simple docstring""" __lowerCAmelCase = field( default="codeparrot/codeparrot", metadata={"help": "Model name or path of model to be trained."} ) __lowerCAmelCase = field( default="./", metadata={"help": "Save dir where model repo is cloned and models updates are saved to."} ) __lowerCAmelCase = field( default="codeparrot/codeparrot-clean-train", metadata={"help": "Name or path of training dataset."} ) __lowerCAmelCase = field( default="codeparrot/codeparrot-clean-valid", metadata={"help": "Name or path of validation dataset."} ) __lowerCAmelCase = field(default=2, metadata={"help": "Batch size for training."} ) __lowerCAmelCase = field(default=2, metadata={"help": "Batch size for evaluation."} ) __lowerCAmelCase = field(default=0.1, metadata={"help": "Value of weight decay."} ) __lowerCAmelCase = field( default=10000, metadata={"help": "Size of buffer used to shuffle streaming dataset."} ) __lowerCAmelCase = field(default=2e-4, metadata={"help": "Learning rate fo training."} ) __lowerCAmelCase = field(default="cosine", metadata={"help": "Learning rate."} ) __lowerCAmelCase = field( default=750, metadata={"help": "Number of warmup steps in the learning rate schedule."} ) __lowerCAmelCase = field( default=16, metadata={"help": "Number of gradient accumulation steps."} ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Use gradient checkpointing to reduce memory footprint."} ) __lowerCAmelCase = field(default=50000, metadata={"help": "Maximum number of training steps."} ) __lowerCAmelCase = field( default=-1, metadata={"help": "Maximum number of evaluation steps. If -1 the full dataset is evaluated."} ) __lowerCAmelCase = field(default=1024, metadata={"help": "Sequence lengths used for training."} ) __lowerCAmelCase = field(default=1, metadata={"help": "Training seed."} ) __lowerCAmelCase = field( default=1024, metadata={"help": "Interval to save checkpoints. Measured as number of forward passes not training steps."}, ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "States path if the training should continue from a checkpoint folder."} ) __lowerCAmelCase = field(default=_SCREAMING_SNAKE_CASE, metadata={"help": "If True the data is pretokenized."} ) @dataclass class __A : """simple docstring""" __lowerCAmelCase = field( default="codeparrot/codeparrot", metadata={"help": "Model name or path of model to be evaluated."} ) __lowerCAmelCase = field( default="codeparrot/codeparrot-clean-valid", metadata={"help": "Name or path of validation dataset."} ) __lowerCAmelCase = field(default=2, metadata={"help": "Batch size used for evaluation."} ) __lowerCAmelCase = field( default=-1, metadata={"help": "Maximum number of evaluation steps. If -1 the full dataset is evaluated."} ) __lowerCAmelCase = field(default=1024, metadata={"help": "Length of sequences to be evaluated."} ) __lowerCAmelCase = field(default=1, metadata={"help": "Random seed used for evaluation."} ) @dataclass class __A : """simple docstring""" __lowerCAmelCase = field( default="codeparrot/codeparrot", metadata={"help": "Model name or path of model to be evaluated."} ) __lowerCAmelCase = field(default=_SCREAMING_SNAKE_CASE, metadata={"help": "Number of workers used for code evaluation."} ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The number of human-eval tasks to run. If not included all tasks are evaluated."}, ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Sample from the language model's output distribution."} ) __lowerCAmelCase = field(default=0.2, metadata={"help": "Sampling temperature used for generation."} ) __lowerCAmelCase = field(default=256, metadata={"help": "Maximum number of newly generated tokens."} ) __lowerCAmelCase = field(default=0, metadata={"help": "Top-k parameter used for generation."} ) __lowerCAmelCase = field(default=0.9_5, metadata={"help": "Top-p parameter used for nucleus sampling."} ) __lowerCAmelCase = field(default=10, metadata={"help": "Number of generations to run in parallel."} ) __lowerCAmelCase = field( default=200, metadata={"help": "Number of completions to generate for each sample."} ) __lowerCAmelCase = field(default=1, metadata={"help": "Random seed used for evaluation."} ) __lowerCAmelCase = field( default="eval_results.json", metadata={"help": "Random seed used for evaluation."} ) __lowerCAmelCase = field( default="0", metadata={"help": "Allow `code_eval` to execute Python code on machine"} ) __lowerCAmelCase = field( default=-1, metadata={ "help": ( "Determine which device to run the `text-generation` Pipeline on. -1 is CPU and any zero or positive" " number corresponds to which GPU device id to run on." ) }, ) @dataclass class __A : """simple docstring""" __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={ "help": "The number of CPU cores to use for parallel preprocessing. Default uses the maximum available." }, ) __lowerCAmelCase = field( default="transformersbook/codeparrot", metadata={"help": "Folder or name of dataset to process."} ) __lowerCAmelCase = field( default="codeparrot-clean", metadata={"help": "Folder to save processed processed dataset."} ) __lowerCAmelCase = field( default=100000, metadata={"help": "Number of files to save per JSON output file."} ) __lowerCAmelCase = field(default="content", metadata={"help": "Column containing text data to process."} ) __lowerCAmelCase = field( default=1000, metadata={"help": "Maximum line length in file, otherwise file is filtered."} ) __lowerCAmelCase = field( default=100, metadata={"help": "Maximum mean line length in file, otherwise file is filtered."} ) __lowerCAmelCase = field( default=0.2_5, metadata={"help": "Maximum fraction of non-alphanumeric characters, otherwise file is filtered."} ) __lowerCAmelCase = field( default=1.5, metadata={"help": "Minimum character token ratio for the file, otherwise file is filtered."} ) __lowerCAmelCase = field( default=0.7, metadata={"help": "Probability for filtering config, test and uncommon files."} ) __lowerCAmelCase = field( default="codeparrot/codeparrot", metadata={"help": "Name or path to the tokenizer."}, ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "If True, near-duplicate samples are removed."} ) __lowerCAmelCase = field( default=0.8_5, metadata={"help": "Jaccard threshold for near-duplicate samples."} ) @dataclass class __A : """simple docstring""" __lowerCAmelCase = field( default="gpt2", metadata={"help": "Base tokenizer to build new tokenizer from."} ) __lowerCAmelCase = field( default="transformersbook/codeparrot-train", metadata={"help": "Dataset to train tokenizer on."} ) __lowerCAmelCase = field(default="content", metadata={"help": "Column containing text data to process."} ) __lowerCAmelCase = field(default=200000, metadata={"help": "Number of examples to train tokenizer on."} ) __lowerCAmelCase = field( default=32768, metadata={"help": "Number of examples to train the tokenizer on."} ) __lowerCAmelCase = field(default="codeparrot", metadata={"help": "Name of new tokenizer."} ) __lowerCAmelCase = field(default=_SCREAMING_SNAKE_CASE, metadata={"help": "Push saved tokenizer to the hub."} ) @dataclass class __A : """simple docstring""" __lowerCAmelCase = field( default="codeparrot/codeparrot", metadata={"help": "Name or path to the tokenizer."} ) __lowerCAmelCase = field( default="codeparrot/codeparrot-clean-train", metadata={"help": "Name or path to the dataset to pretokenize."} ) __lowerCAmelCase = field( default="tokenized-codeparrot-train", metadata={"help": "Repo name of the pretokenized data."} ) __lowerCAmelCase = field(default=_SCREAMING_SNAKE_CASE, metadata={"help": "Number of workers used for code evaluation."} ) @dataclass class __A : """simple docstring""" __lowerCAmelCase = field( default="gpt2-large", metadata={"help": "Configuration to use for model initialization."} ) __lowerCAmelCase = field( default="codeparrot/codeparrot", metadata={"help": "Tokenizer attached to model."} ) __lowerCAmelCase = field(default="codeparrot", metadata={"help": "Name of the created model."} ) __lowerCAmelCase = field(default=_SCREAMING_SNAKE_CASE, metadata={"help": "Push saved tokenizer to the hub."} )
81
"""simple docstring""" 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 __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = BertTokenizer __lowerCAmelCase = BertTokenizerFast __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = filter_non_english def SCREAMING_SNAKE_CASE ( self ) -> List[str]: super().setUp() a =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a =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 SCREAMING_SNAKE_CASE ( self , __A ) -> Union[str, Any]: a ='''UNwant\u00E9d,running''' a ='''unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.tokenizer_class(self.vocab_file ) a =tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__A , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [9, 6, 7, 12, 10, 11] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: if not self.test_rust_tokenizer: return a =self.get_tokenizer() a =self.get_rust_tokenizer() a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) # With lower casing a =self.get_tokenizer(do_lower_case=__A ) a =self.get_rust_tokenizer(do_lower_case=__A ) a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Any: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =BasicTokenizer(do_lower_case=__A , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =BasicTokenizer() a ='''a\n\'ll !!to?\'d of, can\'t.''' a =['''a''', '''\'''', '''ll''', '''!''', '''!''', '''to''', '''?''', '''\'''', '''d''', '''of''', ''',''', '''can''', '''\'''', '''t''', '''.'''] self.assertListEqual(tokenizer.tokenize(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a ={} for i, token in enumerate(__A ): a =i a =WordpieceTokenizer(vocab=__A , 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 SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE ( self ) -> Any: 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 SCREAMING_SNAKE_CASE ( self ) -> str: 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 SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.get_tokenizer() a =self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.tokenizer_class.from_pretrained('''bert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def SCREAMING_SNAKE_CASE ( self ) -> Any: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' a =tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) a =tokenizer_r.do_lower_case if hasattr(__A , '''do_lower_case''' ) else False a =( [ ((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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =['''的''', '''人''', '''有'''] a =''''''.join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =True a =self.tokenizer_class.from_pretrained(__A , **__A ) a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) a =False a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =self.tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". a =[ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A )
81
1
"""simple docstring""" lowerCamelCase_ : Any = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} lowerCamelCase_ : Optional[int] = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _A ( lowercase , lowercase , lowercase ): """simple docstring""" a =True a =[] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(lowercase , lowercase , lowercase ) order.append(lowercase ) return order def _A ( lowercase , lowercase , lowercase ): """simple docstring""" a =True a =[vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(lowercase , lowercase , lowercase ) return component def _A ( lowercase ): """simple docstring""" a =len(lowercase ) * [False] a ={vert: [] for vert in range(len(lowercase ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(lowercase ) a =[] for i, was_visited in enumerate(lowercase ): if not was_visited: order += topology_sort(lowercase , lowercase , lowercase ) a =[] a =len(lowercase ) * [False] for i in range(len(lowercase ) ): a =order[len(lowercase ) - i - 1] if not visited[vert]: a =find_components(lowercase , lowercase , lowercase ) components_list.append(lowercase ) return components_list
81
"""simple docstring""" import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ : Union[str, Any] = logging.get_logger(__name__) lowerCamelCase_ : Any = { """microsoft/conditional-detr-resnet-50""": ( """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json""" ), } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "conditional_detr" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , __A=True , __A=None , __A=3 , __A=300 , __A=6 , __A=2048 , __A=8 , __A=6 , __A=2048 , __A=8 , __A=0.0 , __A=0.0 , __A=True , __A="relu" , __A=256 , __A=0.1 , __A=0.0 , __A=0.0 , __A=0.02 , __A=1.0 , __A=False , __A="sine" , __A="resnet50" , __A=True , __A=False , __A=2 , __A=5 , __A=2 , __A=1 , __A=1 , __A=2 , __A=5 , __A=2 , __A=0.25 , **__A , ) -> List[Any]: if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) a =CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(__A , __A ): a =backbone_config.get('''model_type''' ) a =CONFIG_MAPPING[backbone_model_type] a =config_class.from_dict(__A ) a =use_timm_backbone a =backbone_config a =num_channels a =num_queries a =d_model a =encoder_ffn_dim a =encoder_layers a =encoder_attention_heads a =decoder_ffn_dim a =decoder_layers a =decoder_attention_heads a =dropout a =attention_dropout a =activation_dropout a =activation_function a =init_std a =init_xavier_std a =encoder_layerdrop a =decoder_layerdrop a =encoder_layers a =auxiliary_loss a =position_embedding_type a =backbone a =use_pretrained_backbone a =dilation # Hungarian matcher a =class_cost a =bbox_cost a =giou_cost # Loss coefficients a =mask_loss_coefficient a =dice_loss_coefficient a =cls_loss_coefficient a =bbox_loss_coefficient a =giou_loss_coefficient a =focal_alpha super().__init__(is_encoder_decoder=__A , **__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.d_model def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: a =self.backbone_config.to_dict() a =self.__class__.model_type return output class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def SCREAMING_SNAKE_CASE ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE ( self ) -> int: return 12
81
1
"""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 lowerCamelCase_ : Dict = logging.getLogger(__name__) lowerCamelCase_ : Tuple = """pytorch_model.bin""" @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co."}, ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the training data."} ) __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the data to predict on."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "A csv or a json file containing the validation data."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The name of the task to train on."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The list of labels for the task."} ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "The output directory where the model predictions and checkpoints will be written."} ) __lowerCAmelCase = dataclasses.field( default="accuracy", metadata={"help": "The evaluation metric used for the task."} ) __lowerCAmelCase = dataclasses.field( default="no", metadata={ "help": "The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]" }, ) __lowerCAmelCase = dataclasses.field( default=10, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={ "help": "How much the specified evaluation metric must improve to satisfy early stopping conditions." }, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the confidence score."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the validation performance."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to fine-tune on labeled data after pseudo training."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={"help": "Confidence threshold for pseudo-labeled data filtering."}, ) __lowerCAmelCase = dataclasses.field( default=100, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Random seed for initialization."}, ) def _A ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: a =dataset.filter(lambda lowercase : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 a =int(eval_result * len(lowercase ) ) print(lowercase ) a =dataset.sort('''probability''' , reverse=lowercase ) a =dataset.select(range(lowercase ) ) a =dataset.remove_columns(['''label''', '''probability'''] ) a =dataset.rename_column('''prediction''' , '''label''' ) a =dataset.map(lambda lowercase : {"label": idalabel[example["label"]]} ) a =dataset.shuffle(seed=args.seed ) a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(lowercase , index=lowercase ) else: dataset.to_json(lowercase ) def _A ( lowercase , lowercase , lowercase , lowercase , **lowercase ): """simple docstring""" a =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() a =STModelArguments(model_name_or_path=lowercase ) a =STDataArguments(train_file=lowercase , infer_file=lowercase ) a =STTrainingArguments(output_dir=lowercase ) a =argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(lowercase ).items(): setattr(lowercase , lowercase , lowercase ) for key, value in kwargs.items(): if hasattr(lowercase , lowercase ): setattr(lowercase , lowercase , lowercase ) # Sanity checks a ={} a =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 a =args.train_file a =args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None a =args.eval_file for key in data_files: a =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: a =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...''' ) a =f'''{args.output_dir}/self-train_iter-{{}}'''.format a =data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=lowercase ) os.makedirs(lowercase , exist_ok=lowercase ) accelerator.wait_for_everyone() a =None a =None a =0 a =False # Show the progress bar a =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 ) ): a =data_dir_format(lowercase ) assert os.path.exists(lowercase ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 a =os.path.join(lowercase , '''stage-1''' ) a ={ '''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(lowercase , lowercase ): arguments_dict.update({key: value} ) a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 1 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 1.''' , lowercase ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data a =os.path.join(lowercase , '''best-checkpoint''' ) a =os.path.join(lowercase , '''stage-2''' ) # Update arguments_dict a =model_path a =data_files['''train'''] a =current_output_dir a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 2 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 2.''' , lowercase ) a =iteration a =data_dir_format(iteration + 1 ) a =AutoConfig.from_pretrained(os.path.join(lowercase , '''best-checkpoint''' ) ) a =config.idalabel a =os.path.join(lowercase , '''eval_results_best-checkpoint.json''' ) a =os.path.join(lowercase , '''test_results_best-checkpoint.json''' ) assert os.path.exists(lowercase ) with open(lowercase , '''r''' ) as f: a =float(json.load(lowercase )[args.eval_metric] ) a =os.path.join(lowercase , '''infer_output_best-checkpoint.csv''' ) assert os.path.exists(lowercase ) # Loading the dataset from local csv or json files. a =load_dataset(args.data_file_extension , data_files={'''data''': data_files['''infer''']} )['''data'''] a =load_dataset('''csv''' , data_files={'''data''': infer_output_file} )['''data'''] if accelerator.is_main_process: os.makedirs(lowercase , exist_ok=lowercase ) shutil.copy(lowercase , os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(lowercase ): shutil.copy(lowercase , os.path.join(lowercase , f'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) accelerator.wait_for_everyone() a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: a =eval_result if best_iteration is None: a =new_iteration a =new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: a =new_iteration a =new_eval_result a =0 else: if new_eval_result == best_eval_result: a =new_iteration a =new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: a =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''' , lowercase ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) , os.path.join(lowercase , '''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 , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(lowercase , '''eval_results_best-iteration.json''' ) , )
81
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" while second != 0: a =first & second first ^= second a =c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase_ : Dict = int(input("""Enter the first number: """).strip()) lowerCamelCase_ : List[Any] = int(input("""Enter the second number: """).strip()) print(F'{add(first, second) = }')
81
1
"""simple docstring""" class __A : """simple docstring""" def __init__( self , __A ) -> None: a =len(__A ) a =[0] * len_array if len_array > 0: a =array[0] for i in range(1 , __A ): a =self.prefix_sum[i - 1] + array[i] def SCREAMING_SNAKE_CASE ( self , __A , __A ) -> int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def SCREAMING_SNAKE_CASE ( self , __A ) -> bool: a ={0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(__A ) return False if __name__ == "__main__": import doctest doctest.testmod()
81
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" a =ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' '''helper utility that will spawn up ''' '''multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=lowercase , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=lowercase , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=lowercase ) return parser.parse_args() def _A ( ): """simple docstring""" a =parse_args() # Import training_script as a module. a =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) a =script_fpath.stem a =importlib.import_module(lowercase ) # Patch sys.argv a =[args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
81
1
"""simple docstring""" from typing import Any class __A : """simple docstring""" def __init__( self , __A ) -> Union[str, Any]: a =data a =None class __A : """simple docstring""" def __init__( self ) -> List[str]: a =None def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.head while temp is not None: print(temp.data , end=''' ''' ) a =temp.next print() def SCREAMING_SNAKE_CASE ( self , __A ) -> Union[str, Any]: a =Node(__A ) a =self.head a =new_node def SCREAMING_SNAKE_CASE ( self , __A , __A ) -> str: if node_data_a == node_data_a: return else: a =self.head while node_a is not None and node_a.data != node_data_a: a =node_a.next a =self.head while node_a is not None and node_a.data != node_data_a: a =node_a.next if node_a is None or node_a is None: return a , a =node_a.data, node_a.data if __name__ == "__main__": lowerCamelCase_ : List[Any] = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print("""After swapping""") ll.print_list()
81
"""simple docstring""" import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor lowerCamelCase_ : str = logging.get_logger(__name__) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , *__A , **__A ) -> None: warnings.warn( '''The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use CLIPImageProcessor instead.''' , __A , ) super().__init__(*__A , **__A )
81
1
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" a =ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' '''helper utility that will spawn up ''' '''multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=lowercase , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=lowercase , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=lowercase ) return parser.parse_args() def _A ( ): """simple docstring""" a =parse_args() # Import training_script as a module. a =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) a =script_fpath.stem a =importlib.import_module(lowercase ) # Patch sys.argv a =[args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
81
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" return number | (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number & ~(1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number ^ (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return ((number >> position) & 1) == 1 def _A ( lowercase , lowercase ): """simple docstring""" return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
81
1
"""simple docstring""" import cva import numpy as np class __A : """simple docstring""" def __init__( self , __A , __A ) -> int: if k in (0.04, 0.06): a =k a =window_size else: raise ValueError('''invalid k value''' ) def __str__( self ) -> str: return str(self.k ) def SCREAMING_SNAKE_CASE ( self , __A ) -> tuple[cva.Mat, list[list[int]]]: a =cva.imread(__A , 0 ) a , a =img.shape a =[] a =img.copy() a =cva.cvtColor(__A , cva.COLOR_GRAY2RGB ) a , a =np.gradient(__A ) a =dx**2 a =dy**2 a =dx * dy a =0.04 a =self.window_size // 2 for y in range(__A , h - offset ): for x in range(__A , w - offset ): a =ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() a =iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() a =ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() a =(wxx * wyy) - (wxy**2) a =wxx + wyy a =det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 255 ) return color_img, corner_list if __name__ == "__main__": lowerCamelCase_ : List[Any] = HarrisCorner(0.04, 3) lowerCamelCase_ , lowerCamelCase_ : int = edge_detect.detect("""path_to_image""") cva.imwrite("""detect.png""", color_img)
81
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _A ( lowercase ): """simple docstring""" a =SwinvaConfig() a =swinva_name.split('''_''' ) a =name_split[1] if "to" in name_split[3]: a =int(name_split[3][-3:] ) else: a =int(name_split[3] ) if "to" in name_split[2]: a =int(name_split[2][-2:] ) else: a =int(name_split[2][6:] ) if model_size == "tiny": a =96 a =(2, 2, 6, 2) a =(3, 6, 12, 24) elif model_size == "small": a =96 a =(2, 2, 18, 2) a =(3, 6, 12, 24) elif model_size == "base": a =1_28 a =(2, 2, 18, 2) a =(4, 8, 16, 32) else: a =1_92 a =(2, 2, 18, 2) a =(6, 12, 24, 48) if "to" in swinva_name: a =(12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): a =2_18_41 a ='''huggingface/label-files''' a ='''imagenet-22k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} else: a =10_00 a ='''huggingface/label-files''' a ='''imagenet-1k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} a =img_size a =num_classes a =embed_dim a =depths a =num_heads a =window_size return config def _A ( lowercase ): """simple docstring""" if "patch_embed.proj" in name: a =name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: a =name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: a ='''encoder.''' + name if "attn.proj" in name: a =name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: a =name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: a =name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: a =name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: a =name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: a =name.replace('''mlp.fc2''' , '''output.dense''' ) if "q_bias" in name: a =name.replace('''q_bias''' , '''query.bias''' ) if "k_bias" in name: a =name.replace('''k_bias''' , '''key.bias''' ) if "v_bias" in name: a =name.replace('''v_bias''' , '''value.bias''' ) if "cpb_mlp" in name: a =name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' ) if name == "norm.weight": a ='''layernorm.weight''' if name == "norm.bias": a ='''layernorm.bias''' if "head" in name: a =name.replace('''head''' , '''classifier''' ) else: a ='''swinv2.''' + name return name def _A ( lowercase , lowercase ): """simple docstring""" for key in orig_state_dict.copy().keys(): a =orig_state_dict.pop(lowercase ) if "mask" in key: continue elif "qkv" in key: a =key.split('''.''' ) a =int(key_split[1] ) a =int(key_split[3] ) a =model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a =val[:dim, :] a =val[dim : dim * 2, :] a =val[-dim:, :] else: a =val[:dim] a =val[ dim : dim * 2 ] a =val[-dim:] else: a =val return orig_state_dict def _A ( lowercase , lowercase ): """simple docstring""" a =timm.create_model(lowercase , pretrained=lowercase ) timm_model.eval() a =get_swinva_config(lowercase ) a =SwinvaForImageClassification(lowercase ) model.eval() a =convert_state_dict(timm_model.state_dict() , lowercase ) model.load_state_dict(lowercase ) a ='''http://images.cocodataset.org/val2017/000000039769.jpg''' a =AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swinva_name.replace('''_''' , '''-''' ) ) ) a =Image.open(requests.get(lowercase , stream=lowercase ).raw ) a =image_processor(images=lowercase , return_tensors='''pt''' ) a =timm_model(inputs['''pixel_values'''] ) a =model(**lowercase ).logits assert torch.allclose(lowercase , lowercase , atol=1E-3 ) print(f'''Saving model {swinva_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) model.push_to_hub( repo_path_or_name=Path(lowercase , lowercase ) , organization='''nandwalritik''' , commit_message='''Add model''' , ) if __name__ == "__main__": lowerCamelCase_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swinv2_name""", default="""swinv2_tiny_patch4_window8_256""", type=str, help="""Name of the Swinv2 timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowerCamelCase_ : Union[str, Any] = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
81
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor lowerCamelCase_ : Union[str, Any] = logging.get_logger(__name__) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , *__A , **__A ) -> None: warnings.warn( '''The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use YolosImageProcessor instead.''' , __A , ) super().__init__(*__A , **__A )
81
"""simple docstring""" lowerCamelCase_ : Any = [ """DownloadConfig""", """DownloadManager""", """DownloadMode""", """StreamingDownloadManager""", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
81
1
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" assert x is not None assert y is not None a =len(lowercase ) a =len(lowercase ) # declaring the array for storing the dp values a =[[0] * (n + 1) for _ in range(m + 1 )] # noqa: E741 for i in range(1 , m + 1 ): for j in range(1 , n + 1 ): a =1 if x[i - 1] == y[j - 1] else 0 a =max(l[i - 1][j] , l[i][j - 1] , l[i - 1][j - 1] + match ) a ='''''' a , a =m, n while i > 0 and j > 0: a =1 if x[i - 1] == y[j - 1] else 0 if l[i][j] == l[i - 1][j - 1] + match: if match == 1: a =x[i - 1] + seq i -= 1 j -= 1 elif l[i][j] == l[i - 1][j]: i -= 1 else: j -= 1 return l[m][n], seq if __name__ == "__main__": lowerCamelCase_ : List[Any] = """AGGTAB""" lowerCamelCase_ : str = """GXTXAYB""" lowerCamelCase_ : Any = 4 lowerCamelCase_ : List[Any] = """GTAB""" lowerCamelCase_ , lowerCamelCase_ : Optional[Any] = longest_common_subsequence(a, b) print("""len =""", ln, """, sub-sequence =""", subseq) import doctest doctest.testmod()
81
"""simple docstring""" from scipy.stats import pearsonr import datasets lowerCamelCase_ : Optional[int] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ lowerCamelCase_ : Optional[Any] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ lowerCamelCase_ : Optional[int] = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Dict: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float''' ), '''references''': datasets.Value('''float''' ), } ) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A=False ) -> Optional[Any]: if return_pvalue: a =pearsonr(__A , __A ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(__A , __A )[0] )}
81
1
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" return int(input_a == input_a == 0 ) def _A ( ): """simple docstring""" print('''Truth Table of NOR Gate:''' ) print('''| Input 1 | Input 2 | Output |''' ) print(f'''| 0 | 0 | {nor_gate(0 , 0 )} |''' ) print(f'''| 0 | 1 | {nor_gate(0 , 1 )} |''' ) print(f'''| 1 | 0 | {nor_gate(1 , 0 )} |''' ) print(f'''| 1 | 1 | {nor_gate(1 , 1 )} |''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
81
"""simple docstring""" lowerCamelCase_ : int = """ # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git """ lowerCamelCase_ : Dict = [{"""type""": """code""", """content""": INSTALL_CONTENT}] lowerCamelCase_ : Union[str, Any] = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
81
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Optional[int] = { """vinvino02/glpn-kitti""": """https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json""", # See all GLPN models at https://huggingface.co/models?filter=glpn } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "glpn" def __init__( self , __A=3 , __A=4 , __A=[2, 2, 2, 2] , __A=[8, 4, 2, 1] , __A=[32, 64, 160, 256] , __A=[7, 3, 3, 3] , __A=[4, 2, 2, 2] , __A=[1, 2, 5, 8] , __A=[4, 4, 4, 4] , __A="gelu" , __A=0.0 , __A=0.0 , __A=0.02 , __A=0.1 , __A=1E-6 , __A=64 , __A=10 , __A=-1 , **__A , ) -> List[str]: super().__init__(**__A ) a =num_channels a =num_encoder_blocks a =depths a =sr_ratios a =hidden_sizes a =patch_sizes a =strides a =mlp_ratios a =num_attention_heads a =hidden_act a =hidden_dropout_prob a =attention_probs_dropout_prob a =initializer_range a =drop_path_rate a =layer_norm_eps a =decoder_hidden_size a =max_depth a =head_in_index
81
"""simple docstring""" def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =set() # Replace all the whitespace in our sentence a =input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowercase ) == 26 def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =[False] * 26 for char in input_str: if char.islower(): a =True elif char.isupper(): a =True return all(lowercase ) def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _A ( ): """simple docstring""" from timeit import timeit a ='''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowercase ) ) print(timeit('''is_pangram_faster()''' , setup=lowercase ) ) print(timeit('''is_pangram_fastest()''' , setup=lowercase ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
81
1
"""simple docstring""" import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() lowerCamelCase_ : List[Any] = logging.get_logger(__name__) lowerCamelCase_ : Tuple = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn.grep_linear""": """encoder.layers.*.attention.gru_rel_pos_linear""", """self_attn.relative_attention_bias""": """encoder.layers.*.attention.rel_attn_embed""", """self_attn.grep_a""": """encoder.layers.*.attention.gru_rel_pos_const""", """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""": """ctc_proj""", """mask_emb""": """masked_spec_embed""", } lowerCamelCase_ : Dict = [ """ctc_proj""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def _A ( lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" for attribute in key.split('''.''' ): a =getattr(lowercase , lowercase ) if weight_type is not None: a =getattr(lowercase , lowercase ).shape else: a =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": a =value elif weight_type == "weight_g": a =value elif weight_type == "weight_v": a =value elif weight_type == "bias": a =value else: a =value logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def _A ( lowercase , lowercase ): """simple docstring""" a =[] a =fairseq_model.state_dict() a =hf_model.feature_extractor for name, value in fairseq_dict.items(): a =False if "conv_layers" in name: load_conv_layer( lowercase , lowercase , lowercase , lowercase , hf_model.config.feat_extract_norm == '''group''' , ) a =True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: a =True if "*" in mapped_key: a =name.split(lowercase )[0].split('''.''' )[-2] a =mapped_key.replace('''*''' , lowercase ) if "weight_g" in name: a ='''weight_g''' elif "weight_v" in name: a ='''weight_v''' elif "bias" in name and "relative_attention_bias" not in name: a ='''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj a ='''weight''' else: a =None set_recursively(lowercase , lowercase , lowercase , lowercase , lowercase ) continue if not is_used: unused_weights.append(lowercase ) logger.warning(f'''Unused weights: {unused_weights}''' ) def _A ( lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =full_name.split('''conv_layers.''' )[-1] a =name.split('''.''' ) a =int(items[0] ) a =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.''' ) a =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.''' ) a =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." ) a =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.''' ) a =value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(lowercase ) @torch.no_grad() def _A ( lowercase , lowercase , lowercase=None ): """simple docstring""" # load the pre-trained checkpoints a =torch.load(lowercase ) a =WavLMConfigOrig(checkpoint['''cfg'''] ) a =WavLMOrig(lowercase ) model.load_state_dict(checkpoint['''model'''] ) model.eval() if config_path is not None: a =WavLMConfig.from_pretrained(lowercase ) else: a =WavLMConfig() a =WavLMModel(lowercase ) recursively_load_weights(lowercase , lowercase ) hf_wavlm.save_pretrained(lowercase ) if __name__ == "__main__": lowerCamelCase_ : int = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") lowerCamelCase_ : Tuple = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys lowerCamelCase_ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" import random class __A : """simple docstring""" @staticmethod def SCREAMING_SNAKE_CASE ( __A ) -> tuple[list[int], list[int]]: a =[ord(__A ) for i in text] a =[] a =[] for i in plain: a =random.randint(1 , 300 ) a =(i + k) * k cipher.append(__A ) key.append(__A ) return cipher, key @staticmethod def SCREAMING_SNAKE_CASE ( __A , __A ) -> str: a =[] for i in range(len(__A ) ): a =int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(__A ) ) return "".join(__A ) if __name__ == "__main__": lowerCamelCase_ , lowerCamelCase_ : Optional[int] = Onepad().encrypt("""Hello""") print(c, k) print(Onepad().decrypt(c, k))
81
"""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 lowerCamelCase_ : Dict = logging.getLogger(__name__) lowerCamelCase_ : Tuple = """pytorch_model.bin""" @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co."}, ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the training data."} ) __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the data to predict on."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "A csv or a json file containing the validation data."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The name of the task to train on."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The list of labels for the task."} ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "The output directory where the model predictions and checkpoints will be written."} ) __lowerCAmelCase = dataclasses.field( default="accuracy", metadata={"help": "The evaluation metric used for the task."} ) __lowerCAmelCase = dataclasses.field( default="no", metadata={ "help": "The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]" }, ) __lowerCAmelCase = dataclasses.field( default=10, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={ "help": "How much the specified evaluation metric must improve to satisfy early stopping conditions." }, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the confidence score."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the validation performance."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to fine-tune on labeled data after pseudo training."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={"help": "Confidence threshold for pseudo-labeled data filtering."}, ) __lowerCAmelCase = dataclasses.field( default=100, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Random seed for initialization."}, ) def _A ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: a =dataset.filter(lambda lowercase : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 a =int(eval_result * len(lowercase ) ) print(lowercase ) a =dataset.sort('''probability''' , reverse=lowercase ) a =dataset.select(range(lowercase ) ) a =dataset.remove_columns(['''label''', '''probability'''] ) a =dataset.rename_column('''prediction''' , '''label''' ) a =dataset.map(lambda lowercase : {"label": idalabel[example["label"]]} ) a =dataset.shuffle(seed=args.seed ) a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(lowercase , index=lowercase ) else: dataset.to_json(lowercase ) def _A ( lowercase , lowercase , lowercase , lowercase , **lowercase ): """simple docstring""" a =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() a =STModelArguments(model_name_or_path=lowercase ) a =STDataArguments(train_file=lowercase , infer_file=lowercase ) a =STTrainingArguments(output_dir=lowercase ) a =argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(lowercase ).items(): setattr(lowercase , lowercase , lowercase ) for key, value in kwargs.items(): if hasattr(lowercase , lowercase ): setattr(lowercase , lowercase , lowercase ) # Sanity checks a ={} a =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 a =args.train_file a =args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None a =args.eval_file for key in data_files: a =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: a =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...''' ) a =f'''{args.output_dir}/self-train_iter-{{}}'''.format a =data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=lowercase ) os.makedirs(lowercase , exist_ok=lowercase ) accelerator.wait_for_everyone() a =None a =None a =0 a =False # Show the progress bar a =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 ) ): a =data_dir_format(lowercase ) assert os.path.exists(lowercase ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 a =os.path.join(lowercase , '''stage-1''' ) a ={ '''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(lowercase , lowercase ): arguments_dict.update({key: value} ) a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 1 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 1.''' , lowercase ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data a =os.path.join(lowercase , '''best-checkpoint''' ) a =os.path.join(lowercase , '''stage-2''' ) # Update arguments_dict a =model_path a =data_files['''train'''] a =current_output_dir a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 2 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 2.''' , lowercase ) a =iteration a =data_dir_format(iteration + 1 ) a =AutoConfig.from_pretrained(os.path.join(lowercase , '''best-checkpoint''' ) ) a =config.idalabel a =os.path.join(lowercase , '''eval_results_best-checkpoint.json''' ) a =os.path.join(lowercase , '''test_results_best-checkpoint.json''' ) assert os.path.exists(lowercase ) with open(lowercase , '''r''' ) as f: a =float(json.load(lowercase )[args.eval_metric] ) a =os.path.join(lowercase , '''infer_output_best-checkpoint.csv''' ) assert os.path.exists(lowercase ) # Loading the dataset from local csv or json files. a =load_dataset(args.data_file_extension , data_files={'''data''': data_files['''infer''']} )['''data'''] a =load_dataset('''csv''' , data_files={'''data''': infer_output_file} )['''data'''] if accelerator.is_main_process: os.makedirs(lowercase , exist_ok=lowercase ) shutil.copy(lowercase , os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(lowercase ): shutil.copy(lowercase , os.path.join(lowercase , f'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) accelerator.wait_for_everyone() a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: a =eval_result if best_iteration is None: a =new_iteration a =new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: a =new_iteration a =new_eval_result a =0 else: if new_eval_result == best_eval_result: a =new_iteration a =new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: a =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''' , lowercase ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) , os.path.join(lowercase , '''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 , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(lowercase , '''eval_results_best-iteration.json''' ) , )
81
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : List[str] = {"""configuration_vit_msn""": ["""VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTMSNConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = [ """VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST""", """ViTMSNModel""", """ViTMSNForImageClassification""", """ViTMSNPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_msn import ( VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMSNForImageClassification, ViTMSNModel, ViTMSNPreTrainedModel, ) else: import sys lowerCamelCase_ : Union[str, Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
"""simple docstring""" def _A ( ): """simple docstring""" for n in range(1 , 1_00_00_00 ): yield n * (n + 1) // 2 def _A ( lowercase ): """simple docstring""" a =1 a =2 while i * i <= n: a =0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _A ( ): """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(lowercase ) > 5_00 ) if __name__ == "__main__": print(solution())
81
1
"""simple docstring""" from __future__ import annotations import math def _A ( lowercase ): """simple docstring""" if num <= 0: a =f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(lowercase ) a =[True] * (num + 1) a =[] a =2 a =int(math.sqrt(lowercase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(lowercase ) # Set multiples of start be False for i in range(start * start , num + 1 , lowercase ): if sieve[i] is True: a =False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(lowercase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
81
"""simple docstring""" from math import factorial def _A ( lowercase = 1_00 ): """simple docstring""" return sum(int(lowercase ) for x in str(factorial(lowercase ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
81
1
"""simple docstring""" import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset lowerCamelCase_ : str = random.Random() def _A ( lowercase , lowercase=1.0 , lowercase=None , lowercase=None ): """simple docstring""" if rng is None: a =global_rng a =[] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class __A ( unittest.TestCase ): """simple docstring""" def __init__( self , __A , __A=7 , __A=400 , __A=2000 , __A=2048 , __A=128 , __A=1 , __A=512 , __A=30 , __A=4_4100 , ) -> Tuple: a =parent a =batch_size a =min_seq_length a =max_seq_length a =(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) a =spectrogram_length a =feature_size a =num_audio_channels a =hop_length a =chunk_length a =sampling_rate def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def SCREAMING_SNAKE_CASE ( self , __A=False , __A=False ) -> Optional[Any]: def _flatten(__A ): return list(itertools.chain(*__A ) ) if equal_length: a =[floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size a =[ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: a =[np.asarray(__A ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = TvltFeatureExtractor def SCREAMING_SNAKE_CASE ( self ) -> Any: a =TvltFeatureExtractionTester(self ) def SCREAMING_SNAKE_CASE ( self ) -> Any: a =self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(__A , '''spectrogram_length''' ) ) self.assertTrue(hasattr(__A , '''feature_size''' ) ) self.assertTrue(hasattr(__A , '''num_audio_channels''' ) ) self.assertTrue(hasattr(__A , '''hop_length''' ) ) self.assertTrue(hasattr(__A , '''chunk_length''' ) ) self.assertTrue(hasattr(__A , '''sampling_rate''' ) ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: a =feat_extract_first.save_pretrained(__A )[0] check_json_file_has_correct_format(__A ) a =self.feature_extraction_class.from_pretrained(__A ) a =feat_extract_first.to_dict() a =feat_extract_second.to_dict() a =dict_first.pop('''mel_filters''' ) a =dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(__A , __A ) ) self.assertEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: a =os.path.join(__A , '''feat_extract.json''' ) feat_extract_first.to_json_file(__A ) a =self.feature_extraction_class.from_json_file(__A ) a =feat_extract_first.to_dict() a =feat_extract_second.to_dict() a =dict_first.pop('''mel_filters''' ) a =dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(__A , __A ) ) self.assertEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> int: # Initialize feature_extractor a =self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 a =[floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] a =[np.asarray(__A ) for speech_input in speech_inputs] # Test not batched input a =feature_extractor(np_speech_inputs[0] , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched a =feature_extractor(__A , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking a =feature_extractor( __A , return_tensors='''np''' , sampling_rate=4_4100 , mask_audio=__A ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. a =[floats_list((1, x) )[0] for x in (800, 800, 800)] a =np.asarray(__A ) a =feature_extractor(__A , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Union[str, Any]: a =load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech a =ds.sort('''id''' ).select(range(__A ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def SCREAMING_SNAKE_CASE ( self ) -> str: a =self._load_datasamples(1 ) a =TvltFeatureExtractor() a =feature_extractor(__A , return_tensors='''pt''' ).audio_values self.assertEquals(audio_values.shape , (1, 1, 192, 128) ) a =torch.tensor([[-0.3_032, -0.2_708], [-0.4_434, -0.4_007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , __A , atol=1E-4 ) )
81
"""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, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Optional[Any] = """▁""" lowerCamelCase_ : Union[str, Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : Any = { """vocab_file""": { """xlm-roberta-base""": """https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large""": """https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large-finetuned-conll02-dutch""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll02-spanish""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-english""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-german""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model""" ), } } lowerCamelCase_ : Tuple = { """xlm-roberta-base""": 5_1_2, """xlm-roberta-large""": 5_1_2, """xlm-roberta-large-finetuned-conll02-dutch""": 5_1_2, """xlm-roberta-large-finetuned-conll02-spanish""": 5_1_2, """xlm-roberta-large-finetuned-conll03-english""": 5_1_2, """xlm-roberta-large-finetuned-conll03-german""": 5_1_2, } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a =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 a ={'''<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 a =1 a =len(self.sp_model ) + self.fairseq_offset a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: a =self.__dict__.copy() a =None a =self.sp_model.serialized_model_proto() return state def __setstate__( self , __A ) -> List[Any]: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[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] @property def SCREAMING_SNAKE_CASE ( self ) -> List[str]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> int: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =self.sp_model.PieceToId(__A ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: a =''''''.join(__A ).replace(__A , ''' ''' ).strip() return out_string def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , '''wb''' ) as fi: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
1
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def _A ( ): """simple docstring""" a =ArgumentParser('''Accelerate CLI tool''' , usage='''accelerate <command> [<args>]''' , allow_abbrev=lowercase ) a =parser.add_subparsers(help='''accelerate command helpers''' ) # Register commands get_config_parser(subparsers=lowercase ) env_command_parser(subparsers=lowercase ) launch_command_parser(subparsers=lowercase ) tpu_command_parser(subparsers=lowercase ) test_command_parser(subparsers=lowercase ) # Let's go a =parser.parse_args() if not hasattr(lowercase , '''func''' ): parser.print_help() exit(1 ) # Run args.func(lowercase ) if __name__ == "__main__": main()
81
"""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, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Tuple = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : str = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } lowerCamelCase_ : Optional[int] = { """moussaKam/mbarthez""": 1_0_2_4, """moussaKam/barthez""": 1_0_2_4, """moussaKam/barthez-orangesum-title""": 1_0_2_4, } lowerCamelCase_ : Tuple = """▁""" class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =vocab_file a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a ={'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} a =len(self.sp_model ) - 1 a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[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] @property def SCREAMING_SNAKE_CASE ( self ) -> Any: return len(self.sp_model ) def SCREAMING_SNAKE_CASE ( self ) -> int: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Dict: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =self.sp_model.PieceToId(__A ) return spm_id if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Tuple: a =[] a ='''''' a =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__A ) + token a =True a =[] else: current_sub_tokens.append(__A ) a =False out_string += self.sp_model.decode(__A ) return out_string.strip() def __getstate__( self ) -> Tuple: a =self.__dict__.copy() a =None return state def __setstate__( self , __A ) -> Tuple: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , '''wb''' ) as fi: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
1
"""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 __A : """simple docstring""" def __init__( self , __A , __A=13 , __A=7 , __A=True , __A=True , __A=True , __A=True , __A=99 , __A=24 , __A=2 , __A=6 , __A=37 , __A="gelu" , __A=0.1 , __A=0.1 , __A=512 , __A=16 , __A=2 , __A=0.02 , __A=3 , __A=None , __A=1000 , ) -> str: a =parent a =batch_size a =seq_length a =is_training a =use_input_mask a =use_token_type_ids a =use_labels a =vocab_size a =hidden_size a =num_hidden_layers a =num_attention_heads a =intermediate_size a =hidden_act a =hidden_dropout_prob a =attention_probs_dropout_prob a =max_position_embeddings a =type_vocab_size a =type_sequence_label_size a =initializer_range a =num_labels a =scope a =range_bbox def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a =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]: a =bbox[i, j, 3] a =bbox[i, j, 1] a =t if bbox[i, j, 2] < bbox[i, j, 0]: a =bbox[i, j, 2] a =bbox[i, j, 0] a =t a =None if self.use_input_mask: a =ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) a =None if self.use_token_type_ids: a =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a =None a =None if self.use_labels: a =ids_tensor([self.batch_size] , self.type_sequence_label_size ) a =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a =self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def SCREAMING_SNAKE_CASE ( self ) -> Tuple: 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 SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A , ) -> Any: a =LiltModel(config=__A ) model.to(__A ) model.eval() a =model(__A , bbox=__A , attention_mask=__A , token_type_ids=__A ) a =model(__A , bbox=__A , token_type_ids=__A ) a =model(__A , bbox=__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A , ) -> List[str]: a =self.num_labels a =LiltForTokenClassification(config=__A ) model.to(__A ) model.eval() a =model( __A , bbox=__A , attention_mask=__A , token_type_ids=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A , ) -> Any: a =LiltForQuestionAnswering(config=__A ) model.to(__A ) model.eval() a =model( __A , bbox=__A , attention_mask=__A , token_type_ids=__A , start_positions=__A , end_positions=__A , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) =config_and_inputs a ={ '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class __A ( _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __lowerCAmelCase = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __lowerCAmelCase = False __lowerCAmelCase = False def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A ) -> Any: return True def SCREAMING_SNAKE_CASE ( self ) -> Any: a =LiltModelTester(self ) a =ConfigTester(self , config_class=__A , hidden_size=37 ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a =type self.model_tester.create_and_check_model(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__A ) @slow def SCREAMING_SNAKE_CASE ( self ) -> str: for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a =LiltModel.from_pretrained(__A ) self.assertIsNotNone(__A ) @require_torch @slow class __A ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''' ).to(__A ) a =torch.tensor([[1, 2]] , device=__A ) a =torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=__A ) # forward pass with torch.no_grad(): a =model(input_ids=__A , bbox=__A ) a =torch.Size([1, 2, 768] ) a =torch.tensor( [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]] , device=__A , ) self.assertTrue(outputs.last_hidden_state.shape , __A ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , __A , atol=1E-3 ) )
81
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) lowerCamelCase_ : Tuple = logging.get_logger(__name__) lowerCamelCase_ : str = OrderedDict( [ ("""align""", """EfficientNetImageProcessor"""), ("""beit""", """BeitImageProcessor"""), ("""bit""", """BitImageProcessor"""), ("""blip""", """BlipImageProcessor"""), ("""blip-2""", """BlipImageProcessor"""), ("""bridgetower""", """BridgeTowerImageProcessor"""), ("""chinese_clip""", """ChineseCLIPImageProcessor"""), ("""clip""", """CLIPImageProcessor"""), ("""clipseg""", """ViTImageProcessor"""), ("""conditional_detr""", """ConditionalDetrImageProcessor"""), ("""convnext""", """ConvNextImageProcessor"""), ("""convnextv2""", """ConvNextImageProcessor"""), ("""cvt""", """ConvNextImageProcessor"""), ("""data2vec-vision""", """BeitImageProcessor"""), ("""deformable_detr""", """DeformableDetrImageProcessor"""), ("""deit""", """DeiTImageProcessor"""), ("""deta""", """DetaImageProcessor"""), ("""detr""", """DetrImageProcessor"""), ("""dinat""", """ViTImageProcessor"""), ("""donut-swin""", """DonutImageProcessor"""), ("""dpt""", """DPTImageProcessor"""), ("""efficientformer""", """EfficientFormerImageProcessor"""), ("""efficientnet""", """EfficientNetImageProcessor"""), ("""flava""", """FlavaImageProcessor"""), ("""focalnet""", """BitImageProcessor"""), ("""git""", """CLIPImageProcessor"""), ("""glpn""", """GLPNImageProcessor"""), ("""groupvit""", """CLIPImageProcessor"""), ("""imagegpt""", """ImageGPTImageProcessor"""), ("""instructblip""", """BlipImageProcessor"""), ("""layoutlmv2""", """LayoutLMv2ImageProcessor"""), ("""layoutlmv3""", """LayoutLMv3ImageProcessor"""), ("""levit""", """LevitImageProcessor"""), ("""mask2former""", """Mask2FormerImageProcessor"""), ("""maskformer""", """MaskFormerImageProcessor"""), ("""mgp-str""", """ViTImageProcessor"""), ("""mobilenet_v1""", """MobileNetV1ImageProcessor"""), ("""mobilenet_v2""", """MobileNetV2ImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevitv2""", """MobileViTImageProcessor"""), ("""nat""", """ViTImageProcessor"""), ("""oneformer""", """OneFormerImageProcessor"""), ("""owlvit""", """OwlViTImageProcessor"""), ("""perceiver""", """PerceiverImageProcessor"""), ("""pix2struct""", """Pix2StructImageProcessor"""), ("""poolformer""", """PoolFormerImageProcessor"""), ("""regnet""", """ConvNextImageProcessor"""), ("""resnet""", """ConvNextImageProcessor"""), ("""sam""", """SamImageProcessor"""), ("""segformer""", """SegformerImageProcessor"""), ("""swiftformer""", """ViTImageProcessor"""), ("""swin""", """ViTImageProcessor"""), ("""swin2sr""", """Swin2SRImageProcessor"""), ("""swinv2""", """ViTImageProcessor"""), ("""table-transformer""", """DetrImageProcessor"""), ("""timesformer""", """VideoMAEImageProcessor"""), ("""tvlt""", """TvltImageProcessor"""), ("""upernet""", """SegformerImageProcessor"""), ("""van""", """ConvNextImageProcessor"""), ("""videomae""", """VideoMAEImageProcessor"""), ("""vilt""", """ViltImageProcessor"""), ("""vit""", """ViTImageProcessor"""), ("""vit_hybrid""", """ViTHybridImageProcessor"""), ("""vit_mae""", """ViTImageProcessor"""), ("""vit_msn""", """ViTImageProcessor"""), ("""xclip""", """CLIPImageProcessor"""), ("""yolos""", """YolosImageProcessor"""), ] ) lowerCamelCase_ : Union[str, Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def _A ( lowercase ): """simple docstring""" for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: a =model_type_to_module_name(lowercase ) a =importlib.import_module(f'''.{module_name}''' , '''transformers.models''' ) try: return getattr(lowercase , lowercase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowercase , '''__name__''' , lowercase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. a =importlib.import_module('''transformers''' ) if hasattr(lowercase , lowercase ): return getattr(lowercase , lowercase ) return None def _A ( lowercase , lowercase = None , lowercase = False , lowercase = False , lowercase = None , lowercase = None , lowercase = None , lowercase = False , **lowercase , ): """simple docstring""" a =get_file_from_repo( lowercase , lowercase , cache_dir=lowercase , force_download=lowercase , resume_download=lowercase , proxies=lowercase , use_auth_token=lowercase , revision=lowercase , local_files_only=lowercase , ) if resolved_config_file is None: logger.info( '''Could not locate the image processor configuration file, will try to use the model config instead.''' ) return {} with open(lowercase , encoding='''utf-8''' ) as reader: return json.load(lowercase ) class __A : """simple docstring""" def __init__( self ) -> Optional[Any]: raise EnvironmentError( '''AutoImageProcessor is designed to be instantiated ''' '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__A ) def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> Dict: a =kwargs.pop('''config''' , __A ) a =kwargs.pop('''trust_remote_code''' , __A ) a =True a , a =ImageProcessingMixin.get_image_processor_dict(__A , **__A ) a =config_dict.get('''image_processor_type''' , __A ) a =None if "AutoImageProcessor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoImageProcessor'''] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: a =config_dict.pop('''feature_extractor_type''' , __A ) if feature_extractor_class is not None: logger.warning( '''Could not find image processor class in the image processor config or the model config. Loading''' ''' based on pattern matching with the model\'s feature extractor configuration.''' ) a =feature_extractor_class.replace('''FeatureExtractor''' , '''ImageProcessor''' ) if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoFeatureExtractor'''] a =feature_extractor_auto_map.replace('''FeatureExtractor''' , '''ImageProcessor''' ) logger.warning( '''Could not find image processor auto map in the image processor config or the model config.''' ''' Loading based on pattern matching with the model\'s feature extractor configuration.''' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(__A , __A ): a =AutoConfig.from_pretrained(__A , **__A ) # It could be in `config.image_processor_type`` a =getattr(__A , '''image_processor_type''' , __A ) if hasattr(__A , '''auto_map''' ) and "AutoImageProcessor" in config.auto_map: a =config.auto_map['''AutoImageProcessor'''] if image_processor_class is not None: a =image_processor_class_from_name(__A ) a =image_processor_auto_map is not None a =image_processor_class is not None or type(__A ) in IMAGE_PROCESSOR_MAPPING a =resolve_trust_remote_code( __A , __A , __A , __A ) if has_remote_code and trust_remote_code: a =get_class_from_dynamic_module( __A , __A , **__A ) a =kwargs.pop('''code_revision''' , __A ) if os.path.isdir(__A ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(__A , **__A ) elif image_processor_class is not None: return image_processor_class.from_dict(__A , **__A ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(__A ) in IMAGE_PROCESSOR_MAPPING: a =IMAGE_PROCESSOR_MAPPING[type(__A )] return image_processor_class.from_dict(__A , **__A ) raise ValueError( f'''Unrecognized image processor in {pretrained_model_name_or_path}. Should have a ''' f'''`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def SCREAMING_SNAKE_CASE ( __A , __A ) -> Any: IMAGE_PROCESSOR_MAPPING.register(__A , __A )
81
1
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" return "\n".join( f'''{number} * {i} = {number * i}''' for i in range(1 , number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=1_0))
81
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = DistilBertTokenizer __lowerCAmelCase = DistilBertTokenizerFast __lowerCAmelCase = True @slow def SCREAMING_SNAKE_CASE ( self ) -> int: a =DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
81
1
"""simple docstring""" def _A ( lowercase = 1_00 ): """simple docstring""" a =(n * (n + 1) // 2) ** 2 a =n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(F'{solution() = }')
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCamelCase_ : List[str] = { """configuration_speech_to_text""": ["""SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Speech2TextConfig"""], """processing_speech_to_text""": ["""Speech2TextProcessor"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""Speech2TextTokenizer"""] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[Any] = ["""Speech2TextFeatureExtractor"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFSpeech2TextForConditionalGeneration""", """TFSpeech2TextModel""", """TFSpeech2TextPreTrainedModel""", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = [ """SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Speech2TextForConditionalGeneration""", """Speech2TextModel""", """Speech2TextPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets lowerCamelCase_ : Optional[int] = """\ @inproceedings{wang2019glue, title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding}, author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.}, note={In the Proceedings of ICLR.}, year={2019} } """ lowerCamelCase_ : List[Any] = """\ GLUE, the General Language Understanding Evaluation benchmark (https://gluebenchmark.com/) is a collection of resources for training, evaluating, and analyzing natural language understanding systems. """ lowerCamelCase_ : List[Any] = """ Compute GLUE evaluation metric associated to each GLUE dataset. Args: predictions: list of predictions to score. Each translation should be tokenized into a list of tokens. references: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. Returns: depending on the GLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"pearson\": Pearson Correlation \"spearmanr\": Spearman Correlation \"matthews_correlation\": Matthew Correlation Examples: >>> glue_metric = datasets.load_metric('glue', 'sst2') # 'sst2' or any of [\"mnli\", \"mnli_mismatched\", \"mnli_matched\", \"qnli\", \"rte\", \"wnli\", \"hans\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> glue_metric = datasets.load_metric('glue', 'mrpc') # 'mrpc' or 'qqp' >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> glue_metric = datasets.load_metric('glue', 'stsb') >>> references = [0., 1., 2., 3., 4., 5.] >>> predictions = [0., 1., 2., 3., 4., 5.] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print({\"pearson\": round(results[\"pearson\"], 2), \"spearmanr\": round(results[\"spearmanr\"], 2)}) {'pearson': 1.0, 'spearmanr': 1.0} >>> glue_metric = datasets.load_metric('glue', 'cola') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'matthews_correlation': 1.0} """ def _A ( lowercase , lowercase ): """simple docstring""" return float((preds == labels).mean() ) def _A ( lowercase , lowercase ): """simple docstring""" a =simple_accuracy(lowercase , lowercase ) a =float(fa_score(y_true=lowercase , y_pred=lowercase ) ) return { "accuracy": acc, "f1": fa, } def _A ( lowercase , lowercase ): """simple docstring""" a =float(pearsonr(lowercase , lowercase )[0] ) a =float(spearmanr(lowercase , lowercase )[0] ) return { "pearson": pearson_corr, "spearmanr": spearman_corr, } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: if self.config_name not in [ "sst2", "mnli", "mnli_mismatched", "mnli_matched", "cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", ''' '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ), '''references''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ), } ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' , ) def SCREAMING_SNAKE_CASE ( self , __A , __A ) -> Dict: if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(__A , __A )} elif self.config_name == "stsb": return pearson_and_spearman(__A , __A ) elif self.config_name in ["mrpc", "qqp"]: return acc_and_fa(__A , __A ) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(__A , __A )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", ''' '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' )
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : Union[str, Any] = { """configuration_table_transformer""": [ """TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TableTransformerConfig""", """TableTransformerOnnxConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TableTransformerForObjectDetection""", """TableTransformerModel""", """TableTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" def _A ( lowercase , lowercase , lowercase ): """simple docstring""" def count_of_possible_combinations(lowercase ) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item ) for item in array ) return count_of_possible_combinations(lowercase ) def _A ( lowercase , lowercase , lowercase ): """simple docstring""" def count_of_possible_combinations_with_dp_array( lowercase , lowercase ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] a =sum( count_of_possible_combinations_with_dp_array(target - item , lowercase ) for item in array ) a =answer return answer a =[-1] * (target + 1) return count_of_possible_combinations_with_dp_array(lowercase , lowercase ) def _A ( lowercase , lowercase , lowercase ): """simple docstring""" a =[0] * (target + 1) a =1 for i in range(1 , target + 1 ): for j in range(lowercase ): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase_ : List[Any] = 3 lowerCamelCase_ : List[Any] = 5 lowerCamelCase_ : Optional[int] = [1, 2, 5] print(combination_sum_iv(n, array, target))
81
"""simple docstring""" from __future__ import annotations import math def _A ( lowercase ): """simple docstring""" if num <= 0: a =f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(lowercase ) a =[True] * (num + 1) a =[] a =2 a =int(math.sqrt(lowercase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(lowercase ) # Set multiples of start be False for i in range(start * start , num + 1 , lowercase ): if sieve[i] is True: a =False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(lowercase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
81
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ : Dict = logging.get_logger(__name__) lowerCamelCase_ : List[Any] = { """google/switch-base-8""": """https://huggingface.co/google/switch-base-8/blob/main/config.json""", } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "switch_transformers" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self , __A=3_2128 , __A=768 , __A=64 , __A=2048 , __A=64 , __A=12 , __A=3 , __A=12 , __A=3 , __A=12 , __A=8 , __A=False , __A=0.01 , __A="float32" , __A=False , __A=32 , __A=128 , __A=0.1 , __A=1E-6 , __A=0.001 , __A=0.001 , __A=1.0 , __A="relu" , __A=True , __A=False , __A=True , __A=0 , __A=1 , **__A , ) -> List[Any]: a =vocab_size a =d_model a =d_kv a =d_ff a =num_sparse_encoder_layers a =num_layers a =( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a =num_sparse_decoder_layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_encoder_layers > 0: a =self.num_layers // self.num_sparse_encoder_layers else: a =self.num_layers # HACK: this will create 0 sparse layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_decoder_layers > 0: a =self.num_decoder_layers // self.num_sparse_decoder_layers else: a =self.num_decoder_layers # HACK: this will create 0 sparse layers a =num_heads a =num_experts a =expert_capacity a =router_bias a =router_jitter_noise if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f'''`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}''' ) a =router_dtype a =router_ignore_padding_tokens a =relative_attention_num_buckets a =relative_attention_max_distance a =dropout_rate a =layer_norm_epsilon a =initializer_factor a =feed_forward_proj a =use_cache a =add_router_probs a =router_z_loss_coef a =router_aux_loss_coef a =self.feed_forward_proj.split('''-''' ) a =act_info[-1] a =act_info[0] == '''gated''' if len(__A ) > 1 and act_info[0] != "gated" or len(__A ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ''' '''\'gated-gelu\' or \'relu\'''' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": a ='''gelu_new''' super().__init__( pad_token_id=__A , eos_token_id=__A , is_encoder_decoder=__A , **__A , )
81
"""simple docstring""" 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 __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = BertTokenizer __lowerCAmelCase = BertTokenizerFast __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = filter_non_english def SCREAMING_SNAKE_CASE ( self ) -> List[str]: super().setUp() a =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a =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 SCREAMING_SNAKE_CASE ( self , __A ) -> Union[str, Any]: a ='''UNwant\u00E9d,running''' a ='''unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.tokenizer_class(self.vocab_file ) a =tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__A , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [9, 6, 7, 12, 10, 11] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: if not self.test_rust_tokenizer: return a =self.get_tokenizer() a =self.get_rust_tokenizer() a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) # With lower casing a =self.get_tokenizer(do_lower_case=__A ) a =self.get_rust_tokenizer(do_lower_case=__A ) a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Any: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =BasicTokenizer(do_lower_case=__A , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =BasicTokenizer() a ='''a\n\'ll !!to?\'d of, can\'t.''' a =['''a''', '''\'''', '''ll''', '''!''', '''!''', '''to''', '''?''', '''\'''', '''d''', '''of''', ''',''', '''can''', '''\'''', '''t''', '''.'''] self.assertListEqual(tokenizer.tokenize(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a ={} for i, token in enumerate(__A ): a =i a =WordpieceTokenizer(vocab=__A , 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 SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE ( self ) -> Any: 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 SCREAMING_SNAKE_CASE ( self ) -> str: 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 SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.get_tokenizer() a =self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.tokenizer_class.from_pretrained('''bert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def SCREAMING_SNAKE_CASE ( self ) -> Any: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' a =tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) a =tokenizer_r.do_lower_case if hasattr(__A , '''do_lower_case''' ) else False a =( [ ((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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =['''的''', '''人''', '''有'''] a =''''''.join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =True a =self.tokenizer_class.from_pretrained(__A , **__A ) a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) a =False a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =self.tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". a =[ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A )
81
1
"""simple docstring""" import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import evaluate import numpy as np from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("""4.31.0""") require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/text-classification/requirements.txt""") lowerCamelCase_ : List[Any] = logging.getLogger(__name__) @dataclass class __A : """simple docstring""" __lowerCAmelCase = field( default=128, metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) }, ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) }, ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) }, ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) }, ) @dataclass class __A : """simple docstring""" __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Evaluation language. Also train language if `train_language` is set to None."} ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Train language if it is different from the evaluation language."} ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"}, ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}, ) __lowerCAmelCase = field( default="main", metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) }, ) __lowerCAmelCase = field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."}, ) def _A ( ): """simple docstring""" # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. a =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) a , a , a =parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_xnli''' , lowercase ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() a =training_args.get_process_log_level() logger.setLevel(lowercase ) datasets.utils.logging.set_verbosity(lowercase ) transformers.utils.logging.set_verbosity(lowercase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + f'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(f'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. a =None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: a =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.''' ) # Set seed before initializing model. set_seed(training_args.seed ) # In distributed training, the load_dataset function guarantees that only one local process can concurrently # download the dataset. # Downloading and loading xnli dataset from the hub. if training_args.do_train: if model_args.train_language is None: a =load_dataset( '''xnli''' , model_args.language , split='''train''' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: a =load_dataset( '''xnli''' , model_args.train_language , split='''train''' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) a =train_dataset.features['''label'''].names if training_args.do_eval: a =load_dataset( '''xnli''' , model_args.language , split='''validation''' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) a =eval_dataset.features['''label'''].names if training_args.do_predict: a =load_dataset( '''xnli''' , model_args.language , split='''test''' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) a =predict_dataset.features['''label'''].names # Labels a =len(lowercase ) # Load pretrained model and tokenizer # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. a =AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowercase , idalabel={str(lowercase ): label for i, label in enumerate(lowercase )} , labelaid={label: i for i, label in enumerate(lowercase )} , finetuning_task='''xnli''' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) a =AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) a =AutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=lowercase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # Preprocessing the datasets # Padding strategy if data_args.pad_to_max_length: a ='''max_length''' else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch a =False def preprocess_function(lowercase ): # Tokenize the texts return tokenizer( examples['''premise'''] , examples['''hypothesis'''] , padding=lowercase , max_length=data_args.max_seq_length , truncation=lowercase , ) if training_args.do_train: if data_args.max_train_samples is not None: a =min(len(lowercase ) , data_args.max_train_samples ) a =train_dataset.select(range(lowercase ) ) with training_args.main_process_first(desc='''train dataset map pre-processing''' ): a =train_dataset.map( lowercase , batched=lowercase , load_from_cache_file=not data_args.overwrite_cache , desc='''Running tokenizer on train dataset''' , ) # Log a few random samples from the training set: for index in random.sample(range(len(lowercase ) ) , 3 ): logger.info(f'''Sample {index} of the training set: {train_dataset[index]}.''' ) if training_args.do_eval: if data_args.max_eval_samples is not None: a =min(len(lowercase ) , data_args.max_eval_samples ) a =eval_dataset.select(range(lowercase ) ) with training_args.main_process_first(desc='''validation dataset map pre-processing''' ): a =eval_dataset.map( lowercase , batched=lowercase , load_from_cache_file=not data_args.overwrite_cache , desc='''Running tokenizer on validation dataset''' , ) if training_args.do_predict: if data_args.max_predict_samples is not None: a =min(len(lowercase ) , data_args.max_predict_samples ) a =predict_dataset.select(range(lowercase ) ) with training_args.main_process_first(desc='''prediction dataset map pre-processing''' ): a =predict_dataset.map( lowercase , batched=lowercase , load_from_cache_file=not data_args.overwrite_cache , desc='''Running tokenizer on prediction dataset''' , ) # Get the metric function a =evaluate.load('''xnli''' ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(lowercase ): a =p.predictions[0] if isinstance(p.predictions , lowercase ) else p.predictions a =np.argmax(lowercase , axis=1 ) return metric.compute(predictions=lowercase , references=p.label_ids ) # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: a =default_data_collator elif training_args.fpaa: a =DataCollatorWithPadding(lowercase , pad_to_multiple_of=8 ) else: a =None # Initialize our Trainer a =Trainer( model=lowercase , args=lowercase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=lowercase , tokenizer=lowercase , data_collator=lowercase , ) # Training if training_args.do_train: a =None if training_args.resume_from_checkpoint is not None: a =training_args.resume_from_checkpoint elif last_checkpoint is not None: a =last_checkpoint a =trainer.train(resume_from_checkpoint=lowercase ) a =train_result.metrics a =( data_args.max_train_samples if data_args.max_train_samples is not None else len(lowercase ) ) a =min(lowercase , len(lowercase ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics('''train''' , lowercase ) trainer.save_metrics('''train''' , lowercase ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) a =trainer.evaluate(eval_dataset=lowercase ) a =data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowercase ) a =min(lowercase , len(lowercase ) ) trainer.log_metrics('''eval''' , lowercase ) trainer.save_metrics('''eval''' , lowercase ) # Prediction if training_args.do_predict: logger.info('''*** Predict ***''' ) a , a , a =trainer.predict(lowercase , metric_key_prefix='''predict''' ) a =( data_args.max_predict_samples if data_args.max_predict_samples is not None else len(lowercase ) ) a =min(lowercase , len(lowercase ) ) trainer.log_metrics('''predict''' , lowercase ) trainer.save_metrics('''predict''' , lowercase ) a =np.argmax(lowercase , axis=1 ) a =os.path.join(training_args.output_dir , '''predictions.txt''' ) if trainer.is_world_process_zero(): with open(lowercase , '''w''' ) as writer: writer.write('''index\tprediction\n''' ) for index, item in enumerate(lowercase ): a =label_list[item] writer.write(f'''{index}\t{item}\n''' ) if __name__ == "__main__": main()
81
"""simple docstring""" import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ : Union[str, Any] = logging.get_logger(__name__) lowerCamelCase_ : Any = { """microsoft/conditional-detr-resnet-50""": ( """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json""" ), } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "conditional_detr" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , __A=True , __A=None , __A=3 , __A=300 , __A=6 , __A=2048 , __A=8 , __A=6 , __A=2048 , __A=8 , __A=0.0 , __A=0.0 , __A=True , __A="relu" , __A=256 , __A=0.1 , __A=0.0 , __A=0.0 , __A=0.02 , __A=1.0 , __A=False , __A="sine" , __A="resnet50" , __A=True , __A=False , __A=2 , __A=5 , __A=2 , __A=1 , __A=1 , __A=2 , __A=5 , __A=2 , __A=0.25 , **__A , ) -> List[Any]: if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) a =CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(__A , __A ): a =backbone_config.get('''model_type''' ) a =CONFIG_MAPPING[backbone_model_type] a =config_class.from_dict(__A ) a =use_timm_backbone a =backbone_config a =num_channels a =num_queries a =d_model a =encoder_ffn_dim a =encoder_layers a =encoder_attention_heads a =decoder_ffn_dim a =decoder_layers a =decoder_attention_heads a =dropout a =attention_dropout a =activation_dropout a =activation_function a =init_std a =init_xavier_std a =encoder_layerdrop a =decoder_layerdrop a =encoder_layers a =auxiliary_loss a =position_embedding_type a =backbone a =use_pretrained_backbone a =dilation # Hungarian matcher a =class_cost a =bbox_cost a =giou_cost # Loss coefficients a =mask_loss_coefficient a =dice_loss_coefficient a =cls_loss_coefficient a =bbox_loss_coefficient a =giou_loss_coefficient a =focal_alpha super().__init__(is_encoder_decoder=__A , **__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.d_model def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: a =self.backbone_config.to_dict() a =self.__class__.model_type return output class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def SCREAMING_SNAKE_CASE ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE ( self ) -> int: return 12
81
1
"""simple docstring""" import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class __A ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =inspect.getfile(accelerate.test_utils ) a =os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) a =os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] ) @require_tpu def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =f''' {self.test_dir}/xla_spawn.py --num_cores 8 {self.test_file_path} '''.split() a =[sys.executable] + distributed_args execute_subprocess_async(__A , env=os.environ.copy() )
81
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" while second != 0: a =first & second first ^= second a =c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase_ : Dict = int(input("""Enter the first number: """).strip()) lowerCamelCase_ : List[Any] = int(input("""Enter the second number: """).strip()) print(F'{add(first, second) = }')
81
1
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ : List[Any] = logging.get_logger(__name__) lowerCamelCase_ : Dict = { """SenseTime/deformable-detr""": """https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json""", # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "deformable_detr" __lowerCAmelCase = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , __A=True , __A=None , __A=3 , __A=300 , __A=1024 , __A=6 , __A=1024 , __A=8 , __A=6 , __A=1024 , __A=8 , __A=0.0 , __A=True , __A="relu" , __A=256 , __A=0.1 , __A=0.0 , __A=0.0 , __A=0.02 , __A=1.0 , __A=True , __A=False , __A="sine" , __A="resnet50" , __A=True , __A=False , __A=4 , __A=4 , __A=4 , __A=False , __A=300 , __A=False , __A=1 , __A=5 , __A=2 , __A=1 , __A=1 , __A=5 , __A=2 , __A=0.1 , __A=0.25 , __A=False , **__A , ) -> Tuple: if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) a =CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(__A , __A ): a =backbone_config.get('''model_type''' ) a =CONFIG_MAPPING[backbone_model_type] a =config_class.from_dict(__A ) a =use_timm_backbone a =backbone_config a =num_channels a =num_queries a =max_position_embeddings a =d_model a =encoder_ffn_dim a =encoder_layers a =encoder_attention_heads a =decoder_ffn_dim a =decoder_layers a =decoder_attention_heads a =dropout a =attention_dropout a =activation_dropout a =activation_function a =init_std a =init_xavier_std a =encoder_layerdrop a =auxiliary_loss a =position_embedding_type a =backbone a =use_pretrained_backbone a =dilation # deformable attributes a =num_feature_levels a =encoder_n_points a =decoder_n_points a =two_stage a =two_stage_num_proposals a =with_box_refine if two_stage is True and with_box_refine is False: raise ValueError('''If two_stage is True, with_box_refine must be True.''' ) # Hungarian matcher a =class_cost a =bbox_cost a =giou_cost # Loss coefficients a =mask_loss_coefficient a =dice_loss_coefficient a =bbox_loss_coefficient a =giou_loss_coefficient a =eos_coefficient a =focal_alpha a =disable_custom_kernels super().__init__(is_encoder_decoder=__A , **__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.d_model def SCREAMING_SNAKE_CASE ( self ) -> str: a =copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: a =self.backbone_config.to_dict() a =self.__class__.model_type return output
81
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" a =ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' '''helper utility that will spawn up ''' '''multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=lowercase , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=lowercase , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=lowercase ) return parser.parse_args() def _A ( ): """simple docstring""" a =parse_args() # Import training_script as a module. a =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) a =script_fpath.stem a =importlib.import_module(lowercase ) # Patch sys.argv a =[args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
81
1
"""simple docstring""" import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase_ : str = logging.get_logger() @dataclass class __A : """simple docstring""" __lowerCAmelCase = 42 __lowerCAmelCase = field(default_factory=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase = field(default_factory=_SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A ) -> Any: a =len(list(m.modules() ) ) == 1 or isinstance(__A , nn.Convad ) or isinstance(__A , nn.BatchNormad ) if has_not_submodules: self.traced.append(__A ) def __call__( self , __A ) -> int: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(__A ) [x.remove() for x in self.handles] return self @property def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda __A : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class __A : """simple docstring""" __lowerCAmelCase = 42 __lowerCAmelCase = 42 __lowerCAmelCase = 0 __lowerCAmelCase = field(default_factory=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase = field(default_factory=_SCREAMING_SNAKE_CASE ) def __call__( self , __A ) -> int: a =Tracker(self.dest )(__A ).parametrized a =Tracker(self.src )(__A ).parametrized a =list(filter(lambda __A : type(__A ) not in self.src_skip , __A ) ) a =list(filter(lambda __A : type(__A ) not in self.dest_skip , __A ) ) if len(__A ) != len(__A ): raise Exception( f'''Numbers of operations are different. Source module has {len(__A )} operations while''' f''' destination module has {len(__A )}.''' ) for dest_m, src_m in zip(__A , __A ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'''Transfered from={src_m} to={dest_m}''' ) def _A ( lowercase , lowercase , lowercase , lowercase = True ): """simple docstring""" print(f'''Converting {name}...''' ) with torch.no_grad(): a =timm.create_model(lowercase , pretrained=lowercase ).eval() a =ResNetForImageClassification(lowercase ).eval() a =ModuleTransfer(src=lowercase , dest=lowercase ) a =torch.randn((1, 3, 2_24, 2_24) ) module_transfer(lowercase ) assert torch.allclose(from_model(lowercase ) , our_model(lowercase ).logits ), "The model logits don't match the original one." a =f'''resnet{"-".join(name.split("resnet" ) )}''' print(lowercase ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add model''' , use_temp_dir=lowercase , ) # we can use the convnext one a =AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add image processor''' , use_temp_dir=lowercase , ) print(f'''Pushed {checkpoint_name}''' ) def _A ( lowercase , lowercase = None , lowercase = True ): """simple docstring""" a ='''imagenet-1k-id2label.json''' a =10_00 a =(1, num_labels) a ='''huggingface/label-files''' a =num_labels a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} a =partial(lowercase , num_labels=lowercase , idalabel=lowercase , labelaid=lowercase ) a ={ '''resnet18''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[64, 1_28, 2_56, 5_12] , layer_type='''basic''' ), '''resnet26''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[2_56, 5_12, 10_24, 20_48] , layer_type='''bottleneck''' ), '''resnet34''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[64, 1_28, 2_56, 5_12] , layer_type='''basic''' ), '''resnet50''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[2_56, 5_12, 10_24, 20_48] , layer_type='''bottleneck''' ), '''resnet101''': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3] , hidden_sizes=[2_56, 5_12, 10_24, 20_48] , layer_type='''bottleneck''' ), '''resnet152''': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3] , hidden_sizes=[2_56, 5_12, 10_24, 20_48] , layer_type='''bottleneck''' ), } if model_name: convert_weight_and_push(lowercase , names_to_config[model_name] , lowercase , lowercase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(lowercase , lowercase , lowercase , lowercase ) return config, expected_shape if __name__ == "__main__": lowerCamelCase_ : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help=( """The name of the model you wish to convert, it must be one of the supported resnet* architecture,""" """ currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=Path, required=True, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=True, type=bool, required=False, help="""If True, push model and image processor to the hub.""", ) lowerCamelCase_ : Dict = parser.parse_args() lowerCamelCase_ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
81
"""simple docstring""" import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor lowerCamelCase_ : str = logging.get_logger(__name__) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , *__A , **__A ) -> None: warnings.warn( '''The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use CLIPImageProcessor instead.''' , __A , ) super().__init__(*__A , **__A )
81
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : int = { """configuration_upernet""": ["""UperNetConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[int] = [ """UperNetForSemanticSegmentation""", """UperNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_upernet import UperNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel else: import sys lowerCamelCase_ : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" return number | (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number & ~(1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number ^ (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return ((number >> position) & 1) == 1 def _A ( lowercase , lowercase ): """simple docstring""" return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
81
1
"""simple docstring""" 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 ( lowercase , lowercase , lowercase=[] ): """simple docstring""" a =size[0] - overlap_pixels * 2 a =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 a =np.ones((size_y, size_x) , dtype=np.uinta ) * 2_55 a =np.pad(lowercase , mode='''linear_ramp''' , pad_width=lowercase , end_values=0 ) if "l" in remove_borders: a =mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: a =mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: a =mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: a =mask[0 : mask.shape[0] - overlap_pixels, :] return mask def _A ( lowercase , lowercase , lowercase ): """simple docstring""" return max(lowercase , min(lowercase , lowercase ) ) def _A ( lowercase , lowercase , lowercase ): """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 ( lowercase , lowercase , lowercase ): """simple docstring""" a =list(lowercase ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap a =clamp_rect(lowercase , [0, 0] , [image_size[0], image_size[1]] ) return rect def _A ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =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(lowercase , (original_slice, 0) ) return result def _A ( lowercase , lowercase ): """simple docstring""" a =(original_image_slice * 4, 0, tile.size[0], tile.size[1]) a =tile.crop(lowercase ) return tile def _A ( lowercase , lowercase ): """simple docstring""" a =n % d return n - divisor class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , __A , __A , __A , __A , __A , __A , __A = 350 , ) -> int: super().__init__( vae=__A , text_encoder=__A , tokenizer=__A , unet=__A , low_res_scheduler=__A , scheduler=__A , max_noise_level=__A , ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A , **__A ) -> Tuple: torch.manual_seed(0 ) a =( 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 ), ) a =add_overlap_rect(__A , __A , image.size ) a =image.crop(__A ) a =((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] a =translated_slice_x - (original_image_slice / 2) a =max(0 , __A ) a =squeeze_tile(__A , __A , __A , __A ) a =to_input.size a =to_input.resize((tile_size, tile_size) , Image.BICUBIC ) a =super(__A , self ).__call__(image=__A , **__A ).images[0] a =upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) a =unsqueeze_tile(__A , __A ) a =upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) a =[] 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''' ) a =Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=__A ) , mode='''L''' , ) final_image.paste( __A , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , __A ) @torch.no_grad() def __call__( self , __A , __A , __A = 75 , __A = 9.0 , __A = 50 , __A = None , __A = 1 , __A = 0.0 , __A = None , __A = None , __A = None , __A = 1 , __A = 128 , __A = 32 , __A = 32 , ) -> Optional[int]: a =Image.new('''RGB''' , (image.size[0] * 4, image.size[1] * 4) ) a =math.ceil(image.size[0] / tile_size ) a =math.ceil(image.size[1] / tile_size ) a =tcx * tcy a =0 for y in range(__A ): for x in range(__A ): self._process_tile( __A , __A , __A , __A , __A , __A , __A , prompt=__A , num_inference_steps=__A , guidance_scale=__A , noise_level=__A , negative_prompt=__A , num_images_per_prompt=__A , eta=__A , generator=__A , latents=__A , ) 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""" # Run a demo a ='''stabilityai/stable-diffusion-x4-upscaler''' a =StableDiffusionTiledUpscalePipeline.from_pretrained(lowercase , revision='''fp16''' , torch_dtype=torch.floataa ) a =pipe.to('''cuda''' ) a =Image.open('''../../docs/source/imgs/diffusers_library.jpg''' ) def callback(lowercase ): print(f'''progress: {obj["progress"]:.4f}''' ) obj["image"].save('''diffusers_library_progress.jpg''' ) a =pipe(image=lowercase , prompt='''Black font, white background, vector''' , noise_level=40 , callback=lowercase ) final_image.save('''diffusers_library.jpg''' ) if __name__ == "__main__": main()
81
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _A ( lowercase ): """simple docstring""" a =SwinvaConfig() a =swinva_name.split('''_''' ) a =name_split[1] if "to" in name_split[3]: a =int(name_split[3][-3:] ) else: a =int(name_split[3] ) if "to" in name_split[2]: a =int(name_split[2][-2:] ) else: a =int(name_split[2][6:] ) if model_size == "tiny": a =96 a =(2, 2, 6, 2) a =(3, 6, 12, 24) elif model_size == "small": a =96 a =(2, 2, 18, 2) a =(3, 6, 12, 24) elif model_size == "base": a =1_28 a =(2, 2, 18, 2) a =(4, 8, 16, 32) else: a =1_92 a =(2, 2, 18, 2) a =(6, 12, 24, 48) if "to" in swinva_name: a =(12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): a =2_18_41 a ='''huggingface/label-files''' a ='''imagenet-22k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} else: a =10_00 a ='''huggingface/label-files''' a ='''imagenet-1k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} a =img_size a =num_classes a =embed_dim a =depths a =num_heads a =window_size return config def _A ( lowercase ): """simple docstring""" if "patch_embed.proj" in name: a =name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: a =name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: a ='''encoder.''' + name if "attn.proj" in name: a =name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: a =name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: a =name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: a =name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: a =name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: a =name.replace('''mlp.fc2''' , '''output.dense''' ) if "q_bias" in name: a =name.replace('''q_bias''' , '''query.bias''' ) if "k_bias" in name: a =name.replace('''k_bias''' , '''key.bias''' ) if "v_bias" in name: a =name.replace('''v_bias''' , '''value.bias''' ) if "cpb_mlp" in name: a =name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' ) if name == "norm.weight": a ='''layernorm.weight''' if name == "norm.bias": a ='''layernorm.bias''' if "head" in name: a =name.replace('''head''' , '''classifier''' ) else: a ='''swinv2.''' + name return name def _A ( lowercase , lowercase ): """simple docstring""" for key in orig_state_dict.copy().keys(): a =orig_state_dict.pop(lowercase ) if "mask" in key: continue elif "qkv" in key: a =key.split('''.''' ) a =int(key_split[1] ) a =int(key_split[3] ) a =model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a =val[:dim, :] a =val[dim : dim * 2, :] a =val[-dim:, :] else: a =val[:dim] a =val[ dim : dim * 2 ] a =val[-dim:] else: a =val return orig_state_dict def _A ( lowercase , lowercase ): """simple docstring""" a =timm.create_model(lowercase , pretrained=lowercase ) timm_model.eval() a =get_swinva_config(lowercase ) a =SwinvaForImageClassification(lowercase ) model.eval() a =convert_state_dict(timm_model.state_dict() , lowercase ) model.load_state_dict(lowercase ) a ='''http://images.cocodataset.org/val2017/000000039769.jpg''' a =AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swinva_name.replace('''_''' , '''-''' ) ) ) a =Image.open(requests.get(lowercase , stream=lowercase ).raw ) a =image_processor(images=lowercase , return_tensors='''pt''' ) a =timm_model(inputs['''pixel_values'''] ) a =model(**lowercase ).logits assert torch.allclose(lowercase , lowercase , atol=1E-3 ) print(f'''Saving model {swinva_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) model.push_to_hub( repo_path_or_name=Path(lowercase , lowercase ) , organization='''nandwalritik''' , commit_message='''Add model''' , ) if __name__ == "__main__": lowerCamelCase_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swinv2_name""", default="""swinv2_tiny_patch4_window8_256""", type=str, help="""Name of the Swinv2 timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowerCamelCase_ : Union[str, Any] = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
81
1
"""simple docstring""" import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowerCamelCase_ : Optional[Any] = logging.get_logger(__name__) lowerCamelCase_ : Tuple = {"""vocab_file""": """spiece.model"""} lowerCamelCase_ : Optional[int] = { """vocab_file""": { """AI-Sweden/gpt-sw3-126m""": """https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model""", """AI-Sweden/gpt-sw3-350m""": """https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model""", """AI-Sweden/gpt-sw3-1.6b""": """https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model""", """AI-Sweden/gpt-sw3-6.7b""": """https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model""", """AI-Sweden/gpt-sw3-20b""": """https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model""", } } lowerCamelCase_ : Dict = { """AI-Sweden/gpt-sw3-126m""": 2_0_4_8, """AI-Sweden/gpt-sw3-350m""": 2_0_4_8, """AI-Sweden/gpt-sw3-1.6b""": 2_0_4_8, """AI-Sweden/gpt-sw3-6.7b""": 2_0_4_8, """AI-Sweden/gpt-sw3-20b""": 2_0_4_8, } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A=False , __A=False , __A=False , __A=None , __A=None , __A=None , __A=None , __A = None , **__A , ) -> None: a ={} if sp_model_kwargs is None else sp_model_kwargs a =kwargs.get('''name_or_path''' ) if name_or_path is None: logger.warning( '''name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,''' ''' you are testing the model, this can safely be ignored''' ) a ='''None''' # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing a ='''<|endoftext|>''' if eos_token is None else eos_token a ='''<unk>''' if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: a =unk_token if pad_token is None else pad_token a =eos_token if bos_token is None else bos_token else: a ='''<pad>''' if pad_token is None else pad_token a ='''<s>''' if bos_token is None else bos_token super().__init__( do_lower_case=__A , remove_space=__A , keep_accents=__A , bos_token=__A , eos_token=__A , unk_token=__A , pad_token=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =do_lower_case a =remove_space a =keep_accents a =vocab_file a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__A ) # Used for whitespace normalization in input texts # fmt : off a ={''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', '''''', '''„'''} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing a =re.compile( f'''[{"".join(map(__A , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]''' ) def __getstate__( self ) -> List[Any]: a =self.__dict__.copy() a =None return state def __setstate__( self , __A ) -> Tuple: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def SCREAMING_SNAKE_CASE ( self ) -> int: return len(self.sp_model ) def SCREAMING_SNAKE_CASE ( self , __A ) -> str: a =self.non_printing_characters_re.sub('''''' , __A ) # Normalize whitespaces a =''''''.join([char if char not in self.whitespaces else ''' ''' for char in text] ) # NFC Unicode normalization a =unicodedata.normalize('''NFC''' , __A ) return text def SCREAMING_SNAKE_CASE ( self , __A , **__A ) -> List[str]: a =self.preprocess_text(__A ) return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> int: return self.sp_model.PieceToId(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> str: return self.sp_model.IdToPiece(__A ) @staticmethod def SCREAMING_SNAKE_CASE ( __A ) -> str: return out_string def SCREAMING_SNAKE_CASE ( self , __A ) -> str: a =[] a ='''''' a =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__A ) + token a =True a =[] else: current_sub_tokens.append(__A ) a =False out_string += self.sp_model.decode(__A ) return out_string def SCREAMING_SNAKE_CASE ( self ) -> Dict[str, int]: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , '''wb''' ) as fi: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,) def SCREAMING_SNAKE_CASE ( self , __A , __A = False ) -> Union[List[int], List[List[int]], "torch.Tensor"]: if isinstance(__A , __A ): a =self.preprocess_text(__A ) a =self.sp_model.encode(__A ) else: a =[self.preprocess_text(__A ) for t in text] a =self.sp_model.encode(__A ) if return_tensors is True or return_tensors == "pt": a =torch.tensor(__A ) return token_ids def SCREAMING_SNAKE_CASE ( self , __A ) -> str: return self.sp_model.decode(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> List[int]: a =[f'''User: {text}''' if is_user else f'''Bot: {text}''' for is_user, text in conversation.iter_texts()] a =( f'''{self.eos_token}{self.bos_token}''' + f'''{self.bos_token}'''.join(__A ) + f'''{self.bos_token}Bot:''' ) return self.encode(text=__A )
81
"""simple docstring""" lowerCamelCase_ : Any = [ """DownloadConfig""", """DownloadManager""", """DownloadMode""", """StreamingDownloadManager""", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
81
1
"""simple docstring""" from collections.abc import Sequence def _A ( lowercase , lowercase = False ): """simple docstring""" if not arr: return 0 a =0 if allow_empty_subarrays else float('''-inf''' ) a =0.0 for num in arr: a =max(0 if allow_empty_subarrays else num , curr_sum + num ) a =max(lowercase , lowercase ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() lowerCamelCase_ : List[str] = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(F'{max_subarray_sum(nums) = }')
81
"""simple docstring""" from scipy.stats import pearsonr import datasets lowerCamelCase_ : Optional[int] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ lowerCamelCase_ : Optional[Any] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ lowerCamelCase_ : Optional[int] = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Dict: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float''' ), '''references''': datasets.Value('''float''' ), } ) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A=False ) -> Optional[Any]: if return_pvalue: a =pearsonr(__A , __A ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(__A , __A )[0] )}
81
1
"""simple docstring""" def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =set() # Replace all the whitespace in our sentence a =input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowercase ) == 26 def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =[False] * 26 for char in input_str: if char.islower(): a =True elif char.isupper(): a =True return all(lowercase ) def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _A ( ): """simple docstring""" from timeit import timeit a ='''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowercase ) ) print(timeit('''is_pangram_faster()''' , setup=lowercase ) ) print(timeit('''is_pangram_fastest()''' , setup=lowercase ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
81
"""simple docstring""" lowerCamelCase_ : int = """ # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git """ lowerCamelCase_ : Dict = [{"""type""": """code""", """content""": INSTALL_CONTENT}] lowerCamelCase_ : Union[str, Any] = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
81
1
"""simple docstring""" import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available from ..wavaveca.test_feature_extraction_wavaveca import floats_list if is_pyctcdecode_available(): from huggingface_hub import snapshot_download from pyctcdecode import BeamSearchDecoderCTC from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput if is_torch_available(): from transformers import WavaVecaForCTC @require_pyctcdecode class __A ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a ='''| <pad> <unk> <s> </s> a b c d e f g h i j k'''.split() a =dict(zip(__A , range(len(__A ) ) ) ) a ={ '''unk_token''': '''<unk>''', '''bos_token''': '''<s>''', '''eos_token''': '''</s>''', } a ={ '''feature_size''': 1, '''padding_value''': 0.0, '''sampling_rate''': 1_6000, '''return_attention_mask''': False, '''do_normalize''': True, } a =tempfile.mkdtemp() a =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) a =os.path.join(self.tmpdirname , __A ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(__A ) + '''\n''' ) with open(self.feature_extraction_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(__A ) + '''\n''' ) # load decoder from hub a ='''hf-internal-testing/ngram-beam-search-decoder''' def SCREAMING_SNAKE_CASE ( self , **__A ) -> Dict: a =self.add_kwargs_tokens_map.copy() kwargs.update(__A ) return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname , **__A ) def SCREAMING_SNAKE_CASE ( self , **__A ) -> Optional[Any]: return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname , **__A ) def SCREAMING_SNAKE_CASE ( self , **__A ) -> Dict: return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name , **__A ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =self.get_tokenizer() a =self.get_feature_extractor() a =self.get_decoder() a =WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A ) processor.save_pretrained(self.tmpdirname ) a =WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname ) # tokenizer self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , __A ) # feature extractor self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __A ) # decoder self.assertEqual(processor.decoder._alphabet.labels , decoder._alphabet.labels ) self.assertEqual( processor.decoder.model_container[decoder._model_key]._unigram_set , decoder.model_container[decoder._model_key]._unigram_set , ) self.assertIsInstance(processor.decoder , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =WavaVecaProcessorWithLM( tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) processor.save_pretrained(self.tmpdirname ) # make sure that error is thrown when decoder alphabet doesn't match a =WavaVecaProcessorWithLM.from_pretrained( self.tmpdirname , alpha=5.0 , beta=3.0 , score_boundary=-7.0 , unk_score_offset=3 ) # decoder self.assertEqual(processor.language_model.alpha , 5.0 ) self.assertEqual(processor.language_model.beta , 3.0 ) self.assertEqual(processor.language_model.score_boundary , -7.0 ) self.assertEqual(processor.language_model.unk_score_offset , 3 ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =self.get_tokenizer() # add token to trigger raise tokenizer.add_tokens(['''xx'''] ) with self.assertRaisesRegex(__A , '''include''' ): WavaVecaProcessorWithLM( tokenizer=__A , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.get_feature_extractor() a =self.get_tokenizer() a =self.get_decoder() a =WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A ) a =floats_list((3, 1000) ) a =feature_extractor(__A , return_tensors='''np''' ) a =processor(__A , 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 SCREAMING_SNAKE_CASE ( self ) -> str: a =self.get_feature_extractor() a =self.get_tokenizer() a =self.get_decoder() a =WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A ) a ='''This is a test string''' a =processor(text=__A ) a =tokenizer(__A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE ( self , __A=(2, 10, 16) , __A=77 ) -> Optional[int]: np.random.seed(__A ) return np.random.rand(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =self.get_feature_extractor() a =self.get_tokenizer() a =self.get_decoder() a =WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A ) a =self._get_dummy_logits(shape=(10, 16) , seed=13 ) a =processor.decode(__A ) a =decoder.decode_beams(__A )[0] self.assertEqual(decoded_decoder[0] , decoded_processor.text ) self.assertEqual('''</s> <s> </s>''' , decoded_processor.text ) self.assertEqual(decoded_decoder[-2] , decoded_processor.logit_score ) self.assertEqual(decoded_decoder[-1] , decoded_processor.lm_score ) @parameterized.expand([[None], ['''fork'''], ['''spawn''']] ) def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: a =self.get_feature_extractor() a =self.get_tokenizer() a =self.get_decoder() a =WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A ) a =self._get_dummy_logits() # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM. # otherwise, the LM won't be available to the pool's sub-processes. # manual logic used to allow parameterized test for both pool=None and pool=Pool(...) if pool_context is None: a =processor.batch_decode(__A ) else: with get_context(__A ).Pool() as pool: a =processor.batch_decode(__A , __A ) a =list(__A ) with get_context('''fork''' ).Pool() as p: a =decoder.decode_beams_batch(__A , __A ) a , a , a =[], [], [] for beams in decoded_beams: texts_decoder.append(beams[0][0] ) logit_scores_decoder.append(beams[0][-2] ) lm_scores_decoder.append(beams[0][-1] ) self.assertListEqual(__A , decoded_processor.text ) self.assertListEqual(['''<s> <s> </s>''', '''<s> <s> <s>'''] , decoded_processor.text ) self.assertListEqual(__A , decoded_processor.logit_score ) self.assertListEqual(__A , decoded_processor.lm_score ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =self.get_feature_extractor() a =self.get_tokenizer() a =self.get_decoder() a =WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A ) a =self._get_dummy_logits() a =15 a =-20.0 a =-4.0 a =processor.batch_decode( __A , beam_width=__A , beam_prune_logp=__A , token_min_logp=__A , ) a =decoded_processor_out.text a =list(__A ) with get_context('''fork''' ).Pool() as pool: a =decoder.decode_beams_batch( __A , __A , beam_width=__A , beam_prune_logp=__A , token_min_logp=__A , ) a =[d[0][0] for d in decoded_decoder_out] a =[d[0][2] for d in decoded_decoder_out] a =[d[0][3] for d in decoded_decoder_out] self.assertListEqual(__A , __A ) self.assertListEqual(['''</s> <s> <s>''', '''<s> <s> <s>'''] , __A ) self.assertTrue(np.array_equal(__A , decoded_processor_out.logit_score ) ) self.assertTrue(np.allclose([-20.054, -18.447] , __A , atol=1E-3 ) ) self.assertTrue(np.array_equal(__A , decoded_processor_out.lm_score ) ) self.assertTrue(np.allclose([-15.554, -13.9_474] , __A , atol=1E-3 ) ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.get_feature_extractor() a =self.get_tokenizer() a =self.get_decoder() a =WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A ) a =self._get_dummy_logits() a =2.0 a =5.0 a =-20.0 a =True a =processor.batch_decode( __A , alpha=__A , beta=__A , unk_score_offset=__A , lm_score_boundary=__A , ) a =decoded_processor_out.text a =list(__A ) decoder.reset_params( alpha=__A , beta=__A , unk_score_offset=__A , lm_score_boundary=__A , ) with get_context('''fork''' ).Pool() as pool: a =decoder.decode_beams_batch( __A , __A , ) a =[d[0][0] for d in decoded_decoder_out] self.assertListEqual(__A , __A ) self.assertListEqual(['''<s> </s> <s> </s> </s>''', '''</s> </s> <s> </s> </s>'''] , __A ) a =processor.decoder.model_container[processor.decoder._model_key] self.assertEqual(lm_model.alpha , 2.0 ) self.assertEqual(lm_model.beta , 5.0 ) self.assertEqual(lm_model.unk_score_offset , -20.0 ) self.assertEqual(lm_model.score_boundary , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) a =processor.decoder.model_container[processor.decoder._model_key] a =Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute() a =os.listdir(__A ) a =['''alphabet.json''', '''language_model'''] downloaded_decoder_files.sort() expected_decoder_files.sort() # test that only decoder relevant files from # https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main # are downloaded and none of the rest (e.g. README.md, ...) self.assertListEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =snapshot_download('''hf-internal-testing/processor_with_lm''' ) a =WavaVecaProcessorWithLM.from_pretrained(__A ) a =processor.decoder.model_container[processor.decoder._model_key] a =Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute() a =os.listdir(__A ) a =os.listdir(__A ) local_decoder_files.sort() expected_decoder_files.sort() # test that both decoder form hub and local files in cache are the same self.assertListEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Any: a =WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) a =AutoProcessor.from_pretrained('''hf-internal-testing/processor_with_lm''' ) a =floats_list((3, 1000) ) a =processor_wavaveca(__A , return_tensors='''np''' ) a =processor_auto(__A , return_tensors='''np''' ) for key in input_wavaveca.keys(): self.assertAlmostEqual(input_wavaveca[key].sum() , input_auto[key].sum() , delta=1E-2 ) a =self._get_dummy_logits() a =processor_wavaveca.batch_decode(__A ) a =processor_auto.batch_decode(__A ) self.assertListEqual(decoded_wavaveca.text , decoded_auto.text ) def SCREAMING_SNAKE_CASE ( self ) -> Any: a =self.get_feature_extractor() a =self.get_tokenizer() a =self.get_decoder() a =WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A ) self.assertListEqual( processor.model_input_names , feature_extractor.model_input_names , msg='''`processor` and `feature_extractor` model input names do not match''' , ) @staticmethod def SCREAMING_SNAKE_CASE ( __A , __A ) -> List[Any]: a =[d[key] for d in offsets] return retrieved_list def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) a =self._get_dummy_logits()[0] a =processor.decode(__A , output_word_offsets=__A ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue('''text''' in outputs ) self.assertTrue('''word_offsets''' in outputs ) self.assertTrue(isinstance(__A , __A ) ) self.assertEqual(''' '''.join(self.get_from_offsets(outputs['''word_offsets'''] , '''word''' ) ) , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''word''' ) , ['''<s>''', '''<s>''', '''</s>'''] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''start_offset''' ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''end_offset''' ) , [1, 3, 5] ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) a =self._get_dummy_logits() a =processor.batch_decode(__A , output_word_offsets=__A ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue('''text''' in outputs ) self.assertTrue('''word_offsets''' in outputs ) self.assertTrue(isinstance(__A , __A ) ) self.assertListEqual( [''' '''.join(self.get_from_offsets(__A , '''word''' ) ) for o in outputs['''word_offsets''']] , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''word''' ) , ['''<s>''', '''<s>''', '''</s>'''] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''start_offset''' ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''end_offset''' ) , [1, 3, 5] ) @slow @require_torch @require_torchaudio def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: import torch a =load_dataset('''common_voice''' , '''en''' , split='''train''' , streaming=__A ) a =ds.cast_column('''audio''' , datasets.Audio(sampling_rate=1_6000 ) ) a =iter(__A ) a =next(__A ) a =AutoProcessor.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' ) a =WavaVecaForCTC.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' ) # compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train a =processor(sample['''audio''']['''array'''] , return_tensors='''pt''' ).input_values with torch.no_grad(): a =model(__A ).logits.cpu().numpy() a =processor.decode(logits[0] , output_word_offsets=__A ) a =model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate a =[ { '''start_time''': d['''start_offset'''] * time_offset, '''end_time''': d['''end_offset'''] * time_offset, '''word''': d['''word'''], } for d in output['''word_offsets'''] ] a ='''WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL''' # output words self.assertEqual(''' '''.join(self.get_from_offsets(__A , '''word''' ) ) , __A ) self.assertEqual(''' '''.join(self.get_from_offsets(__A , '''word''' ) ) , output.text ) # output times a =torch.tensor(self.get_from_offsets(__A , '''start_time''' ) ) a =torch.tensor(self.get_from_offsets(__A , '''end_time''' ) ) # fmt: off a =torch.tensor([1.4_199, 1.6_599, 2.2_599, 3.0, 3.24, 3.5_999, 3.7_999, 4.0_999, 4.26, 4.94, 5.28, 5.6_599, 5.78, 5.94, 6.32, 6.5_399, 6.6_599] ) a =torch.tensor([1.5_399, 1.8_999, 2.9, 3.16, 3.5_399, 3.72, 4.0_199, 4.1_799, 4.76, 5.1_599, 5.5_599, 5.6_999, 5.86, 6.1_999, 6.38, 6.6_199, 6.94] ) # fmt: on self.assertTrue(torch.allclose(__A , __A , atol=0.01 ) ) self.assertTrue(torch.allclose(__A , __A , atol=0.01 ) )
81
"""simple docstring""" def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =set() # Replace all the whitespace in our sentence a =input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowercase ) == 26 def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =[False] * 26 for char in input_str: if char.islower(): a =True elif char.isupper(): a =True return all(lowercase ) def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _A ( ): """simple docstring""" from timeit import timeit a ='''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowercase ) ) print(timeit('''is_pangram_faster()''' , setup=lowercase ) ) print(timeit('''is_pangram_fastest()''' , setup=lowercase ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
81
1
"""simple docstring""" import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin lowerCamelCase_ : int = 1E-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class __A : """simple docstring""" def __init__( self , __A , __A=16 , __A=13 , __A=7 , __A=14 , __A=10 , __A=19 , __A=5 , __A=4 , __A=True , __A=16 , __A=2 , __A=4 , __A=4 , __A="gelu" , __A=0.1 , __A=0.1 , __A=[1, 2, 3, 4, 5] , __A=25 , __A=5 , ) -> Optional[Any]: a =d_model a =parent a =batch_size a =prediction_length a =context_length a =cardinality a =num_time_features a =lags_sequence a =embedding_dimension a =is_training a =hidden_size a =num_hidden_layers a =num_attention_heads a =intermediate_size a =hidden_act a =hidden_dropout_prob a =attention_probs_dropout_prob a =context_length a =prediction_length + label_length a =label_length a =moving_average a =autocorrelation_factor def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: return AutoformerConfig( d_model=self.d_model , 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 , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Any: a =config.context_length + max(config.lags_sequence ) a =ids_tensor([self.batch_size, 1] , config.cardinality[0] ) a =floats_tensor([self.batch_size, _past_length, config.num_time_features] ) a =floats_tensor([self.batch_size, _past_length] ) a =floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs a =floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) a =floats_tensor([self.batch_size, config.prediction_length] ) a ={ '''past_values''': past_values, '''static_categorical_features''': static_categorical_features, '''past_time_features''': past_time_features, '''past_observed_mask''': past_observed_mask, '''future_time_features''': future_time_features, '''future_values''': future_values, } return inputs_dict def SCREAMING_SNAKE_CASE ( self ) -> Any: a =self.get_config() a =self.prepare_autoformer_inputs_dict(__A ) return config, inputs_dict def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a , a =self.prepare_config_and_inputs() return config, inputs_dict def SCREAMING_SNAKE_CASE ( self , __A , __A ) -> Optional[Any]: a =AutoformerModel(config=__A ).to(__A ).eval() a =model(**__A ) a =outputs.encoder_last_hidden_state a =outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: a =model.get_encoder() encoder.save_pretrained(__A ) a =AutoformerEncoder.from_pretrained(__A ).to(__A ) a , a , a , a , a =model.create_network_inputs(**__A ) a , a =model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) a =torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) a =encoder(inputs_embeds=__A )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3 ) a =( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) a =torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) a =torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) a =torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: a =model.get_decoder() decoder.save_pretrained(__A ) a =AutoformerDecoder.from_pretrained(__A ).to(__A ) a =decoder( trend=__A , inputs_embeds=__A , encoder_hidden_states=__A , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3 ) @require_torch class __A ( _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () __lowerCAmelCase = (AutoformerForPrediction,) if is_torch_available() else () __lowerCAmelCase = {"feature-extraction": AutoformerModel} if is_torch_available() else {} __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =AutoformerModelTester(self ) a =ConfigTester(self , config_class=__A , has_text_modality=__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a , a =self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: a =model_class(__A ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__A ) a , a =model_class.from_pretrained(__A , output_loading_info=__A ) self.assertEqual(info['''missing_keys'''] , [] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*__A ) @unittest.skip(reason='''Model has no tokens embeddings''' ) def SCREAMING_SNAKE_CASE ( self ) -> Any: pass def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =inspect.signature(getattr(__A , '''forward''' ) ) # The main input is the name of the argument after `self` a =list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a , a =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a =model_class(__A ) a =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a =[*signature.parameters.keys()] a =[ '''past_values''', '''past_time_features''', '''past_observed_mask''', '''static_categorical_features''', '''static_real_features''', '''future_values''', '''future_time_features''', ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append('''future_observed_mask''' ) expected_arg_names.extend( [ '''decoder_attention_mask''', '''head_mask''', '''decoder_head_mask''', '''cross_attn_head_mask''', '''encoder_outputs''', '''past_key_values''', '''output_hidden_states''', '''output_attentions''', '''use_cache''', '''return_dict''', ] ) self.assertListEqual(arg_names[: len(__A )] , __A ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a , a =self.model_tester.prepare_config_and_inputs_for_common() a =True a =getattr(self.model_tester , '''seq_length''' , __A ) a =getattr(self.model_tester , '''decoder_seq_length''' , __A ) a =getattr(self.model_tester , '''encoder_seq_length''' , __A ) a =getattr(self.model_tester , '''d_model''' , __A ) a =getattr(self.model_tester , '''num_attention_heads''' , __A ) a =d_model // num_attention_heads for model_class in self.all_model_classes: a =True a =False a =True a =model_class(__A ) model.to(__A ) model.eval() with torch.no_grad(): a =model(**self._prepare_for_class(__A , __A ) ) a =outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__A ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] a =True a =model_class(__A ) model.to(__A ) model.eval() with torch.no_grad(): a =model(**self._prepare_for_class(__A , __A ) ) a =outputs.encoder_attentions self.assertEqual(len(__A ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) a =len(__A ) a =7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(__A , __A ) # decoder attentions a =outputs.decoder_attentions self.assertIsInstance(__A , (list, tuple) ) self.assertEqual(len(__A ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions a =outputs.cross_attentions self.assertIsInstance(__A , (list, tuple) ) self.assertEqual(len(__A ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(cross_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine a =True a =True a =model_class(__A ) model.to(__A ) model.eval() with torch.no_grad(): a =model(**self._prepare_for_class(__A , __A ) ) self.assertEqual(out_len + 2 , len(__A ) ) a =outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__A ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def SCREAMING_SNAKE_CASE ( self ) -> int: super().test_retain_grad_hidden_states_attentions() def _A ( lowercase="train-batch.pt" ): """simple docstring""" a =hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch''' , filename=lowercase , repo_type='''dataset''' ) a =torch.load(lowercase , map_location=lowercase ) return batch @require_torch @slow class __A ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(__A ) a =prepare_batch() with torch.no_grad(): a =model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , future_values=batch['''future_values'''] , future_time_features=batch['''future_time_features'''] , )[0] a =torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , __A ) a =torch.tensor( [[0.3_593, -1.3_398, 0.6_330], [0.2_279, 1.5_396, -0.1_792], [0.0_450, 1.3_225, -0.2_335]] , device=__A ) self.assertTrue(torch.allclose(output[0, :3, :3] , __A , atol=__A ) ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(__A ) a =prepare_batch('''val-batch.pt''' ) with torch.no_grad(): a =model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , ).encoder_last_hidden_state a =torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , __A ) a =torch.tensor( [[-0.0_734, -0.9_036, 0.8_358], [4.7_186, 2.4_113, 1.9_581], [1.7_953, 2.3_558, 1.2_970]] , device=__A ) self.assertTrue(torch.allclose(output[0, :3, :3] , __A , atol=__A ) ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(__A ) a =prepare_batch('''val-batch.pt''' ) with torch.no_grad(): a =model.generate( static_categorical_features=batch['''static_categorical_features'''] , past_time_features=batch['''past_time_features'''] , past_values=batch['''past_values'''] , future_time_features=batch['''future_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , ) a =torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , __A ) a =torch.tensor([3_130.6_763, 4_056.5_293, 7_053.0_786] , device=__A ) a =outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , __A , rtol=1E-1 ) )
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys lowerCamelCase_ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" def _A ( ): """simple docstring""" for n in range(1 , 1_00_00_00 ): yield n * (n + 1) // 2 def _A ( lowercase ): """simple docstring""" a =1 a =2 while i * i <= n: a =0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _A ( ): """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(lowercase ) > 5_00 ) if __name__ == "__main__": print(solution())
81
"""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 lowerCamelCase_ : Dict = logging.getLogger(__name__) lowerCamelCase_ : Tuple = """pytorch_model.bin""" @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co."}, ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the training data."} ) __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the data to predict on."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "A csv or a json file containing the validation data."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The name of the task to train on."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The list of labels for the task."} ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "The output directory where the model predictions and checkpoints will be written."} ) __lowerCAmelCase = dataclasses.field( default="accuracy", metadata={"help": "The evaluation metric used for the task."} ) __lowerCAmelCase = dataclasses.field( default="no", metadata={ "help": "The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]" }, ) __lowerCAmelCase = dataclasses.field( default=10, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={ "help": "How much the specified evaluation metric must improve to satisfy early stopping conditions." }, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the confidence score."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the validation performance."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to fine-tune on labeled data after pseudo training."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={"help": "Confidence threshold for pseudo-labeled data filtering."}, ) __lowerCAmelCase = dataclasses.field( default=100, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Random seed for initialization."}, ) def _A ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: a =dataset.filter(lambda lowercase : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 a =int(eval_result * len(lowercase ) ) print(lowercase ) a =dataset.sort('''probability''' , reverse=lowercase ) a =dataset.select(range(lowercase ) ) a =dataset.remove_columns(['''label''', '''probability'''] ) a =dataset.rename_column('''prediction''' , '''label''' ) a =dataset.map(lambda lowercase : {"label": idalabel[example["label"]]} ) a =dataset.shuffle(seed=args.seed ) a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(lowercase , index=lowercase ) else: dataset.to_json(lowercase ) def _A ( lowercase , lowercase , lowercase , lowercase , **lowercase ): """simple docstring""" a =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() a =STModelArguments(model_name_or_path=lowercase ) a =STDataArguments(train_file=lowercase , infer_file=lowercase ) a =STTrainingArguments(output_dir=lowercase ) a =argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(lowercase ).items(): setattr(lowercase , lowercase , lowercase ) for key, value in kwargs.items(): if hasattr(lowercase , lowercase ): setattr(lowercase , lowercase , lowercase ) # Sanity checks a ={} a =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 a =args.train_file a =args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None a =args.eval_file for key in data_files: a =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: a =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...''' ) a =f'''{args.output_dir}/self-train_iter-{{}}'''.format a =data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=lowercase ) os.makedirs(lowercase , exist_ok=lowercase ) accelerator.wait_for_everyone() a =None a =None a =0 a =False # Show the progress bar a =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 ) ): a =data_dir_format(lowercase ) assert os.path.exists(lowercase ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 a =os.path.join(lowercase , '''stage-1''' ) a ={ '''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(lowercase , lowercase ): arguments_dict.update({key: value} ) a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 1 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 1.''' , lowercase ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data a =os.path.join(lowercase , '''best-checkpoint''' ) a =os.path.join(lowercase , '''stage-2''' ) # Update arguments_dict a =model_path a =data_files['''train'''] a =current_output_dir a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 2 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 2.''' , lowercase ) a =iteration a =data_dir_format(iteration + 1 ) a =AutoConfig.from_pretrained(os.path.join(lowercase , '''best-checkpoint''' ) ) a =config.idalabel a =os.path.join(lowercase , '''eval_results_best-checkpoint.json''' ) a =os.path.join(lowercase , '''test_results_best-checkpoint.json''' ) assert os.path.exists(lowercase ) with open(lowercase , '''r''' ) as f: a =float(json.load(lowercase )[args.eval_metric] ) a =os.path.join(lowercase , '''infer_output_best-checkpoint.csv''' ) assert os.path.exists(lowercase ) # Loading the dataset from local csv or json files. a =load_dataset(args.data_file_extension , data_files={'''data''': data_files['''infer''']} )['''data'''] a =load_dataset('''csv''' , data_files={'''data''': infer_output_file} )['''data'''] if accelerator.is_main_process: os.makedirs(lowercase , exist_ok=lowercase ) shutil.copy(lowercase , os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(lowercase ): shutil.copy(lowercase , os.path.join(lowercase , f'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) accelerator.wait_for_everyone() a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: a =eval_result if best_iteration is None: a =new_iteration a =new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: a =new_iteration a =new_eval_result a =0 else: if new_eval_result == best_eval_result: a =new_iteration a =new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: a =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''' , lowercase ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) , os.path.join(lowercase , '''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 , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(lowercase , '''eval_results_best-iteration.json''' ) , )
81
1
"""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, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Tuple = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : str = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } lowerCamelCase_ : Optional[int] = { """moussaKam/mbarthez""": 1_0_2_4, """moussaKam/barthez""": 1_0_2_4, """moussaKam/barthez-orangesum-title""": 1_0_2_4, } lowerCamelCase_ : Tuple = """▁""" class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =vocab_file a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a ={'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} a =len(self.sp_model ) - 1 a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[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] @property def SCREAMING_SNAKE_CASE ( self ) -> Any: return len(self.sp_model ) def SCREAMING_SNAKE_CASE ( self ) -> int: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Dict: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =self.sp_model.PieceToId(__A ) return spm_id if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Tuple: a =[] a ='''''' a =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__A ) + token a =True a =[] else: current_sub_tokens.append(__A ) a =False out_string += self.sp_model.decode(__A ) return out_string.strip() def __getstate__( self ) -> Tuple: a =self.__dict__.copy() a =None return state def __setstate__( self , __A ) -> Tuple: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , '''wb''' ) as fi: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
"""simple docstring""" def _A ( ): """simple docstring""" for n in range(1 , 1_00_00_00 ): yield n * (n + 1) // 2 def _A ( lowercase ): """simple docstring""" a =1 a =2 while i * i <= n: a =0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _A ( ): """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(lowercase ) > 5_00 ) if __name__ == "__main__": print(solution())
81
1
"""simple docstring""" def _A ( lowercase = 2_00 ): """simple docstring""" a =[1, 2, 5, 10, 20, 50, 1_00, 2_00] a =[0] * (pence + 1) a =1 # base case: 1 way to make 0 pence for coin in coins: for i in range(lowercase , pence + 1 , 1 ): number_of_ways[i] += number_of_ways[i - coin] return number_of_ways[pence] if __name__ == "__main__": assert solution(2_0_0) == 7_3_6_8_2
81
"""simple docstring""" from math import factorial def _A ( lowercase = 1_00 ): """simple docstring""" return sum(int(lowercase ) for x in str(factorial(lowercase ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
81
1
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" return number | (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number & ~(1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number ^ (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return ((number >> position) & 1) == 1 def _A ( lowercase , lowercase ): """simple docstring""" return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
81
"""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, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Optional[Any] = """▁""" lowerCamelCase_ : Union[str, Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : Any = { """vocab_file""": { """xlm-roberta-base""": """https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large""": """https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large-finetuned-conll02-dutch""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll02-spanish""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-english""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-german""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model""" ), } } lowerCamelCase_ : Tuple = { """xlm-roberta-base""": 5_1_2, """xlm-roberta-large""": 5_1_2, """xlm-roberta-large-finetuned-conll02-dutch""": 5_1_2, """xlm-roberta-large-finetuned-conll02-spanish""": 5_1_2, """xlm-roberta-large-finetuned-conll03-english""": 5_1_2, """xlm-roberta-large-finetuned-conll03-german""": 5_1_2, } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a =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 a ={'''<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 a =1 a =len(self.sp_model ) + self.fairseq_offset a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: a =self.__dict__.copy() a =None a =self.sp_model.serialized_model_proto() return state def __setstate__( self , __A ) -> List[Any]: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[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] @property def SCREAMING_SNAKE_CASE ( self ) -> List[str]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> int: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =self.sp_model.PieceToId(__A ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: a =''''''.join(__A ).replace(__A , ''' ''' ).strip() return out_string def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , '''wb''' ) as fi: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
1
"""simple docstring""" from collections.abc import Generator def _A ( ): """simple docstring""" a , a =0, 1 while True: a , a =b, a + b yield b def _A ( lowercase = 10_00 ): """simple docstring""" a =1 a =fibonacci_generator() while len(str(next(lowercase ) ) ) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
81
"""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, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Tuple = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : str = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } lowerCamelCase_ : Optional[int] = { """moussaKam/mbarthez""": 1_0_2_4, """moussaKam/barthez""": 1_0_2_4, """moussaKam/barthez-orangesum-title""": 1_0_2_4, } lowerCamelCase_ : Tuple = """▁""" class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =vocab_file a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a ={'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} a =len(self.sp_model ) - 1 a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[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] @property def SCREAMING_SNAKE_CASE ( self ) -> Any: return len(self.sp_model ) def SCREAMING_SNAKE_CASE ( self ) -> int: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Dict: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =self.sp_model.PieceToId(__A ) return spm_id if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Tuple: a =[] a ='''''' a =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__A ) + token a =True a =[] else: current_sub_tokens.append(__A ) a =False out_string += self.sp_model.decode(__A ) return out_string.strip() def __getstate__( self ) -> Tuple: a =self.__dict__.copy() a =None return state def __setstate__( self , __A ) -> Tuple: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , '''wb''' ) as fi: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
1
"""simple docstring""" from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup lowerCamelCase_ : Optional[Any] = """https://www.indeed.co.in/jobs?q=mobile+app+development&l=""" def _A ( lowercase = "mumbai" ): """simple docstring""" a =BeautifulSoup(requests.get(url + location ).content , '''html.parser''' ) # This attribute finds out all the specifics listed in a job for job in soup.find_all('''div''' , attrs={'''data-tn-component''': '''organicJob'''} ): a =job.find('''a''' , attrs={'''data-tn-element''': '''jobTitle'''} ).text.strip() a =job.find('''span''' , {'''class''': '''company'''} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs("""Bangalore"""), 1): print(F'Job {i:>2} is {job[0]} at {job[1]}')
81
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) lowerCamelCase_ : Tuple = logging.get_logger(__name__) lowerCamelCase_ : str = OrderedDict( [ ("""align""", """EfficientNetImageProcessor"""), ("""beit""", """BeitImageProcessor"""), ("""bit""", """BitImageProcessor"""), ("""blip""", """BlipImageProcessor"""), ("""blip-2""", """BlipImageProcessor"""), ("""bridgetower""", """BridgeTowerImageProcessor"""), ("""chinese_clip""", """ChineseCLIPImageProcessor"""), ("""clip""", """CLIPImageProcessor"""), ("""clipseg""", """ViTImageProcessor"""), ("""conditional_detr""", """ConditionalDetrImageProcessor"""), ("""convnext""", """ConvNextImageProcessor"""), ("""convnextv2""", """ConvNextImageProcessor"""), ("""cvt""", """ConvNextImageProcessor"""), ("""data2vec-vision""", """BeitImageProcessor"""), ("""deformable_detr""", """DeformableDetrImageProcessor"""), ("""deit""", """DeiTImageProcessor"""), ("""deta""", """DetaImageProcessor"""), ("""detr""", """DetrImageProcessor"""), ("""dinat""", """ViTImageProcessor"""), ("""donut-swin""", """DonutImageProcessor"""), ("""dpt""", """DPTImageProcessor"""), ("""efficientformer""", """EfficientFormerImageProcessor"""), ("""efficientnet""", """EfficientNetImageProcessor"""), ("""flava""", """FlavaImageProcessor"""), ("""focalnet""", """BitImageProcessor"""), ("""git""", """CLIPImageProcessor"""), ("""glpn""", """GLPNImageProcessor"""), ("""groupvit""", """CLIPImageProcessor"""), ("""imagegpt""", """ImageGPTImageProcessor"""), ("""instructblip""", """BlipImageProcessor"""), ("""layoutlmv2""", """LayoutLMv2ImageProcessor"""), ("""layoutlmv3""", """LayoutLMv3ImageProcessor"""), ("""levit""", """LevitImageProcessor"""), ("""mask2former""", """Mask2FormerImageProcessor"""), ("""maskformer""", """MaskFormerImageProcessor"""), ("""mgp-str""", """ViTImageProcessor"""), ("""mobilenet_v1""", """MobileNetV1ImageProcessor"""), ("""mobilenet_v2""", """MobileNetV2ImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevitv2""", """MobileViTImageProcessor"""), ("""nat""", """ViTImageProcessor"""), ("""oneformer""", """OneFormerImageProcessor"""), ("""owlvit""", """OwlViTImageProcessor"""), ("""perceiver""", """PerceiverImageProcessor"""), ("""pix2struct""", """Pix2StructImageProcessor"""), ("""poolformer""", """PoolFormerImageProcessor"""), ("""regnet""", """ConvNextImageProcessor"""), ("""resnet""", """ConvNextImageProcessor"""), ("""sam""", """SamImageProcessor"""), ("""segformer""", """SegformerImageProcessor"""), ("""swiftformer""", """ViTImageProcessor"""), ("""swin""", """ViTImageProcessor"""), ("""swin2sr""", """Swin2SRImageProcessor"""), ("""swinv2""", """ViTImageProcessor"""), ("""table-transformer""", """DetrImageProcessor"""), ("""timesformer""", """VideoMAEImageProcessor"""), ("""tvlt""", """TvltImageProcessor"""), ("""upernet""", """SegformerImageProcessor"""), ("""van""", """ConvNextImageProcessor"""), ("""videomae""", """VideoMAEImageProcessor"""), ("""vilt""", """ViltImageProcessor"""), ("""vit""", """ViTImageProcessor"""), ("""vit_hybrid""", """ViTHybridImageProcessor"""), ("""vit_mae""", """ViTImageProcessor"""), ("""vit_msn""", """ViTImageProcessor"""), ("""xclip""", """CLIPImageProcessor"""), ("""yolos""", """YolosImageProcessor"""), ] ) lowerCamelCase_ : Union[str, Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def _A ( lowercase ): """simple docstring""" for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: a =model_type_to_module_name(lowercase ) a =importlib.import_module(f'''.{module_name}''' , '''transformers.models''' ) try: return getattr(lowercase , lowercase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowercase , '''__name__''' , lowercase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. a =importlib.import_module('''transformers''' ) if hasattr(lowercase , lowercase ): return getattr(lowercase , lowercase ) return None def _A ( lowercase , lowercase = None , lowercase = False , lowercase = False , lowercase = None , lowercase = None , lowercase = None , lowercase = False , **lowercase , ): """simple docstring""" a =get_file_from_repo( lowercase , lowercase , cache_dir=lowercase , force_download=lowercase , resume_download=lowercase , proxies=lowercase , use_auth_token=lowercase , revision=lowercase , local_files_only=lowercase , ) if resolved_config_file is None: logger.info( '''Could not locate the image processor configuration file, will try to use the model config instead.''' ) return {} with open(lowercase , encoding='''utf-8''' ) as reader: return json.load(lowercase ) class __A : """simple docstring""" def __init__( self ) -> Optional[Any]: raise EnvironmentError( '''AutoImageProcessor is designed to be instantiated ''' '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__A ) def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> Dict: a =kwargs.pop('''config''' , __A ) a =kwargs.pop('''trust_remote_code''' , __A ) a =True a , a =ImageProcessingMixin.get_image_processor_dict(__A , **__A ) a =config_dict.get('''image_processor_type''' , __A ) a =None if "AutoImageProcessor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoImageProcessor'''] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: a =config_dict.pop('''feature_extractor_type''' , __A ) if feature_extractor_class is not None: logger.warning( '''Could not find image processor class in the image processor config or the model config. Loading''' ''' based on pattern matching with the model\'s feature extractor configuration.''' ) a =feature_extractor_class.replace('''FeatureExtractor''' , '''ImageProcessor''' ) if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoFeatureExtractor'''] a =feature_extractor_auto_map.replace('''FeatureExtractor''' , '''ImageProcessor''' ) logger.warning( '''Could not find image processor auto map in the image processor config or the model config.''' ''' Loading based on pattern matching with the model\'s feature extractor configuration.''' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(__A , __A ): a =AutoConfig.from_pretrained(__A , **__A ) # It could be in `config.image_processor_type`` a =getattr(__A , '''image_processor_type''' , __A ) if hasattr(__A , '''auto_map''' ) and "AutoImageProcessor" in config.auto_map: a =config.auto_map['''AutoImageProcessor'''] if image_processor_class is not None: a =image_processor_class_from_name(__A ) a =image_processor_auto_map is not None a =image_processor_class is not None or type(__A ) in IMAGE_PROCESSOR_MAPPING a =resolve_trust_remote_code( __A , __A , __A , __A ) if has_remote_code and trust_remote_code: a =get_class_from_dynamic_module( __A , __A , **__A ) a =kwargs.pop('''code_revision''' , __A ) if os.path.isdir(__A ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(__A , **__A ) elif image_processor_class is not None: return image_processor_class.from_dict(__A , **__A ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(__A ) in IMAGE_PROCESSOR_MAPPING: a =IMAGE_PROCESSOR_MAPPING[type(__A )] return image_processor_class.from_dict(__A , **__A ) raise ValueError( f'''Unrecognized image processor in {pretrained_model_name_or_path}. Should have a ''' f'''`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def SCREAMING_SNAKE_CASE ( __A , __A ) -> Any: IMAGE_PROCESSOR_MAPPING.register(__A , __A )
81
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase_ : List[str] = { """configuration_chinese_clip""": [ """CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ChineseCLIPConfig""", """ChineseCLIPOnnxConfig""", """ChineseCLIPTextConfig""", """ChineseCLIPVisionConfig""", ], """processing_chinese_clip""": ["""ChineseCLIPProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""ChineseCLIPFeatureExtractor"""] lowerCamelCase_ : List[Any] = ["""ChineseCLIPImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[int] = [ """CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """ChineseCLIPModel""", """ChineseCLIPPreTrainedModel""", """ChineseCLIPTextModel""", """ChineseCLIPVisionModel""", ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys lowerCamelCase_ : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = DistilBertTokenizer __lowerCAmelCase = DistilBertTokenizerFast __lowerCAmelCase = True @slow def SCREAMING_SNAKE_CASE ( self ) -> int: a =DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
81
1
"""simple docstring""" from __future__ import annotations import numpy as np def _A ( lowercase ): """simple docstring""" a , a =np.shape(lowercase ) if rows != columns: a =( '''\'table\' has to be of square shaped array but got a ''' f'''{rows}x{columns} array:\n{table}''' ) raise ValueError(lowercase ) a =np.zeros((rows, columns) ) a =np.zeros((rows, columns) ) for i in range(lowercase ): for j in range(lowercase ): a =sum(lower[i][k] * upper[k][j] for k in range(lowercase ) ) if upper[j][j] == 0: raise ArithmeticError('''No LU decomposition exists''' ) a =(table[i][j] - total) / upper[j][j] a =1 for j in range(lowercase , lowercase ): a =sum(lower[i][k] * upper[k][j] for k in range(lowercase ) ) a =table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCamelCase_ : List[str] = { """configuration_speech_to_text""": ["""SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Speech2TextConfig"""], """processing_speech_to_text""": ["""Speech2TextProcessor"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""Speech2TextTokenizer"""] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[Any] = ["""Speech2TextFeatureExtractor"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFSpeech2TextForConditionalGeneration""", """TFSpeech2TextModel""", """TFSpeech2TextPreTrainedModel""", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = [ """SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Speech2TextForConditionalGeneration""", """Speech2TextModel""", """Speech2TextPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) lowerCamelCase_ : Tuple = logging.get_logger(__name__) lowerCamelCase_ : str = OrderedDict( [ ("""align""", """EfficientNetImageProcessor"""), ("""beit""", """BeitImageProcessor"""), ("""bit""", """BitImageProcessor"""), ("""blip""", """BlipImageProcessor"""), ("""blip-2""", """BlipImageProcessor"""), ("""bridgetower""", """BridgeTowerImageProcessor"""), ("""chinese_clip""", """ChineseCLIPImageProcessor"""), ("""clip""", """CLIPImageProcessor"""), ("""clipseg""", """ViTImageProcessor"""), ("""conditional_detr""", """ConditionalDetrImageProcessor"""), ("""convnext""", """ConvNextImageProcessor"""), ("""convnextv2""", """ConvNextImageProcessor"""), ("""cvt""", """ConvNextImageProcessor"""), ("""data2vec-vision""", """BeitImageProcessor"""), ("""deformable_detr""", """DeformableDetrImageProcessor"""), ("""deit""", """DeiTImageProcessor"""), ("""deta""", """DetaImageProcessor"""), ("""detr""", """DetrImageProcessor"""), ("""dinat""", """ViTImageProcessor"""), ("""donut-swin""", """DonutImageProcessor"""), ("""dpt""", """DPTImageProcessor"""), ("""efficientformer""", """EfficientFormerImageProcessor"""), ("""efficientnet""", """EfficientNetImageProcessor"""), ("""flava""", """FlavaImageProcessor"""), ("""focalnet""", """BitImageProcessor"""), ("""git""", """CLIPImageProcessor"""), ("""glpn""", """GLPNImageProcessor"""), ("""groupvit""", """CLIPImageProcessor"""), ("""imagegpt""", """ImageGPTImageProcessor"""), ("""instructblip""", """BlipImageProcessor"""), ("""layoutlmv2""", """LayoutLMv2ImageProcessor"""), ("""layoutlmv3""", """LayoutLMv3ImageProcessor"""), ("""levit""", """LevitImageProcessor"""), ("""mask2former""", """Mask2FormerImageProcessor"""), ("""maskformer""", """MaskFormerImageProcessor"""), ("""mgp-str""", """ViTImageProcessor"""), ("""mobilenet_v1""", """MobileNetV1ImageProcessor"""), ("""mobilenet_v2""", """MobileNetV2ImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevitv2""", """MobileViTImageProcessor"""), ("""nat""", """ViTImageProcessor"""), ("""oneformer""", """OneFormerImageProcessor"""), ("""owlvit""", """OwlViTImageProcessor"""), ("""perceiver""", """PerceiverImageProcessor"""), ("""pix2struct""", """Pix2StructImageProcessor"""), ("""poolformer""", """PoolFormerImageProcessor"""), ("""regnet""", """ConvNextImageProcessor"""), ("""resnet""", """ConvNextImageProcessor"""), ("""sam""", """SamImageProcessor"""), ("""segformer""", """SegformerImageProcessor"""), ("""swiftformer""", """ViTImageProcessor"""), ("""swin""", """ViTImageProcessor"""), ("""swin2sr""", """Swin2SRImageProcessor"""), ("""swinv2""", """ViTImageProcessor"""), ("""table-transformer""", """DetrImageProcessor"""), ("""timesformer""", """VideoMAEImageProcessor"""), ("""tvlt""", """TvltImageProcessor"""), ("""upernet""", """SegformerImageProcessor"""), ("""van""", """ConvNextImageProcessor"""), ("""videomae""", """VideoMAEImageProcessor"""), ("""vilt""", """ViltImageProcessor"""), ("""vit""", """ViTImageProcessor"""), ("""vit_hybrid""", """ViTHybridImageProcessor"""), ("""vit_mae""", """ViTImageProcessor"""), ("""vit_msn""", """ViTImageProcessor"""), ("""xclip""", """CLIPImageProcessor"""), ("""yolos""", """YolosImageProcessor"""), ] ) lowerCamelCase_ : Union[str, Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def _A ( lowercase ): """simple docstring""" for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: a =model_type_to_module_name(lowercase ) a =importlib.import_module(f'''.{module_name}''' , '''transformers.models''' ) try: return getattr(lowercase , lowercase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowercase , '''__name__''' , lowercase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. a =importlib.import_module('''transformers''' ) if hasattr(lowercase , lowercase ): return getattr(lowercase , lowercase ) return None def _A ( lowercase , lowercase = None , lowercase = False , lowercase = False , lowercase = None , lowercase = None , lowercase = None , lowercase = False , **lowercase , ): """simple docstring""" a =get_file_from_repo( lowercase , lowercase , cache_dir=lowercase , force_download=lowercase , resume_download=lowercase , proxies=lowercase , use_auth_token=lowercase , revision=lowercase , local_files_only=lowercase , ) if resolved_config_file is None: logger.info( '''Could not locate the image processor configuration file, will try to use the model config instead.''' ) return {} with open(lowercase , encoding='''utf-8''' ) as reader: return json.load(lowercase ) class __A : """simple docstring""" def __init__( self ) -> Optional[Any]: raise EnvironmentError( '''AutoImageProcessor is designed to be instantiated ''' '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__A ) def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> Dict: a =kwargs.pop('''config''' , __A ) a =kwargs.pop('''trust_remote_code''' , __A ) a =True a , a =ImageProcessingMixin.get_image_processor_dict(__A , **__A ) a =config_dict.get('''image_processor_type''' , __A ) a =None if "AutoImageProcessor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoImageProcessor'''] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: a =config_dict.pop('''feature_extractor_type''' , __A ) if feature_extractor_class is not None: logger.warning( '''Could not find image processor class in the image processor config or the model config. Loading''' ''' based on pattern matching with the model\'s feature extractor configuration.''' ) a =feature_extractor_class.replace('''FeatureExtractor''' , '''ImageProcessor''' ) if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoFeatureExtractor'''] a =feature_extractor_auto_map.replace('''FeatureExtractor''' , '''ImageProcessor''' ) logger.warning( '''Could not find image processor auto map in the image processor config or the model config.''' ''' Loading based on pattern matching with the model\'s feature extractor configuration.''' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(__A , __A ): a =AutoConfig.from_pretrained(__A , **__A ) # It could be in `config.image_processor_type`` a =getattr(__A , '''image_processor_type''' , __A ) if hasattr(__A , '''auto_map''' ) and "AutoImageProcessor" in config.auto_map: a =config.auto_map['''AutoImageProcessor'''] if image_processor_class is not None: a =image_processor_class_from_name(__A ) a =image_processor_auto_map is not None a =image_processor_class is not None or type(__A ) in IMAGE_PROCESSOR_MAPPING a =resolve_trust_remote_code( __A , __A , __A , __A ) if has_remote_code and trust_remote_code: a =get_class_from_dynamic_module( __A , __A , **__A ) a =kwargs.pop('''code_revision''' , __A ) if os.path.isdir(__A ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(__A , **__A ) elif image_processor_class is not None: return image_processor_class.from_dict(__A , **__A ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(__A ) in IMAGE_PROCESSOR_MAPPING: a =IMAGE_PROCESSOR_MAPPING[type(__A )] return image_processor_class.from_dict(__A , **__A ) raise ValueError( f'''Unrecognized image processor in {pretrained_model_name_or_path}. Should have a ''' f'''`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def SCREAMING_SNAKE_CASE ( __A , __A ) -> Any: IMAGE_PROCESSOR_MAPPING.register(__A , __A )
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : Union[str, Any] = { """configuration_table_transformer""": [ """TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TableTransformerConfig""", """TableTransformerOnnxConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TableTransformerForObjectDetection""", """TableTransformerModel""", """TableTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class __A : """simple docstring""" __lowerCAmelCase = 42 # setable values __lowerCAmelCase = 42 __lowerCAmelCase = 42 __lowerCAmelCase = None @classmethod def SCREAMING_SNAKE_CASE ( cls , __A , __A , __A ) -> Optional[Any]: return cls(common=__A , init_noise_sigma=__A , timesteps=__A ) @dataclass class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = 42 class __A ( _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = [e.name for e in FlaxKarrasDiffusionSchedulers] __lowerCAmelCase = 42 @property def SCREAMING_SNAKE_CASE ( self ) -> List[str]: return True @register_to_config def __init__( self , __A = 1000 , __A = 0.0_001 , __A = 0.02 , __A = "linear" , __A = None , __A = "fixed_small" , __A = True , __A = "epsilon" , __A = jnp.floataa , ) -> int: a =dtype def SCREAMING_SNAKE_CASE ( self , __A = None ) -> DDPMSchedulerState: if common is None: a =CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution a =jnp.array(1.0 , dtype=self.dtype ) a =jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__A , init_noise_sigma=__A , timesteps=__A , ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A = None ) -> jnp.ndarray: return sample def SCREAMING_SNAKE_CASE ( self , __A , __A , __A = () ) -> DDPMSchedulerState: a =self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 a =(jnp.arange(0 , __A ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__A , timesteps=__A , ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A=None , __A=None ) -> Optional[Any]: a =state.common.alphas_cumprod[t] a =jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample a =(1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: a =self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": a =jnp.clip(__A , a_min=1E-2_0 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": a =jnp.log(jnp.clip(__A , a_min=1E-2_0 ) ) elif variance_type == "fixed_large": a =state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log a =jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": a =variance a =state.common.betas[t] a =(predicted_variance + 1) / 2 a =frac * max_log + (1 - frac) * min_log return variance def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A = None , __A = True , ) -> Union[FlaxDDPMSchedulerOutput, Tuple]: a =timestep if key is None: a =jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: a , a =jnp.split(__A , sample.shape[1] , axis=1 ) else: a =None # 1. compute alphas, betas a =state.common.alphas_cumprod[t] a =jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) a =1 - alpha_prod_t a =1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": a =(sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": a =model_output elif self.config.prediction_type == "v_prediction": a =(alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: a =jnp.clip(__A , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf a =(alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t a =state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf a =pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): a =jax.random.split(__A , num=1 ) a =jax.random.normal(__A , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(__A , __A , predicted_variance=__A ) ** 0.5) * noise a =jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) a =pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__A , state=__A ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , ) -> jnp.ndarray: return add_noise_common(state.common , __A , __A , __A ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , ) -> jnp.ndarray: return get_velocity_common(state.common , __A , __A , __A ) def __len__( self ) -> Dict: return self.config.num_train_timesteps
81
"""simple docstring""" from __future__ import annotations import math def _A ( lowercase ): """simple docstring""" if num <= 0: a =f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(lowercase ) a =[True] * (num + 1) a =[] a =2 a =int(math.sqrt(lowercase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(lowercase ) # Set multiples of start be False for i in range(start * start , num + 1 , lowercase ): if sieve[i] is True: a =False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(lowercase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
81
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ : str = logging.get_logger(__name__) lowerCamelCase_ : str = { """google/pegasus-large""": """https://huggingface.co/google/pegasus-large/resolve/main/config.json""", # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "pegasus" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , __A=5_0265 , __A=1024 , __A=12 , __A=4096 , __A=16 , __A=12 , __A=4096 , __A=16 , __A=0.0 , __A=0.0 , __A=True , __A=True , __A="gelu" , __A=1024 , __A=0.1 , __A=0.0 , __A=0.0 , __A=0.02 , __A=0 , __A=False , __A=0 , __A=1 , __A=1 , **__A , ) -> Union[str, Any]: a =vocab_size a =max_position_embeddings a =d_model a =encoder_ffn_dim a =encoder_layers a =encoder_attention_heads a =decoder_ffn_dim a =decoder_layers a =decoder_attention_heads a =dropout a =attention_dropout a =activation_dropout a =activation_function a =init_std a =encoder_layerdrop a =decoder_layerdrop a =use_cache a =encoder_layers a =scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=__A , eos_token_id=__A , is_encoder_decoder=__A , decoder_start_token_id=__A , forced_eos_token_id=__A , **__A , ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.d_model
81
"""simple docstring""" 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 __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = BertTokenizer __lowerCAmelCase = BertTokenizerFast __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = filter_non_english def SCREAMING_SNAKE_CASE ( self ) -> List[str]: super().setUp() a =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a =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 SCREAMING_SNAKE_CASE ( self , __A ) -> Union[str, Any]: a ='''UNwant\u00E9d,running''' a ='''unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.tokenizer_class(self.vocab_file ) a =tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__A , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [9, 6, 7, 12, 10, 11] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: if not self.test_rust_tokenizer: return a =self.get_tokenizer() a =self.get_rust_tokenizer() a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) # With lower casing a =self.get_tokenizer(do_lower_case=__A ) a =self.get_rust_tokenizer(do_lower_case=__A ) a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Any: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =BasicTokenizer(do_lower_case=__A , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =BasicTokenizer() a ='''a\n\'ll !!to?\'d of, can\'t.''' a =['''a''', '''\'''', '''ll''', '''!''', '''!''', '''to''', '''?''', '''\'''', '''d''', '''of''', ''',''', '''can''', '''\'''', '''t''', '''.'''] self.assertListEqual(tokenizer.tokenize(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a ={} for i, token in enumerate(__A ): a =i a =WordpieceTokenizer(vocab=__A , 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 SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE ( self ) -> Any: 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 SCREAMING_SNAKE_CASE ( self ) -> str: 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 SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.get_tokenizer() a =self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.tokenizer_class.from_pretrained('''bert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def SCREAMING_SNAKE_CASE ( self ) -> Any: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' a =tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) a =tokenizer_r.do_lower_case if hasattr(__A , '''do_lower_case''' ) else False a =( [ ((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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =['''的''', '''人''', '''有'''] a =''''''.join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =True a =self.tokenizer_class.from_pretrained(__A , **__A ) a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) a =False a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =self.tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". a =[ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A )
81
1
"""simple docstring""" from PIL import Image def _A ( lowercase , lowercase ): """simple docstring""" a =(2_59 * (level + 2_55)) / (2_55 * (2_59 - level)) def contrast(lowercase ) -> int: return int(1_28 + factor * (c - 1_28) ) return img.point(lowercase ) if __name__ == "__main__": # Load image with Image.open("""image_data/lena.jpg""") as img: # Change contrast to 170 lowerCamelCase_ : Dict = change_contrast(img, 1_7_0) cont_img.save("""image_data/lena_high_contrast.png""", format="""png""")
81
"""simple docstring""" import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ : Union[str, Any] = logging.get_logger(__name__) lowerCamelCase_ : Any = { """microsoft/conditional-detr-resnet-50""": ( """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json""" ), } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "conditional_detr" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , __A=True , __A=None , __A=3 , __A=300 , __A=6 , __A=2048 , __A=8 , __A=6 , __A=2048 , __A=8 , __A=0.0 , __A=0.0 , __A=True , __A="relu" , __A=256 , __A=0.1 , __A=0.0 , __A=0.0 , __A=0.02 , __A=1.0 , __A=False , __A="sine" , __A="resnet50" , __A=True , __A=False , __A=2 , __A=5 , __A=2 , __A=1 , __A=1 , __A=2 , __A=5 , __A=2 , __A=0.25 , **__A , ) -> List[Any]: if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) a =CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(__A , __A ): a =backbone_config.get('''model_type''' ) a =CONFIG_MAPPING[backbone_model_type] a =config_class.from_dict(__A ) a =use_timm_backbone a =backbone_config a =num_channels a =num_queries a =d_model a =encoder_ffn_dim a =encoder_layers a =encoder_attention_heads a =decoder_ffn_dim a =decoder_layers a =decoder_attention_heads a =dropout a =attention_dropout a =activation_dropout a =activation_function a =init_std a =init_xavier_std a =encoder_layerdrop a =decoder_layerdrop a =encoder_layers a =auxiliary_loss a =position_embedding_type a =backbone a =use_pretrained_backbone a =dilation # Hungarian matcher a =class_cost a =bbox_cost a =giou_cost # Loss coefficients a =mask_loss_coefficient a =dice_loss_coefficient a =cls_loss_coefficient a =bbox_loss_coefficient a =giou_loss_coefficient a =focal_alpha super().__init__(is_encoder_decoder=__A , **__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.d_model def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: a =self.backbone_config.to_dict() a =self.__class__.model_type return output class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def SCREAMING_SNAKE_CASE ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE ( self ) -> int: return 12
81
1
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" @staticmethod @abstractmethod def SCREAMING_SNAKE_CASE ( __A ) -> int: raise NotImplementedError() @abstractmethod def SCREAMING_SNAKE_CASE ( self ) -> str: raise NotImplementedError()
81
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" while second != 0: a =first & second first ^= second a =c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase_ : Dict = int(input("""Enter the first number: """).strip()) lowerCamelCase_ : List[Any] = int(input("""Enter the second number: """).strip()) print(F'{add(first, second) = }')
81
1
"""simple docstring""" import random import unittest import torch from diffusers import IFInpaintingPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class __A ( _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = IFInpaintingPipeline __lowerCAmelCase = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"} __lowerCAmelCase = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS __lowerCAmelCase = PipelineTesterMixin.required_optional_params - {"latents"} def SCREAMING_SNAKE_CASE ( self ) -> str: return self._get_dummy_components() def SCREAMING_SNAKE_CASE ( self , __A , __A=0 ) -> List[str]: if str(__A ).startswith('''mps''' ): a =torch.manual_seed(__A ) else: a =torch.Generator(device=__A ).manual_seed(__A ) a =floats_tensor((1, 3, 32, 32) , rng=random.Random(__A ) ).to(__A ) a =floats_tensor((1, 3, 32, 32) , rng=random.Random(__A ) ).to(__A ) a ={ '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def SCREAMING_SNAKE_CASE ( self ) -> str: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def SCREAMING_SNAKE_CASE ( self ) -> str: # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1E-1 ) def SCREAMING_SNAKE_CASE ( self ) -> Any: self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: self._test_save_load_local() def SCREAMING_SNAKE_CASE ( self ) -> int: self._test_inference_batch_single_identical( expected_max_diff=1E-2 , )
81
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" a =ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' '''helper utility that will spawn up ''' '''multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=lowercase , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=lowercase , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=lowercase ) return parser.parse_args() def _A ( ): """simple docstring""" a =parse_args() # Import training_script as a module. a =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) a =script_fpath.stem a =importlib.import_module(lowercase ) # Patch sys.argv a =[args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
81
1
"""simple docstring""" lowerCamelCase_ : Optional[int] = [ """Audio""", """Array2D""", """Array3D""", """Array4D""", """Array5D""", """ClassLabel""", """Features""", """Sequence""", """Value""", """Image""", """Translation""", """TranslationVariableLanguages""", ] from .audio import Audio from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, ClassLabel, Features, Sequence, Value from .image import Image from .translation import Translation, TranslationVariableLanguages
81
"""simple docstring""" import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor lowerCamelCase_ : str = logging.get_logger(__name__) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , *__A , **__A ) -> None: warnings.warn( '''The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use CLIPImageProcessor instead.''' , __A , ) super().__init__(*__A , **__A )
81
1
"""simple docstring""" lowerCamelCase_ : int = range(2, 2_0 + 1) lowerCamelCase_ : Tuple = [1_0**k for k in range(ks[-1] + 1)] lowerCamelCase_ : dict[int, dict[int, list[list[int]]]] = {} def _A ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =sum(a_i[j] for j in range(lowercase , len(lowercase ) ) ) a =sum(a_i[j] * base[j] for j in range(min(len(lowercase ) , lowercase ) ) ) a , a =0, 0 a =n - i a =memo.get(lowercase ) if sub_memo is not None: a =sub_memo.get(lowercase ) if jumps is not None and len(lowercase ) > 0: # find and make the largest jump without going over a =-1 for _k in range(len(lowercase ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: a =_k break if max_jump >= 0: a , a , a =jumps[max_jump] # since the difference between jumps is cached, add c a =diff + c for j in range(min(lowercase , len(lowercase ) ) ): a , a =divmod(lowercase , 10 ) if new_c > 0: add(lowercase , lowercase , lowercase ) else: a =[] else: a ={c: []} a =sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps a , a =next_term(lowercase , k - 1 , i + dn , lowercase ) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead a , a =compute(lowercase , lowercase , i + dn , lowercase ) diff += _diff dn += terms_jumped a =sub_memo[c] # keep jumps sorted by # of terms skipped a =0 while j < len(lowercase ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(lowercase , (diff, dn, k) ) return (diff, dn) def _A ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" if i >= n: return 0, i if k > len(lowercase ): a_i.extend([0 for _ in range(k - len(lowercase ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) a =i a , a , a =0, 0, 0 for j in range(len(lowercase ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 a =ds_c + ds_b diff += addend a =0 for j in range(lowercase ): a =a_i[j] + addend a , a =divmod(lowercase , 10 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(lowercase , lowercase , lowercase ) return diff, i - start_i def _A ( lowercase , lowercase , lowercase ): """simple docstring""" for j in range(lowercase , len(lowercase ) ): a =digits[j] + addend if s >= 10: a , a =divmod(lowercase , 10 ) a =addend // 10 + quotient else: a =s a =addend // 10 if addend == 0: break while addend > 0: a , a =divmod(lowercase , 10 ) digits.append(lowercase ) def _A ( lowercase = 10**15 ): """simple docstring""" a =[1] a =1 a =0 while True: a , a =next_term(lowercase , 20 , i + dn , lowercase ) dn += terms_jumped if dn == n - i: break a =0 for j in range(len(lowercase ) ): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(F'{solution() = }')
81
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" return number | (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number & ~(1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number ^ (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return ((number >> position) & 1) == 1 def _A ( lowercase , lowercase ): """simple docstring""" return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
81
1
"""simple docstring""" import requests from bsa import BeautifulSoup def _A ( lowercase = "AAPL" ): """simple docstring""" a =f'''https://in.finance.yahoo.com/quote/{symbol}?s={symbol}''' a =BeautifulSoup(requests.get(lowercase ).text , '''html.parser''' ) a ='''My(6px) Pos(r) smartphone_Mt(6px)''' return soup.find('''div''' , class_=class_ ).find('''span''' ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(F'Current {symbol:<4} stock price is {stock_price(symbol):>8}')
81
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _A ( lowercase ): """simple docstring""" a =SwinvaConfig() a =swinva_name.split('''_''' ) a =name_split[1] if "to" in name_split[3]: a =int(name_split[3][-3:] ) else: a =int(name_split[3] ) if "to" in name_split[2]: a =int(name_split[2][-2:] ) else: a =int(name_split[2][6:] ) if model_size == "tiny": a =96 a =(2, 2, 6, 2) a =(3, 6, 12, 24) elif model_size == "small": a =96 a =(2, 2, 18, 2) a =(3, 6, 12, 24) elif model_size == "base": a =1_28 a =(2, 2, 18, 2) a =(4, 8, 16, 32) else: a =1_92 a =(2, 2, 18, 2) a =(6, 12, 24, 48) if "to" in swinva_name: a =(12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): a =2_18_41 a ='''huggingface/label-files''' a ='''imagenet-22k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} else: a =10_00 a ='''huggingface/label-files''' a ='''imagenet-1k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} a =img_size a =num_classes a =embed_dim a =depths a =num_heads a =window_size return config def _A ( lowercase ): """simple docstring""" if "patch_embed.proj" in name: a =name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: a =name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: a ='''encoder.''' + name if "attn.proj" in name: a =name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: a =name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: a =name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: a =name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: a =name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: a =name.replace('''mlp.fc2''' , '''output.dense''' ) if "q_bias" in name: a =name.replace('''q_bias''' , '''query.bias''' ) if "k_bias" in name: a =name.replace('''k_bias''' , '''key.bias''' ) if "v_bias" in name: a =name.replace('''v_bias''' , '''value.bias''' ) if "cpb_mlp" in name: a =name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' ) if name == "norm.weight": a ='''layernorm.weight''' if name == "norm.bias": a ='''layernorm.bias''' if "head" in name: a =name.replace('''head''' , '''classifier''' ) else: a ='''swinv2.''' + name return name def _A ( lowercase , lowercase ): """simple docstring""" for key in orig_state_dict.copy().keys(): a =orig_state_dict.pop(lowercase ) if "mask" in key: continue elif "qkv" in key: a =key.split('''.''' ) a =int(key_split[1] ) a =int(key_split[3] ) a =model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a =val[:dim, :] a =val[dim : dim * 2, :] a =val[-dim:, :] else: a =val[:dim] a =val[ dim : dim * 2 ] a =val[-dim:] else: a =val return orig_state_dict def _A ( lowercase , lowercase ): """simple docstring""" a =timm.create_model(lowercase , pretrained=lowercase ) timm_model.eval() a =get_swinva_config(lowercase ) a =SwinvaForImageClassification(lowercase ) model.eval() a =convert_state_dict(timm_model.state_dict() , lowercase ) model.load_state_dict(lowercase ) a ='''http://images.cocodataset.org/val2017/000000039769.jpg''' a =AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swinva_name.replace('''_''' , '''-''' ) ) ) a =Image.open(requests.get(lowercase , stream=lowercase ).raw ) a =image_processor(images=lowercase , return_tensors='''pt''' ) a =timm_model(inputs['''pixel_values'''] ) a =model(**lowercase ).logits assert torch.allclose(lowercase , lowercase , atol=1E-3 ) print(f'''Saving model {swinva_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) model.push_to_hub( repo_path_or_name=Path(lowercase , lowercase ) , organization='''nandwalritik''' , commit_message='''Add model''' , ) if __name__ == "__main__": lowerCamelCase_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swinv2_name""", default="""swinv2_tiny_patch4_window8_256""", type=str, help="""Name of the Swinv2 timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowerCamelCase_ : Union[str, Any] = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
81
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "openai/whisper-base" __lowerCAmelCase = ( "This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the " "transcribed text." ) __lowerCAmelCase = "transcriber" __lowerCAmelCase = WhisperProcessor __lowerCAmelCase = WhisperForConditionalGeneration __lowerCAmelCase = ["audio"] __lowerCAmelCase = ["text"] def SCREAMING_SNAKE_CASE ( self , __A ) -> List[Any]: return self.pre_processor(__A , return_tensors='''pt''' ).input_features def SCREAMING_SNAKE_CASE ( self , __A ) -> Tuple: return self.model.generate(inputs=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: return self.pre_processor.batch_decode(__A , skip_special_tokens=__A )[0]
81
"""simple docstring""" lowerCamelCase_ : Any = [ """DownloadConfig""", """DownloadManager""", """DownloadMode""", """StreamingDownloadManager""", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
81
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ : List[Any] = logging.get_logger(__name__) lowerCamelCase_ : Any = { """microsoft/cvt-13""": """https://huggingface.co/microsoft/cvt-13/resolve/main/config.json""", # See all Cvt models at https://huggingface.co/models?filter=cvt } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "cvt" def __init__( self , __A=3 , __A=[7, 3, 3] , __A=[4, 2, 2] , __A=[2, 1, 1] , __A=[64, 192, 384] , __A=[1, 3, 6] , __A=[1, 2, 10] , __A=[4.0, 4.0, 4.0] , __A=[0.0, 0.0, 0.0] , __A=[0.0, 0.0, 0.0] , __A=[0.0, 0.0, 0.1] , __A=[True, True, True] , __A=[False, False, True] , __A=["dw_bn", "dw_bn", "dw_bn"] , __A=[3, 3, 3] , __A=[1, 1, 1] , __A=[2, 2, 2] , __A=[1, 1, 1] , __A=[1, 1, 1] , __A=0.02 , __A=1E-1_2 , **__A , ) -> Tuple: super().__init__(**__A ) a =num_channels a =patch_sizes a =patch_stride a =patch_padding a =embed_dim a =num_heads a =depth a =mlp_ratio a =attention_drop_rate a =drop_rate a =drop_path_rate a =qkv_bias a =cls_token a =qkv_projection_method a =kernel_qkv a =padding_kv a =stride_kv a =padding_q a =stride_q a =initializer_range a =layer_norm_eps
81
"""simple docstring""" from scipy.stats import pearsonr import datasets lowerCamelCase_ : Optional[int] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ lowerCamelCase_ : Optional[Any] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ lowerCamelCase_ : Optional[int] = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Dict: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float''' ), '''references''': datasets.Value('''float''' ), } ) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A=False ) -> Optional[Any]: if return_pvalue: a =pearsonr(__A , __A ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(__A , __A )[0] )}
81
1
"""simple docstring""" from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging lowerCamelCase_ : List[str] = logging.get_logger(__name__) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = ["audio_values", "audio_mask"] def __init__( self , __A=2048 , __A=1 , __A=[16, 16] , __A=128 , __A=4_4100 , __A=86 , __A=2048 , __A=0.0 , **__A , ) -> Union[str, Any]: super().__init__( feature_size=__A , sampling_rate=__A , padding_value=__A , **__A , ) a =spectrogram_length a =num_channels a =patch_size a =feature_size // self.patch_size[1] a =n_fft a =sampling_rate // hop_length_to_sampling_rate a =sampling_rate a =padding_value a =mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=__A , min_frequency=0.0 , max_frequency=22_050.0 , sampling_rate=__A , norm='''slaney''' , mel_scale='''slaney''' , ).T def SCREAMING_SNAKE_CASE ( self , __A ) -> np.ndarray: a =spectrogram( __A , window_function(self.n_fft , '''hann''' ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters.T , log_mel='''dB''' , db_range=80.0 , ) a =log_spec[:, :-1] a =log_spec - 20.0 a =np.clip(log_spec / 40.0 , -2.0 , 0.0 ) + 1.0 return log_spec def __call__( self , __A , __A = None , __A = True , __A = None , __A = False , __A = False , **__A , ) -> BatchFeature: if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( '''This feature extractor is set to support sampling rate''' f''' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled''' f''' with {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.''' ) a =isinstance(__A , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' ) a =is_batched_numpy or ( isinstance(__A , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: a =[np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(__A , np.ndarray ): a =np.asarray(__A , dtype=np.floataa ) elif isinstance(__A , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): a =raw_speech.astype(np.floataa ) # always return batch if not is_batched: a =[np.asarray([raw_speech] ).T] # Convert audio signals to log mel spectrograms, truncate by time axis a =[ self._np_extract_fbank_features(waveform.squeeze() ).T[: self.spectrogram_length] for waveform in raw_speech ] if isinstance(audio_features[0] , __A ): a =[np.asarray(__A , dtype=np.floataa ) for feature in audio_features] # Create audio attention mask a =max( [ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len for feature in audio_features] ) # The maximum number of audio patches in a batch if return_attention_mask: a =[ (ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [1] + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [0] for feature in audio_features ] a =np.array(__A ).astype(np.floataa ) # convert into correct format for padding a =max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch a =np.ones([len(__A ), 1, max_time_len, self.feature_size] ).astype(np.floataa ) a =padded_audio_features * self.padding_value for i in range(len(__A ) ): a =audio_features[i] a =feature # return as BatchFeature if return_attention_mask: a ={'''audio_values''': padded_audio_features, '''audio_mask''': audio_mask} else: a ={'''audio_values''': padded_audio_features} a =BatchFeature(data=__A , tensor_type=__A ) return encoded_inputs
81
"""simple docstring""" lowerCamelCase_ : int = """ # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git """ lowerCamelCase_ : Dict = [{"""type""": """code""", """content""": INSTALL_CONTENT}] lowerCamelCase_ : Union[str, Any] = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
81
1
"""simple docstring""" def _A ( lowercase = 50 ): """simple docstring""" a =[1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F'{solution() = }')
81
"""simple docstring""" def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =set() # Replace all the whitespace in our sentence a =input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowercase ) == 26 def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =[False] * 26 for char in input_str: if char.islower(): a =True elif char.isupper(): a =True return all(lowercase ) def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _A ( ): """simple docstring""" from timeit import timeit a ='''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowercase ) ) print(timeit('''is_pangram_faster()''' , setup=lowercase ) ) print(timeit('''is_pangram_fastest()''' , setup=lowercase ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
81
1
"""simple docstring""" import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def _A ( lowercase , lowercase ): """simple docstring""" assert isinstance(lowercase , lowercase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def _A ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =tmp_path / '''cache''' a ={'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a =SqlDatasetReader( '''dataset''' , '''sqlite:///''' + sqlite_path , cache_dir=lowercase , keep_in_memory=lowercase ).read() _check_sql_dataset(lowercase , lowercase ) @require_sqlalchemy @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def _A ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =tmp_path / '''cache''' a ={'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} a =features.copy() if features else default_expected_features a =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) a =SqlDatasetReader('''dataset''' , '''sqlite:///''' + sqlite_path , features=lowercase , cache_dir=lowercase ).read() _check_sql_dataset(lowercase , lowercase ) def _A ( lowercase ): """simple docstring""" with contextlib.closing(sqlitea.connect(lowercase ) ) as con: a =con.cursor() cur.execute('''SELECT * FROM dataset''' ) for row in cur: yield row @require_sqlalchemy def _A ( lowercase , lowercase , lowercase ): """simple docstring""" a =tmp_path / '''cache''' a =os.path.join(lowercase , '''tmp.sql''' ) a =SqlDatasetReader('''dataset''' , '''sqlite:///''' + sqlite_path , cache_dir=lowercase ).read() SqlDatasetWriter(lowercase , '''dataset''' , '''sqlite:///''' + output_sqlite_path , num_proc=1 ).write() a =iter_sql_file(lowercase ) a =iter_sql_file(lowercase ) for rowa, rowa in zip(lowercase , lowercase ): assert rowa == rowa @require_sqlalchemy def _A ( lowercase , lowercase , lowercase ): """simple docstring""" a =tmp_path / '''cache''' a =os.path.join(lowercase , '''tmp.sql''' ) a =SqlDatasetReader('''dataset''' , '''sqlite:///''' + sqlite_path , cache_dir=lowercase ).read() SqlDatasetWriter(lowercase , '''dataset''' , '''sqlite:///''' + output_sqlite_path , num_proc=2 ).write() a =iter_sql_file(lowercase ) a =iter_sql_file(lowercase ) for rowa, rowa in zip(lowercase , lowercase ): assert rowa == rowa @require_sqlalchemy def _A ( lowercase , lowercase , lowercase ): """simple docstring""" a =tmp_path / '''cache''' a =os.path.join(lowercase , '''tmp.sql''' ) a =SqlDatasetReader('''dataset''' , '''sqlite:///''' + sqlite_path , cache_dir=lowercase ).read() with pytest.raises(lowercase ): SqlDatasetWriter(lowercase , '''dataset''' , '''sqlite:///''' + output_sqlite_path , num_proc=0 ).write()
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys lowerCamelCase_ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class __A : """simple docstring""" def __init__( self , __A , __A=13 , __A=7 , __A=True , __A=True , __A=True , __A=True , __A=99 , __A=32 , __A=5 , __A=4 , __A=37 , __A="gelu" , __A=0.1 , __A=0.1 , __A=128 , __A=32 , __A=16 , __A=2 , __A=0.02 , __A=3 , __A=4 , __A=None , ) -> Union[str, Any]: a =parent a =batch_size a =seq_length a =is_training a =use_input_mask a =use_token_type_ids a =use_labels a =vocab_size a =hidden_size a =num_hidden_layers a =num_attention_heads a =intermediate_size a =hidden_act a =hidden_dropout_prob a =attention_probs_dropout_prob a =max_position_embeddings a =type_vocab_size a =type_sequence_label_size a =initializer_range a =num_labels a =num_choices a =scope def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a =None if self.use_input_mask: a =random_attention_mask([self.batch_size, self.seq_length] ) a =None if self.use_token_type_ids: a =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a =None a =None a =None if self.use_labels: a =ids_tensor([self.batch_size] , self.type_sequence_label_size ) a =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a =ids_tensor([self.batch_size] , self.num_choices ) a =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self ) -> Tuple: return NezhaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__A , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) =self.prepare_config_and_inputs() a =True a =floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) a =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 SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> Tuple: a =NezhaModel(config=__A ) model.to(__A ) model.eval() a =model(__A , attention_mask=__A , token_type_ids=__A ) a =model(__A , token_type_ids=__A ) a =model(__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A , __A , __A , ) -> List[Any]: a =True a =NezhaModel(__A ) model.to(__A ) model.eval() a =model( __A , attention_mask=__A , token_type_ids=__A , encoder_hidden_states=__A , encoder_attention_mask=__A , ) a =model( __A , attention_mask=__A , token_type_ids=__A , encoder_hidden_states=__A , ) a =model(__A , attention_mask=__A , token_type_ids=__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> List[Any]: a =NezhaForMaskedLM(config=__A ) model.to(__A ) model.eval() a =model(__A , attention_mask=__A , token_type_ids=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> int: a =NezhaForNextSentencePrediction(config=__A ) model.to(__A ) model.eval() a =model( __A , attention_mask=__A , token_type_ids=__A , labels=__A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> Any: a =NezhaForPreTraining(config=__A ) model.to(__A ) model.eval() a =model( __A , attention_mask=__A , token_type_ids=__A , labels=__A , next_sentence_label=__A , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> List[str]: a =NezhaForQuestionAnswering(config=__A ) model.to(__A ) model.eval() a =model( __A , attention_mask=__A , token_type_ids=__A , start_positions=__A , end_positions=__A , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> Tuple: a =self.num_labels a =NezhaForSequenceClassification(__A ) model.to(__A ) model.eval() a =model(__A , attention_mask=__A , token_type_ids=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> Union[str, Any]: a =self.num_labels a =NezhaForTokenClassification(config=__A ) model.to(__A ) model.eval() a =model(__A , attention_mask=__A , token_type_ids=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A , __A ) -> Union[str, Any]: a =self.num_choices a =NezhaForMultipleChoice(config=__A ) model.to(__A ) model.eval() a =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a =token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a =model( __A , attention_mask=__A , token_type_ids=__A , labels=__A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) =config_and_inputs a ={'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __A ( _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) __lowerCAmelCase = ( { "feature-extraction": NezhaModel, "fill-mask": NezhaForMaskedLM, "question-answering": NezhaForQuestionAnswering, "text-classification": NezhaForSequenceClassification, "token-classification": NezhaForTokenClassification, "zero-shot": NezhaForSequenceClassification, } if is_torch_available() else {} ) __lowerCAmelCase = True def SCREAMING_SNAKE_CASE ( self , __A , __A , __A=False ) -> Union[str, Any]: a =super()._prepare_for_class(__A , __A , return_labels=__A ) if return_labels: if model_class in get_values(__A ): a =torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__A ) a =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__A ) return inputs_dict def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =NezhaModelTester(self ) a =ConfigTester(self , config_class=__A , hidden_size=37 ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: # This regression test was failing with PyTorch < 1.3 ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) =self.model_tester.prepare_config_and_inputs_for_decoder() a =None self.model_tester.create_and_check_model_as_decoder( __A , __A , __A , __A , __A , __A , __A , __A , __A , ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__A ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Any: for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a =NezhaModel.from_pretrained(__A ) self.assertIsNotNone(__A ) @slow @require_torch_gpu def SCREAMING_SNAKE_CASE ( self ) -> str: a , a =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return a =True a =model_class(config=__A ) a =self._prepare_for_class(__A , __A ) a =torch.jit.trace( __A , (inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__A , os.path.join(__A , '''bert.pt''' ) ) a =torch.jit.load(os.path.join(__A , '''bert.pt''' ) , map_location=__A ) loaded(inputs_dict['''input_ids'''].to(__A ) , inputs_dict['''attention_mask'''].to(__A ) ) @require_torch class __A ( unittest.TestCase ): """simple docstring""" @slow def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =NezhaModel.from_pretrained('''sijunhe/nezha-cn-base''' ) a =torch.tensor([[0, 1, 2, 3, 4, 5]] ) a =torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): a =model(__A , attention_mask=__A )[0] a =torch.Size((1, 6, 768) ) self.assertEqual(output.shape , __A ) a =torch.tensor([[[0.0_685, 0.2_441, 0.1_102], [0.0_600, 0.1_906, 0.1_349], [0.0_221, 0.0_819, 0.0_586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __A , atol=1E-4 ) ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =NezhaForMaskedLM.from_pretrained('''sijunhe/nezha-cn-base''' ) a =torch.tensor([[0, 1, 2, 3, 4, 5]] ) a =torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): a =model(__A , attention_mask=__A )[0] a =torch.Size((1, 6, 2_1128) ) self.assertEqual(output.shape , __A ) a =torch.tensor( [[-2.7_939, -1.7_902, -2.2_189], [-2.8_585, -1.8_908, -2.3_723], [-2.6_499, -1.7_750, -2.2_558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __A , atol=1E-4 ) )
81
"""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 lowerCamelCase_ : Dict = logging.getLogger(__name__) lowerCamelCase_ : Tuple = """pytorch_model.bin""" @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co."}, ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the training data."} ) __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the data to predict on."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "A csv or a json file containing the validation data."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The name of the task to train on."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The list of labels for the task."} ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "The output directory where the model predictions and checkpoints will be written."} ) __lowerCAmelCase = dataclasses.field( default="accuracy", metadata={"help": "The evaluation metric used for the task."} ) __lowerCAmelCase = dataclasses.field( default="no", metadata={ "help": "The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]" }, ) __lowerCAmelCase = dataclasses.field( default=10, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={ "help": "How much the specified evaluation metric must improve to satisfy early stopping conditions." }, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the confidence score."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the validation performance."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to fine-tune on labeled data after pseudo training."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={"help": "Confidence threshold for pseudo-labeled data filtering."}, ) __lowerCAmelCase = dataclasses.field( default=100, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Random seed for initialization."}, ) def _A ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: a =dataset.filter(lambda lowercase : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 a =int(eval_result * len(lowercase ) ) print(lowercase ) a =dataset.sort('''probability''' , reverse=lowercase ) a =dataset.select(range(lowercase ) ) a =dataset.remove_columns(['''label''', '''probability'''] ) a =dataset.rename_column('''prediction''' , '''label''' ) a =dataset.map(lambda lowercase : {"label": idalabel[example["label"]]} ) a =dataset.shuffle(seed=args.seed ) a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(lowercase , index=lowercase ) else: dataset.to_json(lowercase ) def _A ( lowercase , lowercase , lowercase , lowercase , **lowercase ): """simple docstring""" a =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() a =STModelArguments(model_name_or_path=lowercase ) a =STDataArguments(train_file=lowercase , infer_file=lowercase ) a =STTrainingArguments(output_dir=lowercase ) a =argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(lowercase ).items(): setattr(lowercase , lowercase , lowercase ) for key, value in kwargs.items(): if hasattr(lowercase , lowercase ): setattr(lowercase , lowercase , lowercase ) # Sanity checks a ={} a =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 a =args.train_file a =args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None a =args.eval_file for key in data_files: a =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: a =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...''' ) a =f'''{args.output_dir}/self-train_iter-{{}}'''.format a =data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=lowercase ) os.makedirs(lowercase , exist_ok=lowercase ) accelerator.wait_for_everyone() a =None a =None a =0 a =False # Show the progress bar a =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 ) ): a =data_dir_format(lowercase ) assert os.path.exists(lowercase ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 a =os.path.join(lowercase , '''stage-1''' ) a ={ '''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(lowercase , lowercase ): arguments_dict.update({key: value} ) a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 1 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 1.''' , lowercase ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data a =os.path.join(lowercase , '''best-checkpoint''' ) a =os.path.join(lowercase , '''stage-2''' ) # Update arguments_dict a =model_path a =data_files['''train'''] a =current_output_dir a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 2 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 2.''' , lowercase ) a =iteration a =data_dir_format(iteration + 1 ) a =AutoConfig.from_pretrained(os.path.join(lowercase , '''best-checkpoint''' ) ) a =config.idalabel a =os.path.join(lowercase , '''eval_results_best-checkpoint.json''' ) a =os.path.join(lowercase , '''test_results_best-checkpoint.json''' ) assert os.path.exists(lowercase ) with open(lowercase , '''r''' ) as f: a =float(json.load(lowercase )[args.eval_metric] ) a =os.path.join(lowercase , '''infer_output_best-checkpoint.csv''' ) assert os.path.exists(lowercase ) # Loading the dataset from local csv or json files. a =load_dataset(args.data_file_extension , data_files={'''data''': data_files['''infer''']} )['''data'''] a =load_dataset('''csv''' , data_files={'''data''': infer_output_file} )['''data'''] if accelerator.is_main_process: os.makedirs(lowercase , exist_ok=lowercase ) shutil.copy(lowercase , os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(lowercase ): shutil.copy(lowercase , os.path.join(lowercase , f'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) accelerator.wait_for_everyone() a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: a =eval_result if best_iteration is None: a =new_iteration a =new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: a =new_iteration a =new_eval_result a =0 else: if new_eval_result == best_eval_result: a =new_iteration a =new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: a =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''' , lowercase ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) , os.path.join(lowercase , '''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 , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(lowercase , '''eval_results_best-iteration.json''' ) , )
81
1
"""simple docstring""" from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class __A ( nn.Module ): """simple docstring""" def __init__( self , __A = 16 , __A = 88 , __A = None , __A = 1 , __A = 0.0 , __A = 32 , __A = None , __A = False , __A = None , __A = None , __A = "geglu" , __A = None , ) -> Tuple: super().__init__() a =nn.ModuleList( [ TransformeraDModel( num_attention_heads=__A , attention_head_dim=__A , in_channels=__A , num_layers=__A , dropout=__A , norm_num_groups=__A , cross_attention_dim=__A , attention_bias=__A , sample_size=__A , num_vector_embeds=__A , activation_fn=__A , num_embeds_ada_norm=__A , ) 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 a =0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` a =[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])` a =[1, 0] def SCREAMING_SNAKE_CASE ( self , __A , __A , __A=None , __A=None , __A=None , __A = True , ) -> List[Any]: a =hidden_states a =[] a =0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens a =encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] a =self.transformer_index_for_condition[i] a =self.transformers[transformer_index]( __A , encoder_hidden_states=__A , timestep=__A , cross_attention_kwargs=__A , return_dict=__A , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] a =encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) a =output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=__A )
81
"""simple docstring""" def _A ( ): """simple docstring""" for n in range(1 , 1_00_00_00 ): yield n * (n + 1) // 2 def _A ( lowercase ): """simple docstring""" a =1 a =2 while i * i <= n: a =0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _A ( ): """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(lowercase ) > 5_00 ) if __name__ == "__main__": print(solution())
81
1
"""simple docstring""" import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging lowerCamelCase_ : List[str] = logging.get_logger(__name__) lowerCamelCase_ : Any = R""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax. kwargs (`Dict[str, Any]`, *optional*): Additional stopping criteria specific kwargs. Return: `bool`. `False` indicates we should continue, `True` indicates we should stop. """ class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" @add_start_docstrings(__A ) def __call__( self , __A , __A , **__A ) -> bool: raise NotImplementedError('''StoppingCriteria needs to be subclassed''' ) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , __A , __A = None ) -> Any: a =max_length a =max_position_embeddings @add_start_docstrings(__A ) def __call__( self , __A , __A , **__A ) -> bool: a =input_ids.shape[-1] a =cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( '''This is a friendly reminder - the current text generation call will exceed the model\'s predefined ''' f'''maximum length ({self.max_position_embeddings}). Depending on the model, you may observe ''' '''exceptions, performance degradation, or nothing at all.''' ) return is_done class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , __A , __A ) -> Tuple: warnings.warn( '''The class `MaxNewTokensCriteria` is deprecated. ''' f'''Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` ''' '''with `max_length = start_length + max_new_tokens` instead.''' , __A , ) a =start_length a =max_new_tokens a =start_length + max_new_tokens @add_start_docstrings(__A ) def __call__( self , __A , __A , **__A ) -> bool: return input_ids.shape[-1] >= self.max_length class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , __A , __A = None ) -> int: a =max_time a =time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(__A ) def __call__( self , __A , __A , **__A ) -> bool: return time.time() - self.initial_timestamp > self.max_time class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" @add_start_docstrings(__A ) def __call__( self , __A , __A , **__A ) -> bool: return any(criteria(__A , __A ) for criteria in self ) @property def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: for stopping_criterium in self: if isinstance(__A , __A ): return stopping_criterium.max_length elif isinstance(__A , __A ): return stopping_criterium.max_length return None def _A ( lowercase , lowercase ): """simple docstring""" a =stopping_criteria.max_length a =deepcopy(lowercase ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn('''You set different `max_length` for stopping criteria and `max_length` parameter''' , lowercase ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=lowercase ) ) return new_stopping_criteria
81
"""simple docstring""" from math import factorial def _A ( lowercase = 1_00 ): """simple docstring""" return sum(int(lowercase ) for x in str(factorial(lowercase ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
81
1
"""simple docstring""" # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( """pipelines_utils""", """0.22.0""", """Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.""", standard_warn=False, stacklevel=3, )
81
"""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, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Optional[Any] = """▁""" lowerCamelCase_ : Union[str, Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : Any = { """vocab_file""": { """xlm-roberta-base""": """https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large""": """https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large-finetuned-conll02-dutch""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll02-spanish""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-english""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-german""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model""" ), } } lowerCamelCase_ : Tuple = { """xlm-roberta-base""": 5_1_2, """xlm-roberta-large""": 5_1_2, """xlm-roberta-large-finetuned-conll02-dutch""": 5_1_2, """xlm-roberta-large-finetuned-conll02-spanish""": 5_1_2, """xlm-roberta-large-finetuned-conll03-english""": 5_1_2, """xlm-roberta-large-finetuned-conll03-german""": 5_1_2, } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a =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 a ={'''<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 a =1 a =len(self.sp_model ) + self.fairseq_offset a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: a =self.__dict__.copy() a =None a =self.sp_model.serialized_model_proto() return state def __setstate__( self , __A ) -> List[Any]: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[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] @property def SCREAMING_SNAKE_CASE ( self ) -> List[str]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> int: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =self.sp_model.PieceToId(__A ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: a =''''''.join(__A ).replace(__A , ''' ''' ).strip() return out_string def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , '''wb''' ) as fi: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
1
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=_SCREAMING_SNAKE_CASE ) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = field(default="summarization", metadata={"include_in_asdict_even_if_is_default": True} ) __lowerCAmelCase = Features({"text": Value("string" )} ) __lowerCAmelCase = Features({"summary": Value("string" )} ) __lowerCAmelCase = "text" __lowerCAmelCase = "summary" @property def SCREAMING_SNAKE_CASE ( self ) -> Dict[str, str]: return {self.text_column: "text", self.summary_column: "summary"}
81
"""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, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Tuple = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : str = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } lowerCamelCase_ : Optional[int] = { """moussaKam/mbarthez""": 1_0_2_4, """moussaKam/barthez""": 1_0_2_4, """moussaKam/barthez-orangesum-title""": 1_0_2_4, } lowerCamelCase_ : Tuple = """▁""" class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =vocab_file a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a ={'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} a =len(self.sp_model ) - 1 a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[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] @property def SCREAMING_SNAKE_CASE ( self ) -> Any: return len(self.sp_model ) def SCREAMING_SNAKE_CASE ( self ) -> int: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Dict: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =self.sp_model.PieceToId(__A ) return spm_id if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Tuple: a =[] a ='''''' a =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__A ) + token a =True a =[] else: current_sub_tokens.append(__A ) a =False out_string += self.sp_model.decode(__A ) return out_string.strip() def __getstate__( self ) -> Tuple: a =self.__dict__.copy() a =None return state def __setstate__( self , __A ) -> Tuple: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , '''wb''' ) as fi: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ : Dict = logging.get_logger(__name__) lowerCamelCase_ : List[Any] = { """facebook/nllb-moe-54B""": """https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json""", } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "nllb-moe" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , __A=12_8112 , __A=1024 , __A=12 , __A=4096 , __A=16 , __A=12 , __A=4096 , __A=16 , __A=0.05 , __A=0.05 , __A=True , __A=True , __A="relu" , __A=1024 , __A=0.1 , __A=0.1 , __A=0.0 , __A=0.02 , __A=2 , __A=True , __A=False , __A="float32" , __A=False , __A=128 , __A=64 , __A=4 , __A=4 , __A=0.001 , __A=0.001 , __A="all" , __A=False , __A=False , __A=1.0 , __A=0.2 , __A=1 , __A=0 , __A=2 , __A=False , **__A , ) -> List[Any]: a =vocab_size a =max_position_embeddings a =d_model a =encoder_ffn_dim a =encoder_layers a =encoder_attention_heads a =decoder_ffn_dim a =decoder_layers a =decoder_attention_heads a =dropout a =attention_dropout a =activation_dropout a =activation_function a =init_std a =encoder_layerdrop a =decoder_layerdrop a =use_cache a =encoder_layers a =scale_embedding # scale factor will be sqrt(d_model) if True a =router_z_loss_coef a =router_aux_loss_coef a =decoder_sparse_step a =encoder_sparse_step a =num_experts a =expert_capacity a =router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f'''`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}''' ) a =router_dtype a =router_ignore_padding_tokens a =batch_prioritized_routing a =second_expert_policy a =normalize_router_prob_before_dropping a =moe_eval_capacity_token_fraction a =moe_token_dropout a =output_router_logits super().__init__( pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , is_encoder_decoder=__A , decoder_start_token_id=__A , **__A , )
81
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) lowerCamelCase_ : Tuple = logging.get_logger(__name__) lowerCamelCase_ : str = OrderedDict( [ ("""align""", """EfficientNetImageProcessor"""), ("""beit""", """BeitImageProcessor"""), ("""bit""", """BitImageProcessor"""), ("""blip""", """BlipImageProcessor"""), ("""blip-2""", """BlipImageProcessor"""), ("""bridgetower""", """BridgeTowerImageProcessor"""), ("""chinese_clip""", """ChineseCLIPImageProcessor"""), ("""clip""", """CLIPImageProcessor"""), ("""clipseg""", """ViTImageProcessor"""), ("""conditional_detr""", """ConditionalDetrImageProcessor"""), ("""convnext""", """ConvNextImageProcessor"""), ("""convnextv2""", """ConvNextImageProcessor"""), ("""cvt""", """ConvNextImageProcessor"""), ("""data2vec-vision""", """BeitImageProcessor"""), ("""deformable_detr""", """DeformableDetrImageProcessor"""), ("""deit""", """DeiTImageProcessor"""), ("""deta""", """DetaImageProcessor"""), ("""detr""", """DetrImageProcessor"""), ("""dinat""", """ViTImageProcessor"""), ("""donut-swin""", """DonutImageProcessor"""), ("""dpt""", """DPTImageProcessor"""), ("""efficientformer""", """EfficientFormerImageProcessor"""), ("""efficientnet""", """EfficientNetImageProcessor"""), ("""flava""", """FlavaImageProcessor"""), ("""focalnet""", """BitImageProcessor"""), ("""git""", """CLIPImageProcessor"""), ("""glpn""", """GLPNImageProcessor"""), ("""groupvit""", """CLIPImageProcessor"""), ("""imagegpt""", """ImageGPTImageProcessor"""), ("""instructblip""", """BlipImageProcessor"""), ("""layoutlmv2""", """LayoutLMv2ImageProcessor"""), ("""layoutlmv3""", """LayoutLMv3ImageProcessor"""), ("""levit""", """LevitImageProcessor"""), ("""mask2former""", """Mask2FormerImageProcessor"""), ("""maskformer""", """MaskFormerImageProcessor"""), ("""mgp-str""", """ViTImageProcessor"""), ("""mobilenet_v1""", """MobileNetV1ImageProcessor"""), ("""mobilenet_v2""", """MobileNetV2ImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevitv2""", """MobileViTImageProcessor"""), ("""nat""", """ViTImageProcessor"""), ("""oneformer""", """OneFormerImageProcessor"""), ("""owlvit""", """OwlViTImageProcessor"""), ("""perceiver""", """PerceiverImageProcessor"""), ("""pix2struct""", """Pix2StructImageProcessor"""), ("""poolformer""", """PoolFormerImageProcessor"""), ("""regnet""", """ConvNextImageProcessor"""), ("""resnet""", """ConvNextImageProcessor"""), ("""sam""", """SamImageProcessor"""), ("""segformer""", """SegformerImageProcessor"""), ("""swiftformer""", """ViTImageProcessor"""), ("""swin""", """ViTImageProcessor"""), ("""swin2sr""", """Swin2SRImageProcessor"""), ("""swinv2""", """ViTImageProcessor"""), ("""table-transformer""", """DetrImageProcessor"""), ("""timesformer""", """VideoMAEImageProcessor"""), ("""tvlt""", """TvltImageProcessor"""), ("""upernet""", """SegformerImageProcessor"""), ("""van""", """ConvNextImageProcessor"""), ("""videomae""", """VideoMAEImageProcessor"""), ("""vilt""", """ViltImageProcessor"""), ("""vit""", """ViTImageProcessor"""), ("""vit_hybrid""", """ViTHybridImageProcessor"""), ("""vit_mae""", """ViTImageProcessor"""), ("""vit_msn""", """ViTImageProcessor"""), ("""xclip""", """CLIPImageProcessor"""), ("""yolos""", """YolosImageProcessor"""), ] ) lowerCamelCase_ : Union[str, Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def _A ( lowercase ): """simple docstring""" for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: a =model_type_to_module_name(lowercase ) a =importlib.import_module(f'''.{module_name}''' , '''transformers.models''' ) try: return getattr(lowercase , lowercase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowercase , '''__name__''' , lowercase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. a =importlib.import_module('''transformers''' ) if hasattr(lowercase , lowercase ): return getattr(lowercase , lowercase ) return None def _A ( lowercase , lowercase = None , lowercase = False , lowercase = False , lowercase = None , lowercase = None , lowercase = None , lowercase = False , **lowercase , ): """simple docstring""" a =get_file_from_repo( lowercase , lowercase , cache_dir=lowercase , force_download=lowercase , resume_download=lowercase , proxies=lowercase , use_auth_token=lowercase , revision=lowercase , local_files_only=lowercase , ) if resolved_config_file is None: logger.info( '''Could not locate the image processor configuration file, will try to use the model config instead.''' ) return {} with open(lowercase , encoding='''utf-8''' ) as reader: return json.load(lowercase ) class __A : """simple docstring""" def __init__( self ) -> Optional[Any]: raise EnvironmentError( '''AutoImageProcessor is designed to be instantiated ''' '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__A ) def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> Dict: a =kwargs.pop('''config''' , __A ) a =kwargs.pop('''trust_remote_code''' , __A ) a =True a , a =ImageProcessingMixin.get_image_processor_dict(__A , **__A ) a =config_dict.get('''image_processor_type''' , __A ) a =None if "AutoImageProcessor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoImageProcessor'''] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: a =config_dict.pop('''feature_extractor_type''' , __A ) if feature_extractor_class is not None: logger.warning( '''Could not find image processor class in the image processor config or the model config. Loading''' ''' based on pattern matching with the model\'s feature extractor configuration.''' ) a =feature_extractor_class.replace('''FeatureExtractor''' , '''ImageProcessor''' ) if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoFeatureExtractor'''] a =feature_extractor_auto_map.replace('''FeatureExtractor''' , '''ImageProcessor''' ) logger.warning( '''Could not find image processor auto map in the image processor config or the model config.''' ''' Loading based on pattern matching with the model\'s feature extractor configuration.''' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(__A , __A ): a =AutoConfig.from_pretrained(__A , **__A ) # It could be in `config.image_processor_type`` a =getattr(__A , '''image_processor_type''' , __A ) if hasattr(__A , '''auto_map''' ) and "AutoImageProcessor" in config.auto_map: a =config.auto_map['''AutoImageProcessor'''] if image_processor_class is not None: a =image_processor_class_from_name(__A ) a =image_processor_auto_map is not None a =image_processor_class is not None or type(__A ) in IMAGE_PROCESSOR_MAPPING a =resolve_trust_remote_code( __A , __A , __A , __A ) if has_remote_code and trust_remote_code: a =get_class_from_dynamic_module( __A , __A , **__A ) a =kwargs.pop('''code_revision''' , __A ) if os.path.isdir(__A ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(__A , **__A ) elif image_processor_class is not None: return image_processor_class.from_dict(__A , **__A ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(__A ) in IMAGE_PROCESSOR_MAPPING: a =IMAGE_PROCESSOR_MAPPING[type(__A )] return image_processor_class.from_dict(__A , **__A ) raise ValueError( f'''Unrecognized image processor in {pretrained_model_name_or_path}. Should have a ''' f'''`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def SCREAMING_SNAKE_CASE ( __A , __A ) -> Any: IMAGE_PROCESSOR_MAPPING.register(__A , __A )
81
1
"""simple docstring""" import argparse import os import re import packaging.version lowerCamelCase_ : Tuple = """examples/""" lowerCamelCase_ : str = { """examples""": (re.compile(R"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(R"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(R"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), R"""\1version=\"VERSION\","""), """doc""": (re.compile(R"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } lowerCamelCase_ : Dict = { """init""": """src/transformers/__init__.py""", """setup""": """setup.py""", } lowerCamelCase_ : Any = """README.md""" def _A ( lowercase , lowercase , lowercase ): """simple docstring""" with open(lowercase , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: a =f.read() a , a =REPLACE_PATTERNS[pattern] a =replace.replace('''VERSION''' , lowercase ) a =re_pattern.sub(lowercase , lowercase ) with open(lowercase , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.write(lowercase ) def _A ( lowercase ): """simple docstring""" for folder, directories, fnames in os.walk(lowercase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('''research_projects''' ) if "legacy" in directories: directories.remove('''legacy''' ) for fname in fnames: if fname.endswith('''.py''' ): update_version_in_file(os.path.join(lowercase , lowercase ) , lowercase , pattern='''examples''' ) def _A ( lowercase , lowercase=False ): """simple docstring""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(lowercase , lowercase , lowercase ) if not patch: update_version_in_examples(lowercase ) def _A ( ): """simple docstring""" a ='''🤗 Transformers currently provides the following architectures''' a ='''1. Want to contribute a new model?''' with open(lowercase , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: a =f.readlines() # Find the start of the list. a =0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 a =start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('''1.''' ): a =lines[index].replace( '''https://huggingface.co/docs/transformers/main/model_doc''' , '''https://huggingface.co/docs/transformers/model_doc''' , ) index += 1 with open(lowercase , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lowercase ) def _A ( ): """simple docstring""" with open(REPLACE_FILES['''init'''] , '''r''' ) as f: a =f.read() a =REPLACE_PATTERNS['''init'''][0].search(lowercase ).groups()[0] return packaging.version.parse(lowercase ) def _A ( lowercase=False ): """simple docstring""" a =get_version() if patch and default_version.is_devrelease: raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!''' ) if default_version.is_devrelease: a =default_version.base_version elif patch: a =f'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}''' else: a =f'''{default_version.major}.{default_version.minor + 1}.0''' # Now let's ask nicely if that's the right one. a =input(f'''Which version are you releasing? [{default_version}]''' ) if len(lowercase ) == 0: a =default_version print(f'''Updating version to {version}.''' ) global_version_update(lowercase , patch=lowercase ) if not patch: print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() def _A ( ): """simple docstring""" a =get_version() a =f'''{current_version.major}.{current_version.minor + 1}.0.dev0''' a =current_version.base_version # Check with the user we got that right. a =input(f'''Which version are we developing now? [{dev_version}]''' ) if len(lowercase ) == 0: a =dev_version print(f'''Updating version to {version}.''' ) global_version_update(lowercase ) print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() if __name__ == "__main__": lowerCamelCase_ : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") lowerCamelCase_ : int = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
81
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = DistilBertTokenizer __lowerCAmelCase = DistilBertTokenizerFast __lowerCAmelCase = True @slow def SCREAMING_SNAKE_CASE ( self ) -> int: a =DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
81
1
"""simple docstring""" def _A ( lowercase = 1_00_00_00 ): """simple docstring""" a =set(range(3 , lowercase , 2 ) ) primes.add(2 ) for p in range(3 , lowercase , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , lowercase , lowercase ) ) ) a =[float(lowercase ) for n in range(limit + 1 )] for p in primes: for n in range(lowercase , limit + 1 , lowercase ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F'{solution() = }')
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCamelCase_ : List[str] = { """configuration_speech_to_text""": ["""SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Speech2TextConfig"""], """processing_speech_to_text""": ["""Speech2TextProcessor"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""Speech2TextTokenizer"""] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[Any] = ["""Speech2TextFeatureExtractor"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFSpeech2TextForConditionalGeneration""", """TFSpeech2TextModel""", """TFSpeech2TextPreTrainedModel""", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = [ """SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Speech2TextForConditionalGeneration""", """Speech2TextModel""", """Speech2TextPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ : int = logging.get_logger(__name__) lowerCamelCase_ : int = { """uw-madison/mra-base-512-4""": """https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json""", } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "mra" def __init__( self , __A=5_0265 , __A=768 , __A=12 , __A=12 , __A=3072 , __A="gelu" , __A=0.1 , __A=0.1 , __A=512 , __A=1 , __A=0.02 , __A=1E-5 , __A="absolute" , __A=4 , __A="full" , __A=0 , __A=0 , __A=1 , __A=0 , __A=2 , **__A , ) -> List[str]: super().__init__(pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , **__A ) a =vocab_size a =max_position_embeddings a =hidden_size a =num_hidden_layers a =num_attention_heads a =intermediate_size a =hidden_act a =hidden_dropout_prob a =attention_probs_dropout_prob a =initializer_range a =type_vocab_size a =layer_norm_eps a =position_embedding_type a =block_per_row a =approx_mode a =initial_prior_first_n_blocks a =initial_prior_diagonal_n_blocks
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : Union[str, Any] = { """configuration_table_transformer""": [ """TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TableTransformerConfig""", """TableTransformerOnnxConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TableTransformerForObjectDetection""", """TableTransformerModel""", """TableTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging lowerCamelCase_ : str = logging.get_logger(__name__) lowerCamelCase_ : Any = { """CarlCochet/trajectory-transformer-halfcheetah-medium-v2""": ( """https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json""" ), # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "trajectory_transformer" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = { "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , __A=100 , __A=5 , __A=1 , __A=1 , __A=249 , __A=6 , __A=17 , __A=25 , __A=4 , __A=4 , __A=128 , __A=0.1 , __A=0.1 , __A=0.1 , __A=0.0_006 , __A=512 , __A=0.02 , __A=1E-1_2 , __A=1 , __A=True , __A=1 , __A=5_0256 , __A=5_0256 , **__A , ) -> List[Any]: a =vocab_size a =action_weight a =reward_weight a =value_weight a =max_position_embeddings a =block_size a =action_dim a =observation_dim a =transition_dim a =learning_rate a =n_layer a =n_head a =n_embd a =embd_pdrop a =attn_pdrop a =resid_pdrop a =initializer_range a =layer_norm_eps a =kaiming_initializer_range a =use_cache super().__init__(pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , **__A )
81
"""simple docstring""" from __future__ import annotations import math def _A ( lowercase ): """simple docstring""" if num <= 0: a =f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(lowercase ) a =[True] * (num + 1) a =[] a =2 a =int(math.sqrt(lowercase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(lowercase ) # Set multiples of start be False for i in range(start * start , num + 1 , lowercase ): if sieve[i] is True: a =False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(lowercase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
81
1
"""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 ( lowercase , lowercase="shi-labs/oneformer_demo" ): """simple docstring""" with open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) as f: a =json.load(lowercase ) a ={} a =[] a =[] for key, info in class_info.items(): a =info['''name'''] class_names.append(info['''name'''] ) if info["isthing"]: thing_ids.append(int(lowercase ) ) a =thing_ids a =class_names return metadata class __A ( unittest.TestCase ): """simple docstring""" def __init__( self , __A , __A=7 , __A=3 , __A=30 , __A=400 , __A=None , __A=True , __A=True , __A=[0.5, 0.5, 0.5] , __A=[0.5, 0.5, 0.5] , __A=10 , __A=False , __A=255 , __A="shi-labs/oneformer_demo" , __A="ade20k_panoptic.json" , __A=10 , ) -> List[Any]: a =parent a =batch_size a =num_channels a =min_resolution a =max_resolution a =do_resize a ={'''shortest_edge''': 32, '''longest_edge''': 1333} if size is None else size a =do_normalize a =image_mean a =image_std a =class_info_file a =prepare_metadata(__A , __A ) a =num_text a =repo_path # for the post_process_functions a =2 a =10 a =10 a =3 a =4 a =num_labels a =do_reduce_labels a =ignore_index def SCREAMING_SNAKE_CASE ( self ) -> Tuple: 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 SCREAMING_SNAKE_CASE ( self , __A , __A=False ) -> List[Any]: if not batched: a =image_inputs[0] if isinstance(__A , Image.Image ): a , a =image.size else: a , a =image.shape[1], image.shape[2] if w < h: a =int(self.size['''shortest_edge'''] * h / w ) a =self.size['''shortest_edge'''] elif w > h: a =self.size['''shortest_edge'''] a =int(self.size['''shortest_edge'''] * w / h ) else: a =self.size['''shortest_edge'''] a =self.size['''shortest_edge'''] else: a =[] for image in image_inputs: a , a =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) a =max(__A , key=lambda __A : item[0] )[0] a =max(__A , key=lambda __A : item[1] )[1] return expected_height, expected_width def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: 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 __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None # only for test_image_processing_common.test_image_proc_to_json_string __lowerCAmelCase = image_processing_class def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =OneFormerImageProcessorTester(self ) @property def SCREAMING_SNAKE_CASE ( self ) -> Tuple: return self.image_processing_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__A , '''image_mean''' ) ) self.assertTrue(hasattr(__A , '''image_std''' ) ) self.assertTrue(hasattr(__A , '''do_normalize''' ) ) self.assertTrue(hasattr(__A , '''do_resize''' ) ) self.assertTrue(hasattr(__A , '''size''' ) ) self.assertTrue(hasattr(__A , '''ignore_index''' ) ) self.assertTrue(hasattr(__A , '''class_info_file''' ) ) self.assertTrue(hasattr(__A , '''num_text''' ) ) self.assertTrue(hasattr(__A , '''repo_path''' ) ) self.assertTrue(hasattr(__A , '''metadata''' ) ) self.assertTrue(hasattr(__A , '''do_reduce_labels''' ) ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: pass def SCREAMING_SNAKE_CASE ( self ) -> Dict: # Initialize image_processor a =self.image_processing_class(**self.image_processor_dict ) # create random PIL images a =prepare_image_inputs(self.image_processing_tester , equal_resolution=__A ) for image in image_inputs: self.assertIsInstance(__A , Image.Image ) # Test not batched input a =image_processor(image_inputs[0] , ['''semantic'''] , return_tensors='''pt''' ).pixel_values a , a =self.image_processing_tester.get_expected_values(__A ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched a , a =self.image_processing_tester.get_expected_values(__A , batched=__A ) a =image_processor( __A , ['''semantic'''] * len(__A ) , 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 SCREAMING_SNAKE_CASE ( self ) -> Tuple: # Initialize image_processor a =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a =prepare_image_inputs(self.image_processing_tester , equal_resolution=__A , numpify=__A ) for image in image_inputs: self.assertIsInstance(__A , np.ndarray ) # Test not batched input a =image_processor(image_inputs[0] , ['''semantic'''] , return_tensors='''pt''' ).pixel_values a , a =self.image_processing_tester.get_expected_values(__A ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched a , a =self.image_processing_tester.get_expected_values(__A , batched=__A ) a =image_processor( __A , ['''semantic'''] * len(__A ) , 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 SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: # Initialize image_processor a =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a =prepare_image_inputs(self.image_processing_tester , equal_resolution=__A , torchify=__A ) for image in image_inputs: self.assertIsInstance(__A , torch.Tensor ) # Test not batched input a =image_processor(image_inputs[0] , ['''semantic'''] , return_tensors='''pt''' ).pixel_values a , a =self.image_processing_tester.get_expected_values(__A ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched a , a =self.image_processing_tester.get_expected_values(__A , batched=__A ) a =image_processor( __A , ['''semantic'''] * len(__A ) , 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 SCREAMING_SNAKE_CASE ( self , __A=False , __A=False , __A="np" ) -> Union[str, Any]: a =self.image_processing_class(**self.image_processor_dict ) # prepare image and target a =self.image_processing_tester.num_labels a =None a =None a =prepare_image_inputs(self.image_processing_tester , equal_resolution=__A ) if with_segmentation_maps: a =num_labels if is_instance_map: a =list(range(__A ) ) * 2 a =dict(enumerate(__A ) ) a =[ np.random.randint(0 , high * 2 , (img.size[1], img.size[0]) ).astype(np.uinta ) for img in image_inputs ] if segmentation_type == "pil": a =[Image.fromarray(__A ) for annotation in annotations] a =image_processor( __A , ['''semantic'''] * len(__A ) , __A , return_tensors='''pt''' , instance_id_to_semantic_id=__A , pad_and_return_pixel_mask=__A , ) return inputs def SCREAMING_SNAKE_CASE ( self ) -> int: pass def SCREAMING_SNAKE_CASE ( self ) -> Any: def common(__A=False , __A=None ): a =self.comm_get_image_processor_inputs( with_segmentation_maps=__A , is_instance_map=__A , segmentation_type=__A ) a =inputs['''mask_labels'''] a =inputs['''class_labels'''] a =inputs['''pixel_values'''] a =inputs['''text_inputs'''] # check the batch_size for mask_label, class_label, text_input in zip(__A , __A , __A ): 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(__A ) , self.image_processing_tester.num_text ) common() common(is_instance_map=__A ) common(is_instance_map=__A , segmentation_type='''pil''' ) common(is_instance_map=__A , segmentation_type='''pil''' ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =np.zeros((20, 50) ) a =1 a =1 a =1 a =binary_mask_to_rle(__A ) self.assertEqual(len(__A ) , 4 ) self.assertEqual(rle[0] , 21 ) self.assertEqual(rle[1] , 45 ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =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''' , ) a =self.image_processing_tester.get_fake_oneformer_outputs() a =fature_extractor.post_process_semantic_segmentation(__A ) self.assertEqual(len(__A ) , self.image_processing_tester.batch_size ) self.assertEqual( segmentation[0].shape , ( self.image_processing_tester.height, self.image_processing_tester.width, ) , ) a =[(1, 4) for i in range(self.image_processing_tester.batch_size )] a =fature_extractor.post_process_semantic_segmentation(__A , target_sizes=__A ) self.assertEqual(segmentation[0].shape , target_sizes[0] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =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''' , ) a =self.image_processing_tester.get_fake_oneformer_outputs() a =image_processor.post_process_instance_segmentation(__A , threshold=0 ) self.assertTrue(len(__A ) == 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'''] ) , __A ) self.assertEqual( el['''segmentation'''].shape , (self.image_processing_tester.height, self.image_processing_tester.width) ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =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''' , ) a =self.image_processing_tester.get_fake_oneformer_outputs() a =image_processor.post_process_panoptic_segmentation(__A , threshold=0 ) self.assertTrue(len(__A ) == 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'''] ) , __A ) self.assertEqual( el['''segmentation'''].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
81
"""simple docstring""" 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 __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = BertTokenizer __lowerCAmelCase = BertTokenizerFast __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = filter_non_english def SCREAMING_SNAKE_CASE ( self ) -> List[str]: super().setUp() a =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a =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 SCREAMING_SNAKE_CASE ( self , __A ) -> Union[str, Any]: a ='''UNwant\u00E9d,running''' a ='''unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.tokenizer_class(self.vocab_file ) a =tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__A , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [9, 6, 7, 12, 10, 11] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: if not self.test_rust_tokenizer: return a =self.get_tokenizer() a =self.get_rust_tokenizer() a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) # With lower casing a =self.get_tokenizer(do_lower_case=__A ) a =self.get_rust_tokenizer(do_lower_case=__A ) a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Any: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =BasicTokenizer(do_lower_case=__A , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =BasicTokenizer() a ='''a\n\'ll !!to?\'d of, can\'t.''' a =['''a''', '''\'''', '''ll''', '''!''', '''!''', '''to''', '''?''', '''\'''', '''d''', '''of''', ''',''', '''can''', '''\'''', '''t''', '''.'''] self.assertListEqual(tokenizer.tokenize(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a ={} for i, token in enumerate(__A ): a =i a =WordpieceTokenizer(vocab=__A , 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 SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE ( self ) -> Any: 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 SCREAMING_SNAKE_CASE ( self ) -> str: 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 SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.get_tokenizer() a =self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.tokenizer_class.from_pretrained('''bert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def SCREAMING_SNAKE_CASE ( self ) -> Any: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' a =tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) a =tokenizer_r.do_lower_case if hasattr(__A , '''do_lower_case''' ) else False a =( [ ((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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =['''的''', '''人''', '''有'''] a =''''''.join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =True a =self.tokenizer_class.from_pretrained(__A , **__A ) a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) a =False a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =self.tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". a =[ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A )
81
1
"""simple docstring""" import argparse import math import traceback import dateutil.parser as date_parser import requests def _A ( lowercase ): """simple docstring""" a ={} a =job['''started_at'''] a =job['''completed_at'''] a =date_parser.parse(lowercase ) a =date_parser.parse(lowercase ) a =round((end_datetime - start_datetime).total_seconds() / 60.0 ) a =start a =end a =duration_in_min return job_info def _A ( lowercase , lowercase=None ): """simple docstring""" a =None if token is not None: a ={'''Accept''': '''application/vnd.github+json''', '''Authorization''': f'''Bearer {token}'''} a =f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' a =requests.get(lowercase , headers=lowercase ).json() a ={} try: job_time.update({job['''name''']: extract_time_from_single_job(lowercase ) for job in result['''jobs''']} ) a =math.ceil((result['''total_count'''] - 1_00) / 1_00 ) for i in range(lowercase ): a =requests.get(url + f'''&page={i + 2}''' , headers=lowercase ).json() job_time.update({job['''name''']: extract_time_from_single_job(lowercase ) for job in result['''jobs''']} ) return job_time except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} if __name__ == "__main__": lowerCamelCase_ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument("""--workflow_run_id""", type=str, required=True, help="""A GitHub Actions workflow run id.""") lowerCamelCase_ : Any = parser.parse_args() lowerCamelCase_ : Dict = get_job_time(args.workflow_run_id) lowerCamelCase_ : Optional[int] = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) for k, v in job_time.items(): print(F'{k}: {v["duration"]}')
81
"""simple docstring""" import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ : Union[str, Any] = logging.get_logger(__name__) lowerCamelCase_ : Any = { """microsoft/conditional-detr-resnet-50""": ( """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json""" ), } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "conditional_detr" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , __A=True , __A=None , __A=3 , __A=300 , __A=6 , __A=2048 , __A=8 , __A=6 , __A=2048 , __A=8 , __A=0.0 , __A=0.0 , __A=True , __A="relu" , __A=256 , __A=0.1 , __A=0.0 , __A=0.0 , __A=0.02 , __A=1.0 , __A=False , __A="sine" , __A="resnet50" , __A=True , __A=False , __A=2 , __A=5 , __A=2 , __A=1 , __A=1 , __A=2 , __A=5 , __A=2 , __A=0.25 , **__A , ) -> List[Any]: if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) a =CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(__A , __A ): a =backbone_config.get('''model_type''' ) a =CONFIG_MAPPING[backbone_model_type] a =config_class.from_dict(__A ) a =use_timm_backbone a =backbone_config a =num_channels a =num_queries a =d_model a =encoder_ffn_dim a =encoder_layers a =encoder_attention_heads a =decoder_ffn_dim a =decoder_layers a =decoder_attention_heads a =dropout a =attention_dropout a =activation_dropout a =activation_function a =init_std a =init_xavier_std a =encoder_layerdrop a =decoder_layerdrop a =encoder_layers a =auxiliary_loss a =position_embedding_type a =backbone a =use_pretrained_backbone a =dilation # Hungarian matcher a =class_cost a =bbox_cost a =giou_cost # Loss coefficients a =mask_loss_coefficient a =dice_loss_coefficient a =cls_loss_coefficient a =bbox_loss_coefficient a =giou_loss_coefficient a =focal_alpha super().__init__(is_encoder_decoder=__A , **__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.d_model def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: a =self.backbone_config.to_dict() a =self.__class__.model_type return output class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def SCREAMING_SNAKE_CASE ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE ( self ) -> int: return 12
81
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "naver-clova-ix/donut-base-finetuned-docvqa" __lowerCAmelCase = ( "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." ) __lowerCAmelCase = "document_qa" __lowerCAmelCase = AutoProcessor __lowerCAmelCase = VisionEncoderDecoderModel __lowerCAmelCase = ["image", "text"] __lowerCAmelCase = ["text"] def __init__( self , *__A , **__A ) -> Tuple: if not is_vision_available(): raise ValueError('''Pillow must be installed to use the DocumentQuestionAnsweringTool.''' ) super().__init__(*__A , **__A ) def SCREAMING_SNAKE_CASE ( self , __A , __A ) -> List[str]: a ='''<s_docvqa><s_question>{user_input}</s_question><s_answer>''' a =task_prompt.replace('''{user_input}''' , __A ) a =self.pre_processor.tokenizer( __A , add_special_tokens=__A , return_tensors='''pt''' ).input_ids a =self.pre_processor(__A , return_tensors='''pt''' ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def SCREAMING_SNAKE_CASE ( self , __A ) -> int: return self.model.generate( inputs['''pixel_values'''].to(self.device ) , decoder_input_ids=inputs['''decoder_input_ids'''].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=__A , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=__A , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=__A , ).sequences def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: a =self.pre_processor.batch_decode(__A )[0] a =sequence.replace(self.pre_processor.tokenizer.eos_token , '''''' ) a =sequence.replace(self.pre_processor.tokenizer.pad_token , '''''' ) a =re.sub(r'''<.*?>''' , '''''' , __A , count=1 ).strip() # remove first task start token a =self.pre_processor.tokenajson(__A ) return sequence["answer"]
81
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" while second != 0: a =first & second first ^= second a =c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase_ : Dict = int(input("""Enter the first number: """).strip()) lowerCamelCase_ : List[Any] = int(input("""Enter the second number: """).strip()) print(F'{add(first, second) = }')
81
1
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_barthez import BarthezTokenizer else: lowerCamelCase_ : Tuple = None lowerCamelCase_ : Optional[Any] = logging.get_logger(__name__) lowerCamelCase_ : Optional[Any] = {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""} lowerCamelCase_ : Optional[Any] = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, """tokenizer_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json""" ), }, } lowerCamelCase_ : Optional[int] = { """moussaKam/mbarthez""": 1_0_2_4, """moussaKam/barthez""": 1_0_2_4, """moussaKam/barthez-orangesum-title""": 1_0_2_4, } lowerCamelCase_ : int = """▁""" class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] __lowerCAmelCase = BarthezTokenizer def __init__( self , __A=None , __A=None , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , **__A , ) -> Union[str, Any]: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token super().__init__( __A , tokenizer_file=__A , bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , **__A , ) a =vocab_file a =False if not self.vocab_file else True def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[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 SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ): copyfile(self.vocab_file , __A ) return (out_vocab_file,)
81
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" a =ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' '''helper utility that will spawn up ''' '''multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=lowercase , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=lowercase , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=lowercase ) return parser.parse_args() def _A ( ): """simple docstring""" a =parse_args() # Import training_script as a module. a =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) a =script_fpath.stem a =importlib.import_module(lowercase ) # Patch sys.argv a =[args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
81
1
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = None __lowerCAmelCase = None __lowerCAmelCase = None __lowerCAmelCase = None class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , __A=1 , __A=0 , __A=2 , __A=512 , __A="cls" , __A=False , __A=True , **__A , ) -> Union[str, Any]: super().__init__(pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , **__A ) a =project_dim a =pooler_fn a =learn_encoder a =use_attention_mask class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = [r"pooler", r"logit_scale"] __lowerCAmelCase = [r"position_ids", r"predictions.decoder.bias"] __lowerCAmelCase = "roberta" __lowerCAmelCase = RobertaSeriesConfig def __init__( self , __A ) -> Dict: super().__init__(__A ) a =XLMRobertaModel(__A ) a =nn.Linear(config.hidden_size , config.project_dim ) a =getattr(__A , '''has_pre_transformation''' , __A ) if self.has_pre_transformation: a =nn.Linear(config.hidden_size , config.project_dim ) a =nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def SCREAMING_SNAKE_CASE ( self , __A = None , __A = None , __A = None , __A = None , __A = None , __A = None , __A = None , __A = None , __A = None , __A = None , __A = None , ) -> Any: a =return_dict if return_dict is not None else self.config.use_return_dict a =self.base_model( input_ids=__A , attention_mask=__A , token_type_ids=__A , position_ids=__A , head_mask=__A , inputs_embeds=__A , encoder_hidden_states=__A , encoder_attention_mask=__A , output_attentions=__A , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=__A , ) if self.has_pre_transformation: a =outputs['''hidden_states'''][-2] a =self.pre_LN(__A ) a =self.transformation_pre(__A ) return TransformationModelOutput( projection_state=__A , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: a =self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=__A , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
81
"""simple docstring""" import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor lowerCamelCase_ : str = logging.get_logger(__name__) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , *__A , **__A ) -> None: warnings.warn( '''The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use CLIPImageProcessor instead.''' , __A , ) super().__init__(*__A , **__A )
81
1
"""simple docstring""" import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() lowerCamelCase_ : int = { """bart""": ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), """bert""": ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """bert-large-uncased-whole-word-masking-finetuned-squad""": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """bert-large-cased-whole-word-masking-finetuned-squad""": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """bert-base-cased-finetuned-mrpc""": ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """dpr""": ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), """gpt2""": ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """xlnet""": ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """xlm""": ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """xlm-roberta""": ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """transfo-xl""": ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """openai-gpt""": ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """roberta""": ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """layoutlm""": ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), """roberta-large-mnli""": ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """camembert""": ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """flaubert""": ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """distilbert""": ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """distilbert-base-distilled-squad""": ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """lxmert""": ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """lxmert-visual-feature-encoder""": ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """ctrl""": ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """albert""": ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """t5""": ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """electra""": ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """wav2vec2""": ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def _A ( lowercase , lowercase , lowercase , lowercase , lowercase=False , lowercase=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(f'''Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.''' ) a , a , a , a =MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: a =cached_file(lowercase , lowercase , force_download=not use_cached_models ) a =config_class.from_json_file(lowercase ) a =True a =True print(f'''Building TensorFlow model from configuration: {config}''' ) a =model_class(lowercase ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): a =cached_file( lowercase , lowercase , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: a =load_pytorch_checkpoint_in_tfa_model(lowercase , lowercase ) if compare_with_pt_model: a =tf_model(tf_model.dummy_inputs , training=lowercase ) # build the network a =torch.load(lowercase , map_location='''cpu''' ) a =pt_model_class.from_pretrained( pretrained_model_name_or_path=lowercase , config=lowercase , state_dict=lowercase ) with torch.no_grad(): a =pt_model(**pt_model.dummy_inputs ) a =pto[0].numpy() a =tfo[0].numpy() a =np.amax(np.abs(np_pt - np_tf ) ) print(f'''Max absolute difference between models outputs {diff}''' ) assert diff <= 2E-2, f'''Error, model absolute difference is >2e-2: {diff}''' # Save pytorch-model print(f'''Save TensorFlow model to {tf_dump_path}''' ) tf_model.save_weights(lowercase , save_format='''h5''' ) def _A ( lowercase , lowercase , lowercase=None , lowercase=None , lowercase=False , lowercase=False , lowercase=False , lowercase=False , ): """simple docstring""" if args_model_type is None: a =list(MODEL_CLASSES.keys() ) else: a =[args_model_type] for j, model_type in enumerate(lowercase , start=1 ): print('''=''' * 1_00 ) print(f''' Converting model type {j}/{len(lowercase )}: {model_type}''' ) print('''=''' * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(f'''Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.''' ) a , a , a , a , a =MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: a =list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: a =model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(lowercase , lowercase ) , start=1 ): print('''-''' * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(f''' Skipping finetuned checkpoint {model_shortcut_name}''' ) continue a =model_shortcut_name elif only_convert_finetuned_models: print(f''' Skipping not finetuned checkpoint {model_shortcut_name}''' ) continue print( f''' Converting checkpoint {i}/{len(lowercase )}: {model_shortcut_name} - model_type {model_type}''' ) print('''-''' * 1_00 ) if config_shortcut_name in aws_config_map: a =cached_file(lowercase , lowercase , force_download=not use_cached_models ) else: a =config_shortcut_name if model_shortcut_name in aws_model_maps: a =cached_file(lowercase , lowercase , force_download=not use_cached_models ) else: a =model_shortcut_name if os.path.isfile(lowercase ): a ='''converted_model''' convert_pt_checkpoint_to_tf( model_type=lowercase , pytorch_checkpoint_path=lowercase , config_file=lowercase , tf_dump_path=os.path.join(lowercase , model_shortcut_name + '''-tf_model.h5''' ) , compare_with_pt_model=lowercase , ) if remove_cached_files: os.remove(lowercase ) os.remove(lowercase ) if __name__ == "__main__": lowerCamelCase_ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_dump_path""", default=None, type=str, required=True, help="""Path to the output Tensorflow dump file.""" ) parser.add_argument( """--model_type""", default=None, type=str, help=( F'Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and ' """convert all the models from AWS.""" ), ) parser.add_argument( """--pytorch_checkpoint_path""", default=None, type=str, help=( """Path to the PyTorch checkpoint path or shortcut name to download from AWS. """ """If not given, will download and convert all the checkpoints from AWS.""" ), ) parser.add_argument( """--config_file""", default=None, type=str, help=( """The config json file corresponding to the pre-trained model. \n""" """This specifies the model architecture. If not given and """ """--pytorch_checkpoint_path is not given or is a shortcut name """ """use the configuration associated to the shortcut name on the AWS""" ), ) parser.add_argument( """--compare_with_pt_model""", action="""store_true""", help="""Compare Tensorflow and PyTorch model predictions.""" ) parser.add_argument( """--use_cached_models""", action="""store_true""", help="""Use cached models if possible instead of updating to latest checkpoint versions.""", ) parser.add_argument( """--remove_cached_files""", action="""store_true""", help="""Remove pytorch models after conversion (save memory when converting in batches).""", ) parser.add_argument("""--only_convert_finetuned_models""", action="""store_true""", help="""Only convert finetuned models.""") lowerCamelCase_ : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
81
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" return number | (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number & ~(1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number ^ (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return ((number >> position) & 1) == 1 def _A ( lowercase , lowercase ): """simple docstring""" return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
81
1
"""simple docstring""" import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class __A : """simple docstring""" @staticmethod def SCREAMING_SNAKE_CASE ( *__A , **__A ) -> Tuple: pass def _A ( lowercase ): """simple docstring""" a =hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class __A ( unittest.TestCase ): """simple docstring""" __lowerCAmelCase = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def SCREAMING_SNAKE_CASE ( self , __A , __A , __A ) -> Union[str, Any]: a =DepthEstimationPipeline(model=__A , image_processor=__A ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def SCREAMING_SNAKE_CASE ( self , __A , __A ) -> Union[str, Any]: a =depth_estimator('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) self.assertEqual({'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )} , __A ) import datasets a =datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''' , '''image''' , split='''test''' ) a =depth_estimator( [ Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ), '''http://images.cocodataset.org/val2017/000000039769.jpg''', # RGBA dataset[0]['''file'''], # LA dataset[1]['''file'''], # L dataset[2]['''file'''], ] ) self.assertEqual( [ {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, ] , __A , ) @require_tf @unittest.skip('''Depth estimation is not implemented in TF''' ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: pass @slow @require_torch def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a ='''Intel/dpt-large''' a =pipeline('''depth-estimation''' , model=__A ) a =depth_estimator('''http://images.cocodataset.org/val2017/000000039769.jpg''' ) a =hashimage(outputs['''depth'''] ) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs['''predicted_depth'''].max().item() ) , 29.304 ) self.assertEqual(nested_simplify(outputs['''predicted_depth'''].min().item() ) , 2.662 ) @require_torch def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: # This is highly irregular to have no small tests. self.skipTest('''There is not hf-internal-testing tiny model for either GLPN nor DPT''' )
81
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _A ( lowercase ): """simple docstring""" a =SwinvaConfig() a =swinva_name.split('''_''' ) a =name_split[1] if "to" in name_split[3]: a =int(name_split[3][-3:] ) else: a =int(name_split[3] ) if "to" in name_split[2]: a =int(name_split[2][-2:] ) else: a =int(name_split[2][6:] ) if model_size == "tiny": a =96 a =(2, 2, 6, 2) a =(3, 6, 12, 24) elif model_size == "small": a =96 a =(2, 2, 18, 2) a =(3, 6, 12, 24) elif model_size == "base": a =1_28 a =(2, 2, 18, 2) a =(4, 8, 16, 32) else: a =1_92 a =(2, 2, 18, 2) a =(6, 12, 24, 48) if "to" in swinva_name: a =(12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): a =2_18_41 a ='''huggingface/label-files''' a ='''imagenet-22k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} else: a =10_00 a ='''huggingface/label-files''' a ='''imagenet-1k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} a =img_size a =num_classes a =embed_dim a =depths a =num_heads a =window_size return config def _A ( lowercase ): """simple docstring""" if "patch_embed.proj" in name: a =name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: a =name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: a ='''encoder.''' + name if "attn.proj" in name: a =name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: a =name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: a =name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: a =name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: a =name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: a =name.replace('''mlp.fc2''' , '''output.dense''' ) if "q_bias" in name: a =name.replace('''q_bias''' , '''query.bias''' ) if "k_bias" in name: a =name.replace('''k_bias''' , '''key.bias''' ) if "v_bias" in name: a =name.replace('''v_bias''' , '''value.bias''' ) if "cpb_mlp" in name: a =name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' ) if name == "norm.weight": a ='''layernorm.weight''' if name == "norm.bias": a ='''layernorm.bias''' if "head" in name: a =name.replace('''head''' , '''classifier''' ) else: a ='''swinv2.''' + name return name def _A ( lowercase , lowercase ): """simple docstring""" for key in orig_state_dict.copy().keys(): a =orig_state_dict.pop(lowercase ) if "mask" in key: continue elif "qkv" in key: a =key.split('''.''' ) a =int(key_split[1] ) a =int(key_split[3] ) a =model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a =val[:dim, :] a =val[dim : dim * 2, :] a =val[-dim:, :] else: a =val[:dim] a =val[ dim : dim * 2 ] a =val[-dim:] else: a =val return orig_state_dict def _A ( lowercase , lowercase ): """simple docstring""" a =timm.create_model(lowercase , pretrained=lowercase ) timm_model.eval() a =get_swinva_config(lowercase ) a =SwinvaForImageClassification(lowercase ) model.eval() a =convert_state_dict(timm_model.state_dict() , lowercase ) model.load_state_dict(lowercase ) a ='''http://images.cocodataset.org/val2017/000000039769.jpg''' a =AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swinva_name.replace('''_''' , '''-''' ) ) ) a =Image.open(requests.get(lowercase , stream=lowercase ).raw ) a =image_processor(images=lowercase , return_tensors='''pt''' ) a =timm_model(inputs['''pixel_values'''] ) a =model(**lowercase ).logits assert torch.allclose(lowercase , lowercase , atol=1E-3 ) print(f'''Saving model {swinva_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) model.push_to_hub( repo_path_or_name=Path(lowercase , lowercase ) , organization='''nandwalritik''' , commit_message='''Add model''' , ) if __name__ == "__main__": lowerCamelCase_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swinv2_name""", default="""swinv2_tiny_patch4_window8_256""", type=str, help="""Name of the Swinv2 timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowerCamelCase_ : Union[str, Any] = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
81
1
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ : Optional[Any] = logging.get_logger(__name__) lowerCamelCase_ : List[str] = { """Salesforce/instruct-blip-flan-t5""": """https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json""", } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "instructblip_vision_model" def __init__( self , __A=1408 , __A=6144 , __A=39 , __A=16 , __A=224 , __A=14 , __A="gelu" , __A=1E-6 , __A=0.0 , __A=1E-1_0 , __A=True , **__A , ) -> Tuple: super().__init__(**__A ) a =hidden_size a =intermediate_size a =num_hidden_layers a =num_attention_heads a =patch_size a =image_size a =initializer_range a =attention_dropout a =layer_norm_eps a =hidden_act a =qkv_bias @classmethod def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> "PretrainedConfig": cls._set_token_in_kwargs(__A ) a , a =cls.get_config_dict(__A , **__A ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('''model_type''' ) == "instructblip": a =config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__A , **__A ) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "instructblip_qformer" def __init__( self , __A=3_0522 , __A=768 , __A=12 , __A=12 , __A=3072 , __A="gelu" , __A=0.1 , __A=0.1 , __A=512 , __A=0.02 , __A=1E-1_2 , __A=0 , __A="absolute" , __A=2 , __A=1408 , **__A , ) -> Union[str, Any]: super().__init__(pad_token_id=__A , **__A ) a =vocab_size a =hidden_size a =num_hidden_layers a =num_attention_heads a =hidden_act a =intermediate_size a =hidden_dropout_prob a =attention_probs_dropout_prob a =max_position_embeddings a =initializer_range a =layer_norm_eps a =position_embedding_type a =cross_attention_frequency a =encoder_hidden_size @classmethod def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> "PretrainedConfig": cls._set_token_in_kwargs(__A ) a , a =cls.get_config_dict(__A , **__A ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('''model_type''' ) == "instructblip": a =config_dict['''qformer_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__A , **__A ) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "instructblip" __lowerCAmelCase = True def __init__( self , __A=None , __A=None , __A=None , __A=32 , **__A ) -> Optional[int]: super().__init__(**__A ) if vision_config is None: a ={} logger.info('''vision_config is None. initializing the InstructBlipVisionConfig with default values.''' ) if qformer_config is None: a ={} logger.info('''qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.''' ) if text_config is None: a ={} logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''' ) a =InstructBlipVisionConfig(**__A ) a =InstructBlipQFormerConfig(**__A ) a =text_config['''model_type'''] if '''model_type''' in text_config else '''opt''' a =CONFIG_MAPPING[text_model_type](**__A ) a =self.text_config.tie_word_embeddings a =self.text_config.is_encoder_decoder a =num_query_tokens a =self.vision_config.hidden_size a =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES a =1.0 a =0.02 @classmethod def SCREAMING_SNAKE_CASE ( cls , __A , __A , __A , **__A , ) -> Any: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **__A , ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =copy.deepcopy(self.__dict__ ) a =self.vision_config.to_dict() a =self.qformer_config.to_dict() a =self.text_config.to_dict() a =self.__class__.model_type return output
81
"""simple docstring""" lowerCamelCase_ : Any = [ """DownloadConfig""", """DownloadManager""", """DownloadMode""", """StreamingDownloadManager""", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
81
1
"""simple docstring""" import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class __A ( unittest.TestCase ): """simple docstring""" @require_torch def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =pipeline( task='''zero-shot-audio-classification''' , model='''hf-internal-testing/tiny-clap-htsat-unfused''' ) a =load_dataset('''ashraq/esc50''' ) a =dataset['''train''']['''audio'''][-1]['''array'''] a =audio_classifier(__A , candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] ) self.assertEqual( nested_simplify(__A ) , [{'''score''': 0.501, '''label''': '''Sound of a dog'''}, {'''score''': 0.499, '''label''': '''Sound of vaccum cleaner'''}] , ) @unittest.skip('''No models are available in TF''' ) def SCREAMING_SNAKE_CASE ( self ) -> int: pass @slow @require_torch def SCREAMING_SNAKE_CASE ( self ) -> Any: a =pipeline( task='''zero-shot-audio-classification''' , model='''laion/clap-htsat-unfused''' , ) # This is an audio of a dog a =load_dataset('''ashraq/esc50''' ) a =dataset['''train''']['''audio'''][-1]['''array'''] a =audio_classifier(__A , candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] ) self.assertEqual( nested_simplify(__A ) , [ {'''score''': 0.999, '''label''': '''Sound of a dog'''}, {'''score''': 0.001, '''label''': '''Sound of vaccum cleaner'''}, ] , ) a =audio_classifier([audio] * 5 , candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] ) self.assertEqual( nested_simplify(__A ) , [ [ {'''score''': 0.999, '''label''': '''Sound of a dog'''}, {'''score''': 0.001, '''label''': '''Sound of vaccum cleaner'''}, ], ] * 5 , ) a =audio_classifier( [audio] * 5 , candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] , batch_size=5 ) self.assertEqual( nested_simplify(__A ) , [ [ {'''score''': 0.999, '''label''': '''Sound of a dog'''}, {'''score''': 0.001, '''label''': '''Sound of vaccum cleaner'''}, ], ] * 5 , ) @unittest.skip('''No models are available in TF''' ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: pass
81
"""simple docstring""" from scipy.stats import pearsonr import datasets lowerCamelCase_ : Optional[int] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ lowerCamelCase_ : Optional[Any] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ lowerCamelCase_ : Optional[int] = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Dict: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float''' ), '''references''': datasets.Value('''float''' ), } ) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A=False ) -> Optional[Any]: if return_pvalue: a =pearsonr(__A , __A ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(__A , __A )[0] )}
81
1
"""simple docstring""" import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging lowerCamelCase_ : Union[str, Any] = logging.get_logger(__name__) def _A ( lowercase , lowercase , lowercase ): """simple docstring""" a =nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(lowercase ) == len(lowercase ), f'''{len(lowercase )} != {len(lowercase )}''' dest_layers.load_state_dict(layers_to_copy.state_dict() ) lowerCamelCase_ : List[str] = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 1_2: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 1_1], 4: [0, 4, 8, 1_1], 6: [0, 2, 4, 7, 9, 1_1], 9: [0, 1, 2, 4, 5, 7, 9, 1_0, 1_1], 1_2: list(range(1_2)), }, 1_6: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 1_5], 3: [0, 8, 1_5], 4: [0, 5, 1_0, 1_5], 6: [0, 3, 6, 9, 1_2, 1_5], 8: [0, 2, 4, 6, 8, 1_0, 1_2, 1_5], 9: [0, 1, 3, 5, 7, 9, 1_1, 1_3, 1_5], 1_2: [0, 1, 2, 3, 4, 5, 6, 7, 9, 1_1, 1_3, 1_5], 1_6: list(range(1_6)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } lowerCamelCase_ : Union[str, Any] = { # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 1_2: {1: [1_1], 2: [5, 1_1], 3: [3, 7, 1_1], 6: [1, 3, 5, 8, 1_0, 1_1]}, 1_6: {1: [1_5], 4: [4, 9, 1_2, 1_5], 8: [1, 3, 5, 7, 9, 1_1, 1_3, 1_5]}, } def _A ( lowercase , lowercase ): """simple docstring""" try: a =LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( f'''no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first''' f''' {n_student}''' ) return list(range(lowercase ) ) def _A ( lowercase , lowercase ): """simple docstring""" if n_student > n_teacher: raise ValueError(f'''Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}''' ) elif n_teacher == n_student: return list(range(lowercase ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def _A ( lowercase , lowercase = "student" , lowercase = None , lowercase = None , lowercase=False , lowercase=None , lowercase=None , **lowercase , ): """simple docstring""" a ='''encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.''' assert (e is not None) or (d is not None), _msg if isinstance(lowercase , lowercase ): AutoTokenizer.from_pretrained(lowercase ).save_pretrained(lowercase ) # purely for convenience a =AutoModelForSeqaSeqLM.from_pretrained(lowercase ).eval() else: assert isinstance(lowercase , lowercase ), f'''teacher must be a model or string got type {type(lowercase )}''' a =teacher.config.to_diff_dict() try: a , a =teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: a =teacher_e if d is None: a =teacher_d init_kwargs.update({'''encoder_layers''': e, '''decoder_layers''': d} ) except AttributeError: # T5 if hasattr(teacher.config , '''num_encoder_layers''' ): a , a =teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: a , a =teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: a =teacher_e if d is None: a =teacher_d if hasattr(teacher.config , '''num_encoder_layers''' ): init_kwargs.update({'''num_encoder_layers''': e, '''num_decoder_layers''': d} ) else: init_kwargs.update({'''num_layers''': e, '''num_decoder_layers''': d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(lowercase ) # Copy weights a =teacher.config_class(**lowercase ) a =AutoModelForSeqaSeqLM.from_config(lowercase ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. a =student.load_state_dict(teacher.state_dict() , strict=lowercase ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save a , a =list(range(lowercase ) ), list(range(lowercase ) ) logger.info( f'''Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to''' f''' {save_path}''' ) student.save_pretrained(lowercase ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: a =pick_layers_to_copy(lowercase , lowercase ) if d_layers_to_copy is None: a =pick_layers_to_copy(lowercase , lowercase ) try: if hasattr( lowercase , '''prophetnet''' ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , lowercase ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , lowercase ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , lowercase ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , lowercase ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , lowercase ) copy_layers(teacher.decoder.block , student.decoder.block , lowercase ) logger.info( f'''Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}''' ) a ={ '''teacher_type''': teacher.config.model_type, '''copied_encoder_layers''': e_layers_to_copy, '''copied_decoder_layers''': d_layers_to_copy, } student.save_pretrained(lowercase ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
81
"""simple docstring""" lowerCamelCase_ : int = """ # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git """ lowerCamelCase_ : Dict = [{"""type""": """code""", """content""": INSTALL_CONTENT}] lowerCamelCase_ : Union[str, Any] = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
81
1
"""simple docstring""" import os from collections import namedtuple import pytest from datasets import ClassLabel, Features, Sequence, Value from datasets.commands.test import TestCommand from datasets.info import DatasetInfo, DatasetInfosDict lowerCamelCase_ : Optional[int] = namedtuple( """_TestCommandArgs""", [ """dataset""", """name""", """cache_dir""", """data_dir""", """all_configs""", """save_infos""", """ignore_verifications""", """force_redownload""", """clear_cache""", ], defaults=[None, None, None, False, False, False, False, False], ) def _A ( lowercase , lowercase ): """simple docstring""" return (abs(source - target ) / target) < 0.01 @pytest.mark.integration def _A ( lowercase ): """simple docstring""" a =_TestCommandArgs(dataset=lowercase , all_configs=lowercase , save_infos=lowercase ) a =TestCommand(*lowercase ) test_command.run() a =os.path.join(lowercase , '''README.md''' ) assert os.path.exists(lowercase ) a =DatasetInfosDict.from_directory(lowercase ) a =DatasetInfosDict( { '''default''': DatasetInfo( features=Features( { '''tokens''': Sequence(Value('''string''' ) ), '''ner_tags''': Sequence( ClassLabel(names=['''O''', '''B-PER''', '''I-PER''', '''B-ORG''', '''I-ORG''', '''B-LOC''', '''I-LOC'''] ) ), '''langs''': Sequence(Value('''string''' ) ), '''spans''': Sequence(Value('''string''' ) ), } ) , splits=[ { '''name''': '''train''', '''num_bytes''': 2_35_15_63, '''num_examples''': 1_00_00, }, { '''name''': '''validation''', '''num_bytes''': 23_84_18, '''num_examples''': 10_00, }, ] , download_size=3_94_06_80 , dataset_size=2_58_99_81 , ) } ) assert dataset_infos.keys() == expected_dataset_infos.keys() for key in DatasetInfo._INCLUDED_INFO_IN_YAML: a , a =getattr(dataset_infos['''default'''] , lowercase ), getattr(expected_dataset_infos['''default'''] , lowercase ) if key == "num_bytes": assert is_apercent_close(lowercase , lowercase ) elif key == "splits": assert list(lowercase ) == list(lowercase ) for split in result: assert result[split].name == expected[split].name assert result[split].num_examples == expected[split].num_examples assert is_apercent_close(result[split].num_bytes , expected[split].num_bytes ) else: result == expected
81
"""simple docstring""" def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =set() # Replace all the whitespace in our sentence a =input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowercase ) == 26 def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =[False] * 26 for char in input_str: if char.islower(): a =True elif char.isupper(): a =True return all(lowercase ) def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _A ( ): """simple docstring""" from timeit import timeit a ='''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowercase ) ) print(timeit('''is_pangram_faster()''' , setup=lowercase ) ) print(timeit('''is_pangram_fastest()''' , setup=lowercase ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
81
1
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline lowerCamelCase_ : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , __A , __A ) -> Any: super().__init__() self.register_modules(unet=__A , scheduler=__A ) @torch.no_grad() def __call__( self , __A = 1 , __A = 100 , __A = None , __A = None , __A = True , ) -> Union[AudioPipelineOutput, Tuple]: if audio_length_in_s is None: a =self.unet.config.sample_size / self.unet.config.sample_rate a =audio_length_in_s * self.unet.config.sample_rate a =2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( f'''{audio_length_in_s} is too small. Make sure it\'s bigger or equal to''' f''' {3 * down_scale_factor / self.unet.config.sample_rate}.''' ) a =int(__A ) if sample_size % down_scale_factor != 0: a =( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( f'''{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled''' f''' by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising''' ''' process.''' ) a =int(__A ) a =next(iter(self.unet.parameters() ) ).dtype a =(batch_size, self.unet.config.in_channels, sample_size) if isinstance(__A , __A ) and len(__A ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(__A )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) a =randn_tensor(__A , generator=__A , device=self.device , dtype=__A ) # set step values self.scheduler.set_timesteps(__A , device=audio.device ) a =self.scheduler.timesteps.to(__A ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output a =self.unet(__A , __A ).sample # 2. compute previous image: x_t -> t_t-1 a =self.scheduler.step(__A , __A , __A ).prev_sample a =audio.clamp(-1 , 1 ).float().cpu().numpy() a =audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=__A )
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys lowerCamelCase_ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : Union[str, Any] = { """configuration_table_transformer""": [ """TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TableTransformerConfig""", """TableTransformerOnnxConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TableTransformerForObjectDetection""", """TableTransformerModel""", """TableTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
"""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 lowerCamelCase_ : Dict = logging.getLogger(__name__) lowerCamelCase_ : Tuple = """pytorch_model.bin""" @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co."}, ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the training data."} ) __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the data to predict on."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "A csv or a json file containing the validation data."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The name of the task to train on."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The list of labels for the task."} ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "The output directory where the model predictions and checkpoints will be written."} ) __lowerCAmelCase = dataclasses.field( default="accuracy", metadata={"help": "The evaluation metric used for the task."} ) __lowerCAmelCase = dataclasses.field( default="no", metadata={ "help": "The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]" }, ) __lowerCAmelCase = dataclasses.field( default=10, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={ "help": "How much the specified evaluation metric must improve to satisfy early stopping conditions." }, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the confidence score."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the validation performance."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to fine-tune on labeled data after pseudo training."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={"help": "Confidence threshold for pseudo-labeled data filtering."}, ) __lowerCAmelCase = dataclasses.field( default=100, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Random seed for initialization."}, ) def _A ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: a =dataset.filter(lambda lowercase : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 a =int(eval_result * len(lowercase ) ) print(lowercase ) a =dataset.sort('''probability''' , reverse=lowercase ) a =dataset.select(range(lowercase ) ) a =dataset.remove_columns(['''label''', '''probability'''] ) a =dataset.rename_column('''prediction''' , '''label''' ) a =dataset.map(lambda lowercase : {"label": idalabel[example["label"]]} ) a =dataset.shuffle(seed=args.seed ) a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(lowercase , index=lowercase ) else: dataset.to_json(lowercase ) def _A ( lowercase , lowercase , lowercase , lowercase , **lowercase ): """simple docstring""" a =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() a =STModelArguments(model_name_or_path=lowercase ) a =STDataArguments(train_file=lowercase , infer_file=lowercase ) a =STTrainingArguments(output_dir=lowercase ) a =argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(lowercase ).items(): setattr(lowercase , lowercase , lowercase ) for key, value in kwargs.items(): if hasattr(lowercase , lowercase ): setattr(lowercase , lowercase , lowercase ) # Sanity checks a ={} a =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 a =args.train_file a =args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None a =args.eval_file for key in data_files: a =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: a =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...''' ) a =f'''{args.output_dir}/self-train_iter-{{}}'''.format a =data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=lowercase ) os.makedirs(lowercase , exist_ok=lowercase ) accelerator.wait_for_everyone() a =None a =None a =0 a =False # Show the progress bar a =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 ) ): a =data_dir_format(lowercase ) assert os.path.exists(lowercase ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 a =os.path.join(lowercase , '''stage-1''' ) a ={ '''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(lowercase , lowercase ): arguments_dict.update({key: value} ) a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 1 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 1.''' , lowercase ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data a =os.path.join(lowercase , '''best-checkpoint''' ) a =os.path.join(lowercase , '''stage-2''' ) # Update arguments_dict a =model_path a =data_files['''train'''] a =current_output_dir a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 2 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 2.''' , lowercase ) a =iteration a =data_dir_format(iteration + 1 ) a =AutoConfig.from_pretrained(os.path.join(lowercase , '''best-checkpoint''' ) ) a =config.idalabel a =os.path.join(lowercase , '''eval_results_best-checkpoint.json''' ) a =os.path.join(lowercase , '''test_results_best-checkpoint.json''' ) assert os.path.exists(lowercase ) with open(lowercase , '''r''' ) as f: a =float(json.load(lowercase )[args.eval_metric] ) a =os.path.join(lowercase , '''infer_output_best-checkpoint.csv''' ) assert os.path.exists(lowercase ) # Loading the dataset from local csv or json files. a =load_dataset(args.data_file_extension , data_files={'''data''': data_files['''infer''']} )['''data'''] a =load_dataset('''csv''' , data_files={'''data''': infer_output_file} )['''data'''] if accelerator.is_main_process: os.makedirs(lowercase , exist_ok=lowercase ) shutil.copy(lowercase , os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(lowercase ): shutil.copy(lowercase , os.path.join(lowercase , f'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) accelerator.wait_for_everyone() a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: a =eval_result if best_iteration is None: a =new_iteration a =new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: a =new_iteration a =new_eval_result a =0 else: if new_eval_result == best_eval_result: a =new_iteration a =new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: a =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''' , lowercase ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) , os.path.join(lowercase , '''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 , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(lowercase , '''eval_results_best-iteration.json''' ) , )
81
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowerCamelCase_ : List[str] = { """configuration_gpt_bigcode""": ["""GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTBigCodeConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : int = [ """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 lowerCamelCase_ : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
"""simple docstring""" def _A ( ): """simple docstring""" for n in range(1 , 1_00_00_00 ): yield n * (n + 1) // 2 def _A ( lowercase ): """simple docstring""" a =1 a =2 while i * i <= n: a =0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _A ( ): """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(lowercase ) > 5_00 ) if __name__ == "__main__": print(solution())
81
1
"""simple docstring""" import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = ProphetNetTokenizer __lowerCAmelCase = False def SCREAMING_SNAKE_CASE ( self ) -> List[str]: super().setUp() a =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a =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 SCREAMING_SNAKE_CASE ( self , __A ) -> Tuple: a ='''UNwant\u00E9d,running''' a ='''unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =self.tokenizer_class(self.vocab_file ) a =tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__A , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [9, 6, 7, 12, 10, 11] ) def SCREAMING_SNAKE_CASE ( self ) -> Any: a =BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Any: a =BasicTokenizer(do_lower_case=__A , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a ={} for i, token in enumerate(__A ): a =i a =WordpieceTokenizer(vocab=__A , 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'''] ) @require_torch def SCREAMING_SNAKE_CASE ( self ) -> int: a =self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) a =['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] a =[1037, 2146, 2_0423, 2005, 7680, 7849, 3989, 1012, 102] a =tokenizer(__A , padding=__A , return_tensors='''pt''' ) self.assertIsInstance(__A , __A ) a =list(batch.input_ids.numpy()[0] ) self.assertListEqual(__A , __A ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def SCREAMING_SNAKE_CASE ( self ) -> int: 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 SCREAMING_SNAKE_CASE ( self ) -> Dict: 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 SCREAMING_SNAKE_CASE ( self ) -> Tuple: 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(''' ''' ) ) @slow def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
81
"""simple docstring""" from math import factorial def _A ( lowercase = 1_00 ): """simple docstring""" return sum(int(lowercase ) for x in str(factorial(lowercase ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
81
1
"""simple docstring""" import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow lowerCamelCase_ : Tuple = False class __A ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self , __A=32 ) -> List[Any]: set_seed(0 ) a =UNetaDModel(sample_size=__A , in_channels=3 , out_channels=3 ) a =torch.optim.SGD(model.parameters() , lr=0.0_001 ) return model, optimizer @slow def SCREAMING_SNAKE_CASE ( self ) -> Any: a ='''cpu''' # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable a =DDPMScheduler( num_train_timesteps=1000 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule='''linear''' , clip_sample=__A , ) a =DDIMScheduler( num_train_timesteps=1000 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule='''linear''' , clip_sample=__A , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) a =[torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(__A ) for _ in range(4 )] a =[torch.randn((4, 3, 32, 32) ).to(__A ) for _ in range(4 )] a =[torch.randint(0 , 1000 , (4,) ).long().to(__A ) for _ in range(4 )] # train with a DDPM scheduler a , a =self.get_model_optimizer(resolution=32 ) model.train().to(__A ) for i in range(4 ): optimizer.zero_grad() a =ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) a =model(__A , timesteps[i] ).sample a =torch.nn.functional.mse_loss(__A , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM a , a =self.get_model_optimizer(resolution=32 ) model.train().to(__A ) for i in range(4 ): optimizer.zero_grad() a =ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) a =model(__A , timesteps[i] ).sample a =torch.nn.functional.mse_loss(__A , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(__A , __A , atol=1E-5 ) ) self.assertTrue(torch.allclose(__A , __A , atol=1E-5 ) )
81
"""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, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Optional[Any] = """▁""" lowerCamelCase_ : Union[str, Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : Any = { """vocab_file""": { """xlm-roberta-base""": """https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large""": """https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large-finetuned-conll02-dutch""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll02-spanish""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-english""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-german""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model""" ), } } lowerCamelCase_ : Tuple = { """xlm-roberta-base""": 5_1_2, """xlm-roberta-large""": 5_1_2, """xlm-roberta-large-finetuned-conll02-dutch""": 5_1_2, """xlm-roberta-large-finetuned-conll02-spanish""": 5_1_2, """xlm-roberta-large-finetuned-conll03-english""": 5_1_2, """xlm-roberta-large-finetuned-conll03-german""": 5_1_2, } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a =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 a ={'''<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 a =1 a =len(self.sp_model ) + self.fairseq_offset a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: a =self.__dict__.copy() a =None a =self.sp_model.serialized_model_proto() return state def __setstate__( self , __A ) -> List[Any]: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[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] @property def SCREAMING_SNAKE_CASE ( self ) -> List[str]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> int: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =self.sp_model.PieceToId(__A ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: a =''''''.join(__A ).replace(__A , ''' ''' ).strip() return out_string def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , '''wb''' ) as fi: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
1
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowerCamelCase_ : str = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = XLNetTokenizer __lowerCAmelCase = XLNetTokenizerFast __lowerCAmelCase = True __lowerCAmelCase = True def SCREAMING_SNAKE_CASE ( self ) -> Tuple: super().setUp() # We have a SentencePiece fixture for testing a =XLNetTokenizer(__A , keep_accents=__A ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a ='''<s>''' a =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__A ) , __A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''<eod>''' ) self.assertEqual(len(__A ) , 1006 ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =XLNetTokenizer(__A , keep_accents=__A ) a =tokenizer.tokenize('''This is a test''' ) self.assertListEqual(__A , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [285, 46, 10, 170, 382] ) a =tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __A , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) a =tokenizer.convert_tokens_to_ids(__A ) self.assertListEqual(__A , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) a =tokenizer.convert_ids_to_tokens(__A ) self.assertListEqual( __A , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =XLNetTokenizer(__A , do_lower_case=__A ) a =tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __A , [ SPIECE_UNDERLINE + '''''', '''i''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''se''', '''.''', ] , ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''▁he''', '''ll''', '''o'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =XLNetTokenizer(__A , do_lower_case=__A ) a =tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __A , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''se''', '''.''', ] , ) @slow def SCREAMING_SNAKE_CASE ( self ) -> str: a =XLNetTokenizer.from_pretrained('''xlnet-base-cased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: # fmt: off a ={'''input_ids''': [[17, 2_1442, 270, 17, 10, 1_4645, 318, 34, 17, 4546, 3145, 787, 13, 7752, 2_2018, 23, 21, 17, 4546, 3145, 787, 13, 3352, 1_4431, 13, 5500, 11, 1176, 580, 13, 1_6819, 4797, 23, 17, 10, 1_7135, 658, 19, 457, 7932, 13, 184, 19, 3154, 1_7135, 6468, 19, 1404, 1_2269, 19, 4229, 5356, 1_6264, 46, 19, 17, 2_0545, 1_0395, 9, 9, 9, 11, 28, 6421, 9531, 2_0729, 17, 10, 353, 1_7022, 11, 21, 6421, 9531, 1_6949, 17, 10, 1_1509, 753, 11, 33, 95, 2421, 7385, 956, 1_4431, 2626, 25, 842, 7385, 4836, 21, 1429, 2272, 9855, 3120, 161, 2_4738, 19, 1_3203, 658, 218, 787, 21, 430, 1_8482, 847, 2637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 2_2178, 27, 1064, 22, 956, 13, 1_1101, 1429, 5854, 2_4313, 1_8953, 40, 422, 2_4366, 68, 1758, 37, 1_0483, 1_4257, 31, 207, 263, 21, 203, 3773, 25, 71, 9735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2049, 3442, 17, 1_3894, 3380, 23, 95, 18, 1_7634, 2288, 9, 4, 3]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__A , model_name='''xlnet-base-cased''' , revision='''c841166438c31ec7ca9a106dee7bb312b73ae511''' , )
81
"""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, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Tuple = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : str = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } lowerCamelCase_ : Optional[int] = { """moussaKam/mbarthez""": 1_0_2_4, """moussaKam/barthez""": 1_0_2_4, """moussaKam/barthez-orangesum-title""": 1_0_2_4, } lowerCamelCase_ : Tuple = """▁""" class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =vocab_file a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a ={'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} a =len(self.sp_model ) - 1 a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[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] @property def SCREAMING_SNAKE_CASE ( self ) -> Any: return len(self.sp_model ) def SCREAMING_SNAKE_CASE ( self ) -> int: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Dict: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =self.sp_model.PieceToId(__A ) return spm_id if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Tuple: a =[] a ='''''' a =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__A ) + token a =True a =[] else: current_sub_tokens.append(__A ) a =False out_string += self.sp_model.decode(__A ) return out_string.strip() def __getstate__( self ) -> Tuple: a =self.__dict__.copy() a =None return state def __setstate__( self , __A ) -> Tuple: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , '''wb''' ) as fi: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
1
"""simple docstring""" import argparse lowerCamelCase_ : int = """docs/source/_static/js/custom.js""" def _A ( lowercase ): """simple docstring""" with open(lowercase , encoding='''utf-8''' , newline='''\n''' ) as f: a =f.readlines() a =0 # First let's put the right version while not lines[index].startswith('''const stableVersion =''' ): index += 1 a =f'''const stableVersion = "v{version}"\n''' # Then update the dictionary while not lines[index].startswith('''const versionMapping = {''' ): index += 1 # We go until the end while not lines[index].startswith('''}''' ): index += 1 # We add the new version at the end lines[index - 1] += f''' "v{version}": "v{version}",\n''' with open(lowercase , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lowercase ) if __name__ == "__main__": lowerCamelCase_ : List[str] = argparse.ArgumentParser() parser.add_argument("""--version""", help="""Release version.""") lowerCamelCase_ : Optional[Any] = parser.parse_args() update_custom_js(args.version)
81
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) lowerCamelCase_ : Tuple = logging.get_logger(__name__) lowerCamelCase_ : str = OrderedDict( [ ("""align""", """EfficientNetImageProcessor"""), ("""beit""", """BeitImageProcessor"""), ("""bit""", """BitImageProcessor"""), ("""blip""", """BlipImageProcessor"""), ("""blip-2""", """BlipImageProcessor"""), ("""bridgetower""", """BridgeTowerImageProcessor"""), ("""chinese_clip""", """ChineseCLIPImageProcessor"""), ("""clip""", """CLIPImageProcessor"""), ("""clipseg""", """ViTImageProcessor"""), ("""conditional_detr""", """ConditionalDetrImageProcessor"""), ("""convnext""", """ConvNextImageProcessor"""), ("""convnextv2""", """ConvNextImageProcessor"""), ("""cvt""", """ConvNextImageProcessor"""), ("""data2vec-vision""", """BeitImageProcessor"""), ("""deformable_detr""", """DeformableDetrImageProcessor"""), ("""deit""", """DeiTImageProcessor"""), ("""deta""", """DetaImageProcessor"""), ("""detr""", """DetrImageProcessor"""), ("""dinat""", """ViTImageProcessor"""), ("""donut-swin""", """DonutImageProcessor"""), ("""dpt""", """DPTImageProcessor"""), ("""efficientformer""", """EfficientFormerImageProcessor"""), ("""efficientnet""", """EfficientNetImageProcessor"""), ("""flava""", """FlavaImageProcessor"""), ("""focalnet""", """BitImageProcessor"""), ("""git""", """CLIPImageProcessor"""), ("""glpn""", """GLPNImageProcessor"""), ("""groupvit""", """CLIPImageProcessor"""), ("""imagegpt""", """ImageGPTImageProcessor"""), ("""instructblip""", """BlipImageProcessor"""), ("""layoutlmv2""", """LayoutLMv2ImageProcessor"""), ("""layoutlmv3""", """LayoutLMv3ImageProcessor"""), ("""levit""", """LevitImageProcessor"""), ("""mask2former""", """Mask2FormerImageProcessor"""), ("""maskformer""", """MaskFormerImageProcessor"""), ("""mgp-str""", """ViTImageProcessor"""), ("""mobilenet_v1""", """MobileNetV1ImageProcessor"""), ("""mobilenet_v2""", """MobileNetV2ImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevitv2""", """MobileViTImageProcessor"""), ("""nat""", """ViTImageProcessor"""), ("""oneformer""", """OneFormerImageProcessor"""), ("""owlvit""", """OwlViTImageProcessor"""), ("""perceiver""", """PerceiverImageProcessor"""), ("""pix2struct""", """Pix2StructImageProcessor"""), ("""poolformer""", """PoolFormerImageProcessor"""), ("""regnet""", """ConvNextImageProcessor"""), ("""resnet""", """ConvNextImageProcessor"""), ("""sam""", """SamImageProcessor"""), ("""segformer""", """SegformerImageProcessor"""), ("""swiftformer""", """ViTImageProcessor"""), ("""swin""", """ViTImageProcessor"""), ("""swin2sr""", """Swin2SRImageProcessor"""), ("""swinv2""", """ViTImageProcessor"""), ("""table-transformer""", """DetrImageProcessor"""), ("""timesformer""", """VideoMAEImageProcessor"""), ("""tvlt""", """TvltImageProcessor"""), ("""upernet""", """SegformerImageProcessor"""), ("""van""", """ConvNextImageProcessor"""), ("""videomae""", """VideoMAEImageProcessor"""), ("""vilt""", """ViltImageProcessor"""), ("""vit""", """ViTImageProcessor"""), ("""vit_hybrid""", """ViTHybridImageProcessor"""), ("""vit_mae""", """ViTImageProcessor"""), ("""vit_msn""", """ViTImageProcessor"""), ("""xclip""", """CLIPImageProcessor"""), ("""yolos""", """YolosImageProcessor"""), ] ) lowerCamelCase_ : Union[str, Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def _A ( lowercase ): """simple docstring""" for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: a =model_type_to_module_name(lowercase ) a =importlib.import_module(f'''.{module_name}''' , '''transformers.models''' ) try: return getattr(lowercase , lowercase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowercase , '''__name__''' , lowercase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. a =importlib.import_module('''transformers''' ) if hasattr(lowercase , lowercase ): return getattr(lowercase , lowercase ) return None def _A ( lowercase , lowercase = None , lowercase = False , lowercase = False , lowercase = None , lowercase = None , lowercase = None , lowercase = False , **lowercase , ): """simple docstring""" a =get_file_from_repo( lowercase , lowercase , cache_dir=lowercase , force_download=lowercase , resume_download=lowercase , proxies=lowercase , use_auth_token=lowercase , revision=lowercase , local_files_only=lowercase , ) if resolved_config_file is None: logger.info( '''Could not locate the image processor configuration file, will try to use the model config instead.''' ) return {} with open(lowercase , encoding='''utf-8''' ) as reader: return json.load(lowercase ) class __A : """simple docstring""" def __init__( self ) -> Optional[Any]: raise EnvironmentError( '''AutoImageProcessor is designed to be instantiated ''' '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__A ) def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> Dict: a =kwargs.pop('''config''' , __A ) a =kwargs.pop('''trust_remote_code''' , __A ) a =True a , a =ImageProcessingMixin.get_image_processor_dict(__A , **__A ) a =config_dict.get('''image_processor_type''' , __A ) a =None if "AutoImageProcessor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoImageProcessor'''] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: a =config_dict.pop('''feature_extractor_type''' , __A ) if feature_extractor_class is not None: logger.warning( '''Could not find image processor class in the image processor config or the model config. Loading''' ''' based on pattern matching with the model\'s feature extractor configuration.''' ) a =feature_extractor_class.replace('''FeatureExtractor''' , '''ImageProcessor''' ) if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoFeatureExtractor'''] a =feature_extractor_auto_map.replace('''FeatureExtractor''' , '''ImageProcessor''' ) logger.warning( '''Could not find image processor auto map in the image processor config or the model config.''' ''' Loading based on pattern matching with the model\'s feature extractor configuration.''' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(__A , __A ): a =AutoConfig.from_pretrained(__A , **__A ) # It could be in `config.image_processor_type`` a =getattr(__A , '''image_processor_type''' , __A ) if hasattr(__A , '''auto_map''' ) and "AutoImageProcessor" in config.auto_map: a =config.auto_map['''AutoImageProcessor'''] if image_processor_class is not None: a =image_processor_class_from_name(__A ) a =image_processor_auto_map is not None a =image_processor_class is not None or type(__A ) in IMAGE_PROCESSOR_MAPPING a =resolve_trust_remote_code( __A , __A , __A , __A ) if has_remote_code and trust_remote_code: a =get_class_from_dynamic_module( __A , __A , **__A ) a =kwargs.pop('''code_revision''' , __A ) if os.path.isdir(__A ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(__A , **__A ) elif image_processor_class is not None: return image_processor_class.from_dict(__A , **__A ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(__A ) in IMAGE_PROCESSOR_MAPPING: a =IMAGE_PROCESSOR_MAPPING[type(__A )] return image_processor_class.from_dict(__A , **__A ) raise ValueError( f'''Unrecognized image processor in {pretrained_model_name_or_path}. Should have a ''' f'''`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def SCREAMING_SNAKE_CASE ( __A , __A ) -> Any: IMAGE_PROCESSOR_MAPPING.register(__A , __A )
81
1
"""simple docstring""" import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def _A ( lowercase ): """simple docstring""" a =SwinConfig() a =swin_name.split('''_''' ) a =name_split[1] a =int(name_split[4] ) a =int(name_split[3][-1] ) if model_size == "tiny": a =96 a =(2, 2, 6, 2) a =(3, 6, 12, 24) elif model_size == "small": a =96 a =(2, 2, 18, 2) a =(3, 6, 12, 24) elif model_size == "base": a =1_28 a =(2, 2, 18, 2) a =(4, 8, 16, 32) else: a =1_92 a =(2, 2, 18, 2) a =(6, 12, 24, 48) if "in22k" in swin_name: a =2_18_41 else: a =10_00 a ='''huggingface/label-files''' a ='''imagenet-1k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} a =img_size a =num_classes a =embed_dim a =depths a =num_heads a =window_size return config def _A ( lowercase ): """simple docstring""" if "patch_embed.proj" in name: a =name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: a =name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: a ='''encoder.''' + name if "attn.proj" in name: a =name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: a =name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: a =name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: a =name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: a =name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: a =name.replace('''mlp.fc2''' , '''output.dense''' ) if name == "norm.weight": a ='''layernorm.weight''' if name == "norm.bias": a ='''layernorm.bias''' if "head" in name: a =name.replace('''head''' , '''classifier''' ) else: a ='''swin.''' + name return name def _A ( lowercase , lowercase ): """simple docstring""" for key in orig_state_dict.copy().keys(): a =orig_state_dict.pop(lowercase ) if "mask" in key: continue elif "qkv" in key: a =key.split('''.''' ) a =int(key_split[1] ) a =int(key_split[3] ) a =model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a =val[:dim, :] a =val[ dim : dim * 2, : ] a =val[-dim:, :] else: a =val[ :dim ] a =val[ dim : dim * 2 ] a =val[ -dim: ] else: a =val return orig_state_dict def _A ( lowercase , lowercase ): """simple docstring""" a =timm.create_model(lowercase , pretrained=lowercase ) timm_model.eval() a =get_swin_config(lowercase ) a =SwinForImageClassification(lowercase ) model.eval() a =convert_state_dict(timm_model.state_dict() , lowercase ) model.load_state_dict(lowercase ) a ='''http://images.cocodataset.org/val2017/000000039769.jpg''' a =AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swin_name.replace('''_''' , '''-''' ) ) ) a =Image.open(requests.get(lowercase , stream=lowercase ).raw ) a =image_processor(images=lowercase , return_tensors='''pt''' ) a =timm_model(inputs['''pixel_values'''] ) a =model(**lowercase ).logits assert torch.allclose(lowercase , lowercase , atol=1E-3 ) print(f'''Saving model {swin_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) if __name__ == "__main__": lowerCamelCase_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swin_name""", default="""swin_tiny_patch4_window7_224""", type=str, help="""Name of the Swin timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowerCamelCase_ : str = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
81
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = DistilBertTokenizer __lowerCAmelCase = DistilBertTokenizerFast __lowerCAmelCase = True @slow def SCREAMING_SNAKE_CASE ( self ) -> int: a =DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
81
1
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : List[Any] = logging.get_logger(__name__) lowerCamelCase_ : Any = {"""vocab_file""": """spiece.model"""} lowerCamelCase_ : int = { """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } lowerCamelCase_ : Optional[Any] = { """albert-base-v1""": 5_1_2, """albert-large-v1""": 5_1_2, """albert-xlarge-v1""": 5_1_2, """albert-xxlarge-v1""": 5_1_2, """albert-base-v2""": 5_1_2, """albert-large-v2""": 5_1_2, """albert-xlarge-v2""": 5_1_2, """albert-xxlarge-v2""": 5_1_2, } lowerCamelCase_ : int = """▁""" class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , __A , __A=True , __A=True , __A=False , __A="[CLS]" , __A="[SEP]" , __A="<unk>" , __A="[SEP]" , __A="<pad>" , __A="[CLS]" , __A="[MASK]" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. a =( AddedToken(__A , lstrip=__A , rstrip=__A , normalized=__A ) if isinstance(__A , __A ) else mask_token ) a ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__A , remove_space=__A , keep_accents=__A , bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , pad_token=__A , cls_token=__A , mask_token=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =do_lower_case a =remove_space a =keep_accents a =vocab_file a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> Dict: return len(self.sp_model ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> Tuple: a =self.__dict__.copy() a =None return state def __setstate__( self , __A ) -> Optional[int]: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Any: if self.remove_space: a =''' '''.join(inputs.strip().split() ) else: a =inputs a =outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: a =unicodedata.normalize('''NFKD''' , __A ) a =''''''.join([c for c in outputs if not unicodedata.combining(__A )] ) if self.do_lower_case: a =outputs.lower() return outputs def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: a =self.preprocess_text(__A ) a =self.sp_model.encode(__A , out_type=__A ) a =[] for piece in pieces: if len(__A ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): a =self.sp_model.EncodeAsPieces(piece[:-1].replace(__A , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: a =cur_pieces[1:] else: a =cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__A ) else: new_pieces.append(__A ) return new_pieces def SCREAMING_SNAKE_CASE ( self , __A ) -> List[Any]: return self.sp_model.PieceToId(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> int: return self.sp_model.IdToPiece(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[int]: a =[] a ='''''' a =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__A ) + token a =True a =[] else: current_sub_tokens.append(__A ) a =False out_string += self.sp_model.decode(__A ) return out_string.strip() def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is not None: return [1] + ([0] * len(__A )) + [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[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 SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , '''wb''' ) as fi: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCamelCase_ : List[str] = { """configuration_speech_to_text""": ["""SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Speech2TextConfig"""], """processing_speech_to_text""": ["""Speech2TextProcessor"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""Speech2TextTokenizer"""] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[Any] = ["""Speech2TextFeatureExtractor"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFSpeech2TextForConditionalGeneration""", """TFSpeech2TextModel""", """TFSpeech2TextPreTrainedModel""", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = [ """SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Speech2TextForConditionalGeneration""", """Speech2TextModel""", """Speech2TextPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ : Union[str, Any] = logging.get_logger(__name__) lowerCamelCase_ : Any = { """microsoft/conditional-detr-resnet-50""": ( """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json""" ), } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "conditional_detr" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , __A=True , __A=None , __A=3 , __A=300 , __A=6 , __A=2048 , __A=8 , __A=6 , __A=2048 , __A=8 , __A=0.0 , __A=0.0 , __A=True , __A="relu" , __A=256 , __A=0.1 , __A=0.0 , __A=0.0 , __A=0.02 , __A=1.0 , __A=False , __A="sine" , __A="resnet50" , __A=True , __A=False , __A=2 , __A=5 , __A=2 , __A=1 , __A=1 , __A=2 , __A=5 , __A=2 , __A=0.25 , **__A , ) -> List[Any]: if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) a =CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(__A , __A ): a =backbone_config.get('''model_type''' ) a =CONFIG_MAPPING[backbone_model_type] a =config_class.from_dict(__A ) a =use_timm_backbone a =backbone_config a =num_channels a =num_queries a =d_model a =encoder_ffn_dim a =encoder_layers a =encoder_attention_heads a =decoder_ffn_dim a =decoder_layers a =decoder_attention_heads a =dropout a =attention_dropout a =activation_dropout a =activation_function a =init_std a =init_xavier_std a =encoder_layerdrop a =decoder_layerdrop a =encoder_layers a =auxiliary_loss a =position_embedding_type a =backbone a =use_pretrained_backbone a =dilation # Hungarian matcher a =class_cost a =bbox_cost a =giou_cost # Loss coefficients a =mask_loss_coefficient a =dice_loss_coefficient a =cls_loss_coefficient a =bbox_loss_coefficient a =giou_loss_coefficient a =focal_alpha super().__init__(is_encoder_decoder=__A , **__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.d_model def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: a =self.backbone_config.to_dict() a =self.__class__.model_type return output class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def SCREAMING_SNAKE_CASE ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE ( self ) -> int: return 12
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : Union[str, Any] = { """configuration_table_transformer""": [ """TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TableTransformerConfig""", """TableTransformerOnnxConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TableTransformerForObjectDetection""", """TableTransformerModel""", """TableTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" 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 __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = BertTokenizer __lowerCAmelCase = BertTokenizerFast __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = filter_non_english def SCREAMING_SNAKE_CASE ( self ) -> List[str]: super().setUp() a =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a =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 SCREAMING_SNAKE_CASE ( self , __A ) -> Union[str, Any]: a ='''UNwant\u00E9d,running''' a ='''unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.tokenizer_class(self.vocab_file ) a =tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__A , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [9, 6, 7, 12, 10, 11] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: if not self.test_rust_tokenizer: return a =self.get_tokenizer() a =self.get_rust_tokenizer() a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) # With lower casing a =self.get_tokenizer(do_lower_case=__A ) a =self.get_rust_tokenizer(do_lower_case=__A ) a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Any: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =BasicTokenizer(do_lower_case=__A , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =BasicTokenizer() a ='''a\n\'ll !!to?\'d of, can\'t.''' a =['''a''', '''\'''', '''ll''', '''!''', '''!''', '''to''', '''?''', '''\'''', '''d''', '''of''', ''',''', '''can''', '''\'''', '''t''', '''.'''] self.assertListEqual(tokenizer.tokenize(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a ={} for i, token in enumerate(__A ): a =i a =WordpieceTokenizer(vocab=__A , 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 SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE ( self ) -> Any: 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 SCREAMING_SNAKE_CASE ( self ) -> str: 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 SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.get_tokenizer() a =self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.tokenizer_class.from_pretrained('''bert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def SCREAMING_SNAKE_CASE ( self ) -> Any: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' a =tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) a =tokenizer_r.do_lower_case if hasattr(__A , '''do_lower_case''' ) else False a =( [ ((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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =['''的''', '''人''', '''有'''] a =''''''.join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =True a =self.tokenizer_class.from_pretrained(__A , **__A ) a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) a =False a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =self.tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". a =[ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A )
81
"""simple docstring""" from __future__ import annotations import math def _A ( lowercase ): """simple docstring""" if num <= 0: a =f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(lowercase ) a =[True] * (num + 1) a =[] a =2 a =int(math.sqrt(lowercase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(lowercase ) # Set multiples of start be False for i in range(start * start , num + 1 , lowercase ): if sieve[i] is True: a =False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(lowercase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
81
1