code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import argparse import collections import json import os import re import string import sys import numpy as np a__ : Optional[int] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a__ : int = None def _UpperCamelCase ( ) -> Dict: '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0." ) parser.add_argument("data_file" , metavar="data.json" , help="Input data JSON file." ) parser.add_argument("pred_file" , metavar="pred.json" , help="Model predictions." ) parser.add_argument( "--out-file" , "-o" , metavar="eval.json" , help="Write accuracy metrics to file (default is stdout)." ) parser.add_argument( "--na-prob-file" , "-n" , metavar="na_prob.json" , help="Model estimates of probability of no answer." ) parser.add_argument( "--na-prob-thresh" , "-t" , type=__A , default=1.0 , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)." , ) parser.add_argument( "--out-image-dir" , "-p" , metavar="out_images" , default=__A , help="Save precision-recall curves to directory." ) parser.add_argument("--verbose" , "-v" , action="store_true" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = bool(qa["answers"]["text"] ) return qid_to_has_ans def _UpperCamelCase ( __A ) -> Optional[Any]: '''simple docstring''' def remove_articles(__A ): return ARTICLES_REGEX.sub(" " , __A ) def white_space_fix(__A ): return " ".join(text.split() ) def remove_punc(__A ): UpperCamelCase__ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__A ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__A ) ) ) ) def _UpperCamelCase ( __A ) -> int: '''simple docstring''' if not s: return [] return normalize_answer(__A ).split() def _UpperCamelCase ( __A , __A ) -> List[Any]: '''simple docstring''' return int(normalize_answer(__A ) == normalize_answer(__A ) ) def _UpperCamelCase ( __A , __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = collections.Counter(__A ) & collections.Counter(__A ) UpperCamelCase__ = sum(common.values() ) if len(__A ) == 0 or len(__A ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = (2 * precision * recall) / (precision + recall) return fa def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = qa["id"] UpperCamelCase__ = [t for t in qa["answers"]["text"] if normalize_answer(__A )] if not gold_answers: # For unanswerable questions, only correct answer is empty string UpperCamelCase__ = [""] if qid not in preds: print(F'''Missing prediction for {qid}''' ) continue UpperCamelCase__ = preds[qid] # Take max over all gold answers UpperCamelCase__ = max(compute_exact(__A , __A ) for a in gold_answers ) UpperCamelCase__ = max(compute_fa(__A , __A ) for a in gold_answers ) return exact_scores, fa_scores def _UpperCamelCase ( __A , __A , __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} for qid, s in scores.items(): UpperCamelCase__ = na_probs[qid] > na_prob_thresh if pred_na: UpperCamelCase__ = float(not qid_to_has_ans[qid] ) else: UpperCamelCase__ = s return new_scores def _UpperCamelCase ( __A , __A , __A=None ) -> List[Any]: '''simple docstring''' if not qid_list: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores.values() ) / total), ("f1", 100.0 * sum(fa_scores.values() ) / total), ("total", total), ] ) else: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("f1", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("total", total), ] ) def _UpperCamelCase ( __A , __A , __A ) -> Optional[int]: '''simple docstring''' for k in new_eval: UpperCamelCase__ = new_eval[k] def _UpperCamelCase ( __A , __A , __A , __A ) -> Optional[int]: '''simple docstring''' plt.step(__A , __A , color="b" , alpha=0.2 , where="post" ) plt.fill_between(__A , __A , step="post" , alpha=0.2 , color="b" ) plt.xlabel("Recall" ) plt.ylabel("Precision" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__A ) plt.savefig(__A ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A , __A=None , __A=None ) -> Any: '''simple docstring''' UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) UpperCamelCase__ = 0.0 UpperCamelCase__ = 1.0 UpperCamelCase__ = 0.0 UpperCamelCase__ = [1.0] UpperCamelCase__ = [0.0] UpperCamelCase__ = 0.0 for i, qid in enumerate(__A ): if qid_to_has_ans[qid]: true_pos += scores[qid] UpperCamelCase__ = true_pos / float(i + 1 ) UpperCamelCase__ = true_pos / float(__A ) if i == len(__A ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__A ) recalls.append(__A ) if out_image: plot_pr_curve(__A , __A , __A , __A ) return {"ap": 100.0 * avg_prec} def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if out_image_dir and not os.path.exists(__A ): os.makedirs(__A ) UpperCamelCase__ = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_exact.png" ) , title="Precision-Recall curve for Exact Match score" , ) UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_f1.png" ) , title="Precision-Recall curve for F1 score" , ) UpperCamelCase__ = {k: float(__A ) for k, v in qid_to_has_ans.items()} UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_oracle.png" ) , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)" , ) merge_eval(__A , __A , "pr_exact" ) merge_eval(__A , __A , "pr_f1" ) merge_eval(__A , __A , "pr_oracle" ) def _UpperCamelCase ( __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if not qid_list: return UpperCamelCase__ = [na_probs[k] for k in qid_list] UpperCamelCase__ = np.ones_like(__A ) / float(len(__A ) ) plt.hist(__A , weights=__A , bins=20 , range=(0.0, 1.0) ) plt.xlabel("Model probability of no-answer" ) plt.ylabel("Proportion of dataset" ) plt.title(F'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__A , F'''na_prob_hist_{name}.png''' ) ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A ) -> Tuple: '''simple docstring''' UpperCamelCase__ = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) UpperCamelCase__ = num_no_ans UpperCamelCase__ = cur_score UpperCamelCase__ = 0.0 UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) for i, qid in enumerate(__A ): if qid not in scores: continue if qid_to_has_ans[qid]: UpperCamelCase__ = scores[qid] else: if preds[qid]: UpperCamelCase__ = -1 else: UpperCamelCase__ = 0 cur_score += diff if cur_score > best_score: UpperCamelCase__ = cur_score UpperCamelCase__ = na_probs[qid] return 100.0 * best_score / len(__A ), best_thresh def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> Dict: '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ = best_exact UpperCamelCase__ = exact_thresh UpperCamelCase__ = best_fa UpperCamelCase__ = fa_thresh def _UpperCamelCase ( ) -> Any: '''simple docstring''' with open(OPTS.data_file ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = dataset_json["data"] with open(OPTS.pred_file ) as f: UpperCamelCase__ = json.load(__A ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: UpperCamelCase__ = json.load(__A ) else: UpperCamelCase__ = {k: 0.0 for k in preds} UpperCamelCase__ = make_qid_to_has_ans(__A ) # maps qid to True/False UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if v] UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if not v] UpperCamelCase__ , UpperCamelCase__ = get_raw_scores(__A , __A ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = make_eval_dict(__A , __A ) if has_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "HasAns" ) if no_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "NoAns" ) if OPTS.na_prob_file: find_all_best_thresh(__A , __A , __A , __A , __A , __A ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__A , __A , __A , __A , __A , OPTS.out_image_dir ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "hasAns" ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "noAns" ) if OPTS.out_file: with open(OPTS.out_file , "w" ) as f: json.dump(__A , __A ) else: print(json.dumps(__A , indent=2 ) ) if __name__ == "__main__": a__ : Optional[int] = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
80
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: if resistor <= 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative or zero value!''' raise ValueError(__A ) first_sum += 1 / float(__A ) index += 1 return 1 / first_sum def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: sum_r += resistor if resistor < 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative value!''' raise ValueError(__A ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
80
1
'''simple docstring''' def _UpperCamelCase ( __A ) -> int: '''simple docstring''' if not isinstance(__A , __A ) or number < 0: raise ValueError("Input must be a non-negative integer" ) UpperCamelCase__ = 0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
80
'''simple docstring''' import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class lowercase_ ( enum.Enum ): __UpperCAmelCase = 0 __UpperCAmelCase = 1 __UpperCAmelCase = 2 @add_end_docstrings(a__ ) class lowercase_ ( a__ ): __UpperCAmelCase = '\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n ' def __init__( self , *a , **a ): super().__init__(*a , **a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. UpperCamelCase__ = None if self.model.config.prefix is not None: UpperCamelCase__ = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. UpperCamelCase__ = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._sanitize_parameters(prefix=a , **self._forward_params ) UpperCamelCase__ = {**self._preprocess_params, **preprocess_params} UpperCamelCase__ = {**self._forward_params, **forward_params} def __a ( self , a=None , a=None , a=None , a=None , a=None , a=None , a=None , a=None , **a , ): UpperCamelCase__ = {} if prefix is not None: UpperCamelCase__ = prefix if prefix: UpperCamelCase__ = self.tokenizer( a , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = prefix_inputs["input_ids"].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' " [None, 'hole']" ) UpperCamelCase__ = handle_long_generation preprocess_params.update(a ) UpperCamelCase__ = generate_kwargs UpperCamelCase__ = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("`return_text` is mutually exclusive with `return_full_text`" ) if return_tensors is not None: raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`" ) UpperCamelCase__ = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("`return_text` is mutually exclusive with `return_tensors`" ) UpperCamelCase__ = ReturnType.TENSORS if return_type is not None: UpperCamelCase__ = return_type if clean_up_tokenization_spaces is not None: UpperCamelCase__ = clean_up_tokenization_spaces if stop_sequence is not None: UpperCamelCase__ = self.tokenizer.encode(a , add_special_tokens=a ) if len(a ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) UpperCamelCase__ = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __a ( self , *a , **a ): # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"add_space_before_punct_symbol": True} ) return super()._parse_and_tokenize(*a , **a ) def __call__( self , a , **a ): return super().__call__(a , **a ) def __a ( self , a , a="" , a=None , **a ): UpperCamelCase__ = self.tokenizer( prefix + prompt_text , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = prompt_text if handle_long_generation == "hole": UpperCamelCase__ = inputs["input_ids"].shape[-1] if "max_new_tokens" in generate_kwargs: UpperCamelCase__ = generate_kwargs["max_new_tokens"] else: UpperCamelCase__ = generate_kwargs.get("max_length" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("We cannot infer how many new tokens are expected" ) if cur_len + new_tokens > self.tokenizer.model_max_length: UpperCamelCase__ = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( "We cannot use `hole` to handle this generation the number of desired tokens exceeds the" " models max length" ) UpperCamelCase__ = inputs["input_ids"][:, -keep_length:] if "attention_mask" in inputs: UpperCamelCase__ = inputs["attention_mask"][:, -keep_length:] return inputs def __a ( self , a , **a ): UpperCamelCase__ = model_inputs["input_ids"] UpperCamelCase__ = model_inputs.get("attention_mask" , a ) # Allow empty prompts if input_ids.shape[1] == 0: UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = 1 else: UpperCamelCase__ = input_ids.shape[0] UpperCamelCase__ = model_inputs.pop("prompt_text" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. UpperCamelCase__ = generate_kwargs.pop("prefix_length" , 0 ) if prefix_length > 0: UpperCamelCase__ = "max_new_tokens" in generate_kwargs or ( "generation_config" in generate_kwargs and generate_kwargs["generation_config"].max_new_tokens is not None ) if not has_max_new_tokens: UpperCamelCase__ = generate_kwargs.get("max_length" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length UpperCamelCase__ = "min_new_tokens" in generate_kwargs or ( "generation_config" in generate_kwargs and generate_kwargs["generation_config"].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL UpperCamelCase__ = self.model.generate(input_ids=a , attention_mask=a , **a ) UpperCamelCase__ = generated_sequence.shape[0] if self.framework == "pt": UpperCamelCase__ = generated_sequence.reshape(a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": UpperCamelCase__ = tf.reshape(a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def __a ( self , a , a=ReturnType.FULL_TEXT , a=True ): UpperCamelCase__ = model_outputs["generated_sequence"][0] UpperCamelCase__ = model_outputs["input_ids"] UpperCamelCase__ = model_outputs["prompt_text"] UpperCamelCase__ = generated_sequence.numpy().tolist() UpperCamelCase__ = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: UpperCamelCase__ = {"generated_token_ids": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text UpperCamelCase__ = self.tokenizer.decode( a , skip_special_tokens=a , clean_up_tokenization_spaces=a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: UpperCamelCase__ = 0 else: UpperCamelCase__ = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=a , clean_up_tokenization_spaces=a , ) ) if return_type == ReturnType.FULL_TEXT: UpperCamelCase__ = prompt_text + text[prompt_length:] else: UpperCamelCase__ = text[prompt_length:] UpperCamelCase__ = {"generated_text": all_text} records.append(a ) return records
80
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Union[str, Any] = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys a__ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
80
'''simple docstring''' from ....utils import logging a__ : Optional[Any] = logging.get_logger(__name__) class lowercase_ ( a__ ): def __init__( self , a , a=None , a=20_48 ): UpperCamelCase__ = config.__dict__ UpperCamelCase__ = modal_hidden_size if num_labels: UpperCamelCase__ = num_labels
80
1
'''simple docstring''' import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def _UpperCamelCase ( __A ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ = {} UpperCamelCase__ = tokenizer(example["content"] , truncation=__A )["input_ids"] UpperCamelCase__ = len(example["content"] ) / len(output["input_ids"] ) return output a__ : Optional[Any] = HfArgumentParser(PretokenizationArguments) a__ : Optional[int] = parser.parse_args() if args.num_workers is None: a__ : str = multiprocessing.cpu_count() a__ : Tuple = AutoTokenizer.from_pretrained(args.tokenizer_dir) a__ : List[str] = time.time() a__ : Dict = load_dataset(args.dataset_name, split='train') print(F"""Dataset loaded in {time.time()-t_start:.2f}s""") a__ : Union[str, Any] = time.time() a__ : List[Any] = ds.map( tokenize, num_proc=args.num_workers, remove_columns=[ 'repo_name', 'path', 'copies', 'size', 'content', 'license', 'hash', 'line_mean', 'line_max', 'alpha_frac', 'autogenerated', ], ) print(F"""Dataset tokenized in {time.time()-t_start:.2f}s""") a__ : Optional[int] = time.time() ds.push_to_hub(args.tokenized_data_repo) print(F"""Data pushed to the hub in {time.time()-t_start:.2f}s""")
80
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent a__ : Tuple = {'UserAgent': UserAgent().random} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' UpperCamelCase__ = script.contents[0] UpperCamelCase__ = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class lowercase_ : def __init__( self , a ): UpperCamelCase__ = f'''https://www.instagram.com/{username}/''' UpperCamelCase__ = self.get_json() def __a ( self ): UpperCamelCase__ = requests.get(self.url , headers=a ).text UpperCamelCase__ = BeautifulSoup(a , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self ): return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self ): return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def __a ( self ): return self.user_data["username"] @property def __a ( self ): return self.user_data["full_name"] @property def __a ( self ): return self.user_data["biography"] @property def __a ( self ): return self.user_data["business_email"] @property def __a ( self ): return self.user_data["external_url"] @property def __a ( self ): return self.user_data["edge_followed_by"]["count"] @property def __a ( self ): return self.user_data["edge_follow"]["count"] @property def __a ( self ): return self.user_data["edge_owner_to_timeline_media"]["count"] @property def __a ( self ): return self.user_data["profile_pic_url_hd"] @property def __a ( self ): return self.user_data["is_verified"] @property def __a ( self ): return self.user_data["is_private"] def _UpperCamelCase ( __A = "github" ) -> None: '''simple docstring''' import os if os.environ.get("CI" ): return # test failing on GitHub Actions UpperCamelCase__ = InstagramUser(__A ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __A ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() a__ : Any = InstagramUser('github') print(instagram_user) print(F"""{instagram_user.number_of_posts = }""") print(F"""{instagram_user.number_of_followers = }""") print(F"""{instagram_user.number_of_followings = }""") print(F"""{instagram_user.email = }""") print(F"""{instagram_user.website = }""") print(F"""{instagram_user.profile_picture_url = }""") print(F"""{instagram_user.is_verified = }""") print(F"""{instagram_user.is_private = }""")
80
1
'''simple docstring''' import os import sys a__ : Tuple = os.path.join(os.path.dirname(__file__), 'src') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a__ : Optional[int] = [ 'torch', 'numpy', 'tokenizers', 'filelock', 'requests', 'tqdm', 'regex', 'sentencepiece', 'sacremoses', 'importlib_metadata', 'huggingface_hub', ] @add_start_docstrings(AutoConfig.__doc__ ) def _UpperCamelCase ( *__A , **__A ) -> str: '''simple docstring''' return AutoConfig.from_pretrained(*__A , **__A ) @add_start_docstrings(AutoTokenizer.__doc__ ) def _UpperCamelCase ( *__A , **__A ) -> List[str]: '''simple docstring''' return AutoTokenizer.from_pretrained(*__A , **__A ) @add_start_docstrings(AutoModel.__doc__ ) def _UpperCamelCase ( *__A , **__A ) -> Dict: '''simple docstring''' return AutoModel.from_pretrained(*__A , **__A ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def _UpperCamelCase ( *__A , **__A ) -> List[Any]: '''simple docstring''' return AutoModelForCausalLM.from_pretrained(*__A , **__A ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def _UpperCamelCase ( *__A , **__A ) -> str: '''simple docstring''' return AutoModelForMaskedLM.from_pretrained(*__A , **__A ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def _UpperCamelCase ( *__A , **__A ) -> Tuple: '''simple docstring''' return AutoModelForSequenceClassification.from_pretrained(*__A , **__A ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def _UpperCamelCase ( *__A , **__A ) -> Dict: '''simple docstring''' return AutoModelForQuestionAnswering.from_pretrained(*__A , **__A )
80
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A , __A , __A ) -> dict[str, float]: '''simple docstring''' if (voltage, current, resistance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if resistance < 0: raise ValueError("Resistance cannot be negative" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
80
1
'''simple docstring''' from math import pi, sqrt def _UpperCamelCase ( __A ) -> float: '''simple docstring''' if num <= 0: raise ValueError("math domain error" ) if num > 171.5: raise OverflowError("math range error" ) elif num - int(__A ) not in (0, 0.5): raise NotImplementedError("num must be an integer or a half-integer" ) elif num == 0.5: return sqrt(__A ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def _UpperCamelCase ( ) -> None: '''simple docstring''' assert gamma(0.5 ) == sqrt(__A ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() a__ : Any = 1.0 while num: a__ : List[str] = float(input('Gamma of: ')) print(F"""gamma({num}) = {gamma(num)}""") print('\nEnter 0 to exit...')
80
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Union[str, Any] = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys a__ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
80
1
'''simple docstring''' import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase_ ( unittest.TestCase ): def __init__( self , a , a=3 , a=32 , a=3 , a=10 , a=[10, 20, 30, 40] , a=[1, 1, 2, 1] , a=True , a=True , a="relu" , a=3 , a=None , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = image_size UpperCamelCase__ = num_channels UpperCamelCase__ = embeddings_size UpperCamelCase__ = hidden_sizes UpperCamelCase__ = depths UpperCamelCase__ = is_training UpperCamelCase__ = use_labels UpperCamelCase__ = hidden_act UpperCamelCase__ = num_labels UpperCamelCase__ = scope UpperCamelCase__ = len(a ) def __a ( self ): UpperCamelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ = self.get_config() return config, pixel_values def __a ( self ): return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def __a ( self , a , a ): UpperCamelCase__ = FlaxRegNetModel(config=a ) UpperCamelCase__ = model(a ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __a ( self , a , a ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = FlaxRegNetForImageClassification(config=a ) UpperCamelCase__ = model(a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __a ( self ): UpperCamelCase__ = self.prepare_config_and_inputs() UpperCamelCase__ , UpperCamelCase__ = config_and_inputs UpperCamelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_flax class lowercase_ ( a__ , unittest.TestCase ): __UpperCAmelCase = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def __a ( self ): UpperCamelCase__ = FlaxRegNetModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=a , has_text_modality=a ) def __a ( self ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __a ( self ): return def __a ( self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def __a ( self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a ) @unittest.skip(reason="RegNet does not use inputs_embeds" ) def __a ( self ): pass @unittest.skip(reason="RegNet does not support input and output embeddings" ) def __a ( self ): pass def __a ( self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = model_class(a ) UpperCamelCase__ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ = [*signature.parameters.keys()] UpperCamelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , a ) def __a ( self ): def check_hidden_states_output(a , a , a ): UpperCamelCase__ = model_class(a ) UpperCamelCase__ = model(**self._prepare_for_class(a , a ) ) UpperCamelCase__ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCamelCase__ = self.model_tester.num_stages self.assertEqual(len(a ) , expected_num_stages + 1 ) UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = True check_hidden_states_output(a , a , a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase__ = True check_hidden_states_output(a , a , a ) def __a ( self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase__ = self._prepare_for_class(a , a ) UpperCamelCase__ = model_class(a ) @jax.jit def model_jitted(a , **a ): return model(pixel_values=a , **a ) with self.subTest("JIT Enabled" ): UpperCamelCase__ = model_jitted(**a ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): UpperCamelCase__ = model_jitted(**a ).to_tuple() self.assertEqual(len(a ) , len(a ) ) for jitted_output, output in zip(a , a ): self.assertEqual(jitted_output.shape , output.shape ) def _UpperCamelCase ( ) -> Any: '''simple docstring''' UpperCamelCase__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_flax class lowercase_ ( unittest.TestCase ): @cached_property def __a ( self ): return AutoImageProcessor.from_pretrained("facebook/regnet-y-040" ) if is_vision_available() else None @slow def __a ( self ): UpperCamelCase__ = FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040" ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=a , return_tensors="np" ) UpperCamelCase__ = model(**a ) # verify the logits UpperCamelCase__ = (1, 10_00) self.assertEqual(outputs.logits.shape , a ) UpperCamelCase__ = jnp.array([-0.4180, -1.5051, -3.4836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , a , atol=1e-4 ) )
80
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if len(__A ) != 2 or len(a[0] ) != 2 or len(__A ) != 2 or len(b[0] ) != 2: raise Exception("Matrices are not 2x2" ) UpperCamelCase__ = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _UpperCamelCase ( __A , __A ) -> str: '''simple docstring''' return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A ) -> tuple[list, list, list, list]: '''simple docstring''' if len(__A ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception("Odd matrices are not supported!" ) UpperCamelCase__ = len(__A ) UpperCamelCase__ = matrix_length // 2 UpperCamelCase__ = [[a[i][j] for j in range(__A , __A )] for i in range(__A )] UpperCamelCase__ = [ [a[i][j] for j in range(__A , __A )] for i in range(__A , __A ) ] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A )] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A , __A )] return top_left, top_right, bot_left, bot_right def _UpperCamelCase ( __A ) -> tuple[int, int]: '''simple docstring''' return len(__A ), len(matrix[0] ) def _UpperCamelCase ( __A ) -> None: '''simple docstring''' print("\n".join(str(__A ) for line in matrix ) ) def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A ) == (2, 2): return default_matrix_multiplication(__A , __A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = matrix_addition(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_subtraction(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) # construct the new matrix from our 4 quadrants UpperCamelCase__ = [] for i in range(len(__A ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(__A ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A )[1] != matrix_dimensions(__A )[0]: UpperCamelCase__ = ( "Unable to multiply these matrices, please check the dimensions.\n" F'''Matrix A: {matrixa}\n''' F'''Matrix B: {matrixa}''' ) raise Exception(__A ) UpperCamelCase__ = matrix_dimensions(__A ) UpperCamelCase__ = matrix_dimensions(__A ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] UpperCamelCase__ = max(*__A , *__A ) UpperCamelCase__ = int(math.pow(2 , math.ceil(math.loga(__A ) ) ) ) UpperCamelCase__ = matrixa UpperCamelCase__ = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) UpperCamelCase__ = actual_strassen(__A , __A ) # Removing the additional zeros for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a__ : int = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a__ : str = [[0, 2, 1, 1], [1_6, 2, 3, 3], [2, 2, 7, 7], [1_3, 1_1, 2_2, 4]] print(strassen(matrixa, matrixa))
80
1
'''simple docstring''' from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar a__ : List[str] = TypeVar('T') class lowercase_ ( Generic[T] ): __UpperCAmelCase = 42 # Cache store of keys __UpperCAmelCase = 42 # References of the keys in cache __UpperCAmelCase = 10 # Maximum capacity of cache def __init__( self , a ): UpperCamelCase__ = deque() UpperCamelCase__ = set() if not n: UpperCamelCase__ = sys.maxsize elif n < 0: raise ValueError("n should be an integer greater than 0." ) else: UpperCamelCase__ = n def __a ( self , a ): if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: UpperCamelCase__ = self.dq_store.pop() self.key_reference.remove(a ) else: self.dq_store.remove(a ) self.dq_store.appendleft(a ) self.key_reference.add(a ) def __a ( self ): for k in self.dq_store: print(a ) def __repr__( self ): return f'''LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}''' if __name__ == "__main__": import doctest doctest.testmod() a__ : LRUCache[str | int] = LRUCache(4) lru_cache.refer('A') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('A') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
80
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging a__ : List[str] = logging.get_logger(__name__) if is_vision_available(): import PIL class lowercase_ ( a__ ): __UpperCAmelCase = ['pixel_values'] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = None , a = True , a = 1 / 2_55 , a = True , a = None , a = None , a = True , **a , ): super().__init__(**a ) UpperCamelCase__ = size if size is not None else {"shortest_edge": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a ) UpperCamelCase__ = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a , param_name="crop_size" ) UpperCamelCase__ = do_resize UpperCamelCase__ = size UpperCamelCase__ = resample UpperCamelCase__ = do_center_crop UpperCamelCase__ = crop_size UpperCamelCase__ = do_rescale UpperCamelCase__ = rescale_factor UpperCamelCase__ = do_normalize UpperCamelCase__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN UpperCamelCase__ = image_std if image_std is not None else OPENAI_CLIP_STD UpperCamelCase__ = do_convert_rgb def __a ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ): UpperCamelCase__ = get_size_dict(a , default_to_square=a ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) UpperCamelCase__ = get_resize_output_image_size(a , size=size["shortest_edge"] , default_to_square=a ) return resize(a , size=a , resample=a , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): UpperCamelCase__ = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(a , size=(size["height"], size["width"]) , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): return rescale(a , scale=a , data_format=a , **a ) def __a ( self , a , a , a , a = None , **a , ): return normalize(a , mean=a , std=a , data_format=a , **a ) def __a ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ): UpperCamelCase__ = do_resize if do_resize is not None else self.do_resize UpperCamelCase__ = size if size is not None else self.size UpperCamelCase__ = get_size_dict(a , param_name="size" , default_to_square=a ) UpperCamelCase__ = resample if resample is not None else self.resample UpperCamelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase__ = crop_size if crop_size is not None else self.crop_size UpperCamelCase__ = get_size_dict(a , param_name="crop_size" , default_to_square=a ) UpperCamelCase__ = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase__ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase__ = image_mean if image_mean is not None else self.image_mean UpperCamelCase__ = image_std if image_std is not None else self.image_std UpperCamelCase__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase__ = make_list_of_images(a ) if not valid_images(a ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase__ = [convert_to_rgb(a ) for image in images] # All transformations expect numpy arrays. UpperCamelCase__ = [to_numpy_array(a ) for image in images] if do_resize: UpperCamelCase__ = [self.resize(image=a , size=a , resample=a ) for image in images] if do_center_crop: UpperCamelCase__ = [self.center_crop(image=a , size=a ) for image in images] if do_rescale: UpperCamelCase__ = [self.rescale(image=a , scale=a ) for image in images] if do_normalize: UpperCamelCase__ = [self.normalize(image=a , mean=a , std=a ) for image in images] UpperCamelCase__ = [to_channel_dimension_format(a , a ) for image in images] UpperCamelCase__ = {"pixel_values": images} return BatchFeature(data=a , tensor_type=a )
80
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. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu a__ : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def _UpperCamelCase ( __A , __A=None , __A=None , __A=None ) -> int: '''simple docstring''' UpperCamelCase__ = True while ask_again: UpperCamelCase__ = input(__A ) try: if default is not None and len(__A ) == 0: return default return convert_value(__A ) if convert_value is not None else result except Exception: if error_message is not None: print(__A ) def _UpperCamelCase ( __A , __A=[] , __A=None , __A=0 ) -> Any: '''simple docstring''' UpperCamelCase__ = BulletMenu(__A , __A ) UpperCamelCase__ = menu.run(default_choice=__A ) return convert_value(__A ) if convert_value is not None else result def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value] ) def _UpperCamelCase ( __A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = int(__A ) return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def _UpperCamelCase ( __A ) -> str: '''simple docstring''' UpperCamelCase__ = int(__A ) return PrecisionType(["no", "fp16", "bf16", "fp8"][value] ) def _UpperCamelCase ( __A ) -> Any: '''simple docstring''' UpperCamelCase__ = int(__A ) return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' return {"yes": True, "no": False}[value.lower()] class lowercase_ ( argparse.RawDescriptionHelpFormatter ): def __a ( self , a , a , a , a ): UpperCamelCase__ = super()._format_usage(a , a , a , a ) UpperCamelCase__ = usage.replace("<command> [<args>] " , "" ) return usage
80
'''simple docstring''' import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase_ ( a__ , unittest.TestCase ): __UpperCAmelCase = CLIPTokenizer __UpperCAmelCase = CLIPTokenizerFast __UpperCAmelCase = True __UpperCAmelCase = {} __UpperCAmelCase = False def __a ( self ): super().setUp() # fmt: off UpperCamelCase__ = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on UpperCamelCase__ = dict(zip(a , range(len(a ) ) ) ) UpperCamelCase__ = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] UpperCamelCase__ = {"unk_token": "<unk>"} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(a ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(a ) ) def __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def __a ( self , a ): UpperCamelCase__ = "lower newer" UpperCamelCase__ = "lower newer" return input_text, output_text def __a ( self ): UpperCamelCase__ = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = "lower newer" UpperCamelCase__ = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] UpperCamelCase__ = tokenizer.tokenize(a ) self.assertListEqual(a , a ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def __a ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = self.tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways UpperCamelCase__ = "xa\u0303y" + " " + "x\xe3y" UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type UpperCamelCase__ = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type UpperCamelCase__ = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def __a ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = "hello" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = f'''{text_of_1_token} {text_of_1_token}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) UpperCamelCase__ = f''' {text}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def __a ( self ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def __a ( self ): super().test_tokenization_python_rust_equals() def __a ( self ): # CLIP always lower cases letters pass
80
1
'''simple docstring''' def _UpperCamelCase ( __A , __A ) -> int: '''simple docstring''' return x if y == 0 else greatest_common_divisor(__A , x % y ) def _UpperCamelCase ( __A , __A ) -> int: '''simple docstring''' return (x * y) // greatest_common_divisor(__A , __A ) def _UpperCamelCase ( __A = 20 ) -> int: '''simple docstring''' UpperCamelCase__ = 1 for i in range(1 , n + 1 ): UpperCamelCase__ = lcm(__A , __A ) return g if __name__ == "__main__": print(F"""{solution() = }""")
80
'''simple docstring''' import argparse import collections import json import os import re import string import sys import numpy as np a__ : Optional[int] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a__ : int = None def _UpperCamelCase ( ) -> Dict: '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0." ) parser.add_argument("data_file" , metavar="data.json" , help="Input data JSON file." ) parser.add_argument("pred_file" , metavar="pred.json" , help="Model predictions." ) parser.add_argument( "--out-file" , "-o" , metavar="eval.json" , help="Write accuracy metrics to file (default is stdout)." ) parser.add_argument( "--na-prob-file" , "-n" , metavar="na_prob.json" , help="Model estimates of probability of no answer." ) parser.add_argument( "--na-prob-thresh" , "-t" , type=__A , default=1.0 , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)." , ) parser.add_argument( "--out-image-dir" , "-p" , metavar="out_images" , default=__A , help="Save precision-recall curves to directory." ) parser.add_argument("--verbose" , "-v" , action="store_true" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = bool(qa["answers"]["text"] ) return qid_to_has_ans def _UpperCamelCase ( __A ) -> Optional[Any]: '''simple docstring''' def remove_articles(__A ): return ARTICLES_REGEX.sub(" " , __A ) def white_space_fix(__A ): return " ".join(text.split() ) def remove_punc(__A ): UpperCamelCase__ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__A ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__A ) ) ) ) def _UpperCamelCase ( __A ) -> int: '''simple docstring''' if not s: return [] return normalize_answer(__A ).split() def _UpperCamelCase ( __A , __A ) -> List[Any]: '''simple docstring''' return int(normalize_answer(__A ) == normalize_answer(__A ) ) def _UpperCamelCase ( __A , __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = collections.Counter(__A ) & collections.Counter(__A ) UpperCamelCase__ = sum(common.values() ) if len(__A ) == 0 or len(__A ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = (2 * precision * recall) / (precision + recall) return fa def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = qa["id"] UpperCamelCase__ = [t for t in qa["answers"]["text"] if normalize_answer(__A )] if not gold_answers: # For unanswerable questions, only correct answer is empty string UpperCamelCase__ = [""] if qid not in preds: print(F'''Missing prediction for {qid}''' ) continue UpperCamelCase__ = preds[qid] # Take max over all gold answers UpperCamelCase__ = max(compute_exact(__A , __A ) for a in gold_answers ) UpperCamelCase__ = max(compute_fa(__A , __A ) for a in gold_answers ) return exact_scores, fa_scores def _UpperCamelCase ( __A , __A , __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} for qid, s in scores.items(): UpperCamelCase__ = na_probs[qid] > na_prob_thresh if pred_na: UpperCamelCase__ = float(not qid_to_has_ans[qid] ) else: UpperCamelCase__ = s return new_scores def _UpperCamelCase ( __A , __A , __A=None ) -> List[Any]: '''simple docstring''' if not qid_list: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores.values() ) / total), ("f1", 100.0 * sum(fa_scores.values() ) / total), ("total", total), ] ) else: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("f1", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("total", total), ] ) def _UpperCamelCase ( __A , __A , __A ) -> Optional[int]: '''simple docstring''' for k in new_eval: UpperCamelCase__ = new_eval[k] def _UpperCamelCase ( __A , __A , __A , __A ) -> Optional[int]: '''simple docstring''' plt.step(__A , __A , color="b" , alpha=0.2 , where="post" ) plt.fill_between(__A , __A , step="post" , alpha=0.2 , color="b" ) plt.xlabel("Recall" ) plt.ylabel("Precision" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__A ) plt.savefig(__A ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A , __A=None , __A=None ) -> Any: '''simple docstring''' UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) UpperCamelCase__ = 0.0 UpperCamelCase__ = 1.0 UpperCamelCase__ = 0.0 UpperCamelCase__ = [1.0] UpperCamelCase__ = [0.0] UpperCamelCase__ = 0.0 for i, qid in enumerate(__A ): if qid_to_has_ans[qid]: true_pos += scores[qid] UpperCamelCase__ = true_pos / float(i + 1 ) UpperCamelCase__ = true_pos / float(__A ) if i == len(__A ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__A ) recalls.append(__A ) if out_image: plot_pr_curve(__A , __A , __A , __A ) return {"ap": 100.0 * avg_prec} def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if out_image_dir and not os.path.exists(__A ): os.makedirs(__A ) UpperCamelCase__ = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_exact.png" ) , title="Precision-Recall curve for Exact Match score" , ) UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_f1.png" ) , title="Precision-Recall curve for F1 score" , ) UpperCamelCase__ = {k: float(__A ) for k, v in qid_to_has_ans.items()} UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_oracle.png" ) , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)" , ) merge_eval(__A , __A , "pr_exact" ) merge_eval(__A , __A , "pr_f1" ) merge_eval(__A , __A , "pr_oracle" ) def _UpperCamelCase ( __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if not qid_list: return UpperCamelCase__ = [na_probs[k] for k in qid_list] UpperCamelCase__ = np.ones_like(__A ) / float(len(__A ) ) plt.hist(__A , weights=__A , bins=20 , range=(0.0, 1.0) ) plt.xlabel("Model probability of no-answer" ) plt.ylabel("Proportion of dataset" ) plt.title(F'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__A , F'''na_prob_hist_{name}.png''' ) ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A ) -> Tuple: '''simple docstring''' UpperCamelCase__ = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) UpperCamelCase__ = num_no_ans UpperCamelCase__ = cur_score UpperCamelCase__ = 0.0 UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) for i, qid in enumerate(__A ): if qid not in scores: continue if qid_to_has_ans[qid]: UpperCamelCase__ = scores[qid] else: if preds[qid]: UpperCamelCase__ = -1 else: UpperCamelCase__ = 0 cur_score += diff if cur_score > best_score: UpperCamelCase__ = cur_score UpperCamelCase__ = na_probs[qid] return 100.0 * best_score / len(__A ), best_thresh def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> Dict: '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ = best_exact UpperCamelCase__ = exact_thresh UpperCamelCase__ = best_fa UpperCamelCase__ = fa_thresh def _UpperCamelCase ( ) -> Any: '''simple docstring''' with open(OPTS.data_file ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = dataset_json["data"] with open(OPTS.pred_file ) as f: UpperCamelCase__ = json.load(__A ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: UpperCamelCase__ = json.load(__A ) else: UpperCamelCase__ = {k: 0.0 for k in preds} UpperCamelCase__ = make_qid_to_has_ans(__A ) # maps qid to True/False UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if v] UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if not v] UpperCamelCase__ , UpperCamelCase__ = get_raw_scores(__A , __A ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = make_eval_dict(__A , __A ) if has_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "HasAns" ) if no_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "NoAns" ) if OPTS.na_prob_file: find_all_best_thresh(__A , __A , __A , __A , __A , __A ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__A , __A , __A , __A , __A , OPTS.out_image_dir ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "hasAns" ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "noAns" ) if OPTS.out_file: with open(OPTS.out_file , "w" ) as f: json.dump(__A , __A ) else: print(json.dumps(__A , indent=2 ) ) if __name__ == "__main__": a__ : Optional[int] = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
80
1
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import LayoutLMConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.layoutlm.modeling_tf_layoutlm import ( TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMForMaskedLM, TFLayoutLMForQuestionAnswering, TFLayoutLMForSequenceClassification, TFLayoutLMForTokenClassification, TFLayoutLMModel, ) class lowercase_ : def __init__( self , a , a=13 , a=7 , a=True , a=True , a=True , a=True , a=99 , a=32 , a=2 , a=4 , a=37 , a="gelu" , a=0.1 , a=0.1 , a=5_12 , a=16 , a=2 , a=0.02 , a=3 , a=4 , a=None , a=10_00 , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = scope UpperCamelCase__ = range_bbox def __a ( self ): UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) # convert bbox to numpy since TF does not support item assignment UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ).numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCamelCase__ = bbox[i, j, 3] UpperCamelCase__ = bbox[i, j, 1] UpperCamelCase__ = t if bbox[i, j, 2] < bbox[i, j, 0]: UpperCamelCase__ = bbox[i, j, 2] UpperCamelCase__ = bbox[i, j, 0] UpperCamelCase__ = t UpperCamelCase__ = tf.convert_to_tensor(a ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = LayoutLMConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __a ( self , a , a , a , a , a , a , a , a ): UpperCamelCase__ = TFLayoutLMModel(config=a ) UpperCamelCase__ = model(a , a , attention_mask=a , token_type_ids=a ) UpperCamelCase__ = model(a , a , token_type_ids=a ) UpperCamelCase__ = model(a , a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __a ( self , a , a , a , a , a , a , a , a ): UpperCamelCase__ = TFLayoutLMForMaskedLM(config=a ) UpperCamelCase__ = model(a , a , attention_mask=a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __a ( self , a , a , a , a , a , a , a , a ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFLayoutLMForSequenceClassification(config=a ) UpperCamelCase__ = model(a , a , attention_mask=a , token_type_ids=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __a ( self , a , a , a , a , a , a , a , a ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFLayoutLMForTokenClassification(config=a ) UpperCamelCase__ = model(a , a , attention_mask=a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __a ( self , a , a , a , a , a , a , a , a ): UpperCamelCase__ = TFLayoutLMForQuestionAnswering(config=a ) UpperCamelCase__ = model(a , a , attention_mask=a , token_type_ids=a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __a ( self ): UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = { "input_ids": input_ids, "bbox": bbox, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_tf class lowercase_ ( a__ , a__ , unittest.TestCase ): __UpperCAmelCase = ( ( TFLayoutLMModel, TFLayoutLMForMaskedLM, TFLayoutLMForTokenClassification, TFLayoutLMForSequenceClassification, TFLayoutLMForQuestionAnswering, ) if is_tf_available() else () ) __UpperCAmelCase = ( { 'feature-extraction': TFLayoutLMModel, 'fill-mask': TFLayoutLMForMaskedLM, 'text-classification': TFLayoutLMForSequenceClassification, 'token-classification': TFLayoutLMForTokenClassification, 'zero-shot': TFLayoutLMForSequenceClassification, } if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = True __UpperCAmelCase = 10 def __a ( self ): UpperCamelCase__ = TFLayoutLMModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=a , hidden_size=37 ) def __a ( self ): self.config_tester.run_common_tests() def __a ( self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def __a ( self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*a ) def __a ( self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a ) def __a ( self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a ) def __a ( self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a ) @slow def __a ( self ): for model_name in TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = TFLayoutLMModel.from_pretrained(a ) self.assertIsNotNone(a ) @unittest.skip("Onnx compliancy broke with TF 2.10" ) def __a ( self ): pass def _UpperCamelCase ( ) -> int: '''simple docstring''' UpperCamelCase__ = tf.convert_to_tensor([[101,1019,1014,1016,1037,12849,4747,1004,14246,2278,5439,4524,5002,2930,2193,2930,4341,3208,1005,1055,2171,2848,11300,3531,102],[101,4070,4034,7020,1024,3058,1015,1013,2861,1013,6070,19274,2772,6205,27814,16147,16147,4343,2047,10283,10969,14389,1012,2338,102]] ) # noqa: E231 UpperCamelCase__ = tf.convert_to_tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],] ) # noqa: E231 UpperCamelCase__ = tf.convert_to_tensor([[[0,0,0,0],[423,237,440,251],[427,272,441,287],[419,115,437,129],[961,885,992,912],[256,38,330,58],[256,38,330,58],[336,42,353,57],[360,39,401,56],[360,39,401,56],[411,39,471,59],[479,41,528,59],[533,39,630,60],[67,113,134,131],[141,115,209,132],[68,149,133,166],[141,149,187,164],[195,148,287,165],[195,148,287,165],[195,148,287,165],[295,148,349,165],[441,149,492,166],[497,149,546,164],[64,201,125,218],[1000,1000,1000,1000]],[[0,0,0,0],[662,150,754,166],[665,199,742,211],[519,213,554,228],[519,213,554,228],[134,433,187,454],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[314,469,376,482],[504,684,582,706],[941,825,973,900],[941,825,973,900],[941,825,973,900],[941,825,973,900],[610,749,652,765],[130,659,168,672],[176,657,237,672],[238,657,312,672],[443,653,628,672],[443,653,628,672],[716,301,825,317],[1000,1000,1000,1000]]] ) # noqa: E231 UpperCamelCase__ = tf.convert_to_tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]] ) # noqa: E231 # these are sequence labels (i.e. at the token level) UpperCamelCase__ = tf.convert_to_tensor([[-100,10,10,10,9,1,-100,7,7,-100,7,7,4,2,5,2,8,8,-100,-100,5,0,3,2,-100],[-100,12,12,12,-100,12,10,-100,-100,-100,-100,10,12,9,-100,-100,-100,10,10,10,9,12,-100,10,-100]] ) # noqa: E231 # fmt: on return input_ids, attention_mask, bbox, token_type_ids, labels @require_tf class lowercase_ ( unittest.TestCase ): @slow def __a ( self ): UpperCamelCase__ = TFLayoutLMModel.from_pretrained("microsoft/layoutlm-base-uncased" ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = prepare_layoutlm_batch_inputs() # forward pass UpperCamelCase__ = model(input_ids=a , bbox=a , attention_mask=a , token_type_ids=a ) # test the sequence output on [0, :3, :3] UpperCamelCase__ = tf.convert_to_tensor( [[0.1785, -0.1947, -0.0425], [-0.3254, -0.2807, 0.2553], [-0.5391, -0.3322, 0.3364]] , ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , a , atol=1e-3 ) ) # test the pooled output on [1, :3] UpperCamelCase__ = tf.convert_to_tensor([-0.6580, -0.0214, 0.8552] ) self.assertTrue(np.allclose(outputs.pooler_output[1, :3] , a , atol=1e-3 ) ) @slow def __a ( self ): # initialize model with randomly initialized sequence classification head UpperCamelCase__ = TFLayoutLMForSequenceClassification.from_pretrained("microsoft/layoutlm-base-uncased" , num_labels=2 ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = prepare_layoutlm_batch_inputs() # forward pass UpperCamelCase__ = model( input_ids=a , bbox=a , attention_mask=a , token_type_ids=a , labels=tf.convert_to_tensor([1, 1] ) , ) # test whether we get a loss as a scalar UpperCamelCase__ = outputs.loss UpperCamelCase__ = (2,) self.assertEqual(loss.shape , a ) # test the shape of the logits UpperCamelCase__ = outputs.logits UpperCamelCase__ = (2, 2) self.assertEqual(logits.shape , a ) @slow def __a ( self ): # initialize model with randomly initialized token classification head UpperCamelCase__ = TFLayoutLMForTokenClassification.from_pretrained("microsoft/layoutlm-base-uncased" , num_labels=13 ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = prepare_layoutlm_batch_inputs() # forward pass UpperCamelCase__ = model( input_ids=a , bbox=a , attention_mask=a , token_type_ids=a , labels=a ) # test the shape of the logits UpperCamelCase__ = outputs.logits UpperCamelCase__ = tf.convert_to_tensor((2, 25, 13) ) self.assertEqual(logits.shape , a ) @slow def __a ( self ): # initialize model with randomly initialized token classification head UpperCamelCase__ = TFLayoutLMForQuestionAnswering.from_pretrained("microsoft/layoutlm-base-uncased" ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = prepare_layoutlm_batch_inputs() # forward pass UpperCamelCase__ = model(input_ids=a , bbox=a , attention_mask=a , token_type_ids=a ) # test the shape of the logits UpperCamelCase__ = tf.convert_to_tensor((2, 25) ) self.assertEqual(outputs.start_logits.shape , a ) self.assertEqual(outputs.end_logits.shape , a )
80
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType a__ : Optional[List[str]] = None a__ : Dict = '<' if sys.byteorder == 'little' else '>' # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image a__ : Any = [ np.dtype('|b1'), np.dtype('|u1'), np.dtype('<u2'), np.dtype('>u2'), np.dtype('<i2'), np.dtype('>i2'), np.dtype('<u4'), np.dtype('>u4'), np.dtype('<i4'), np.dtype('>i4'), np.dtype('<f4'), np.dtype('>f4'), np.dtype('<f8'), np.dtype('>f8'), ] @dataclass class lowercase_ : __UpperCAmelCase = True __UpperCAmelCase = None # Automatically constructed __UpperCAmelCase = "PIL.Image.Image" __UpperCAmelCase = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) __UpperCAmelCase = field(default='Image' , init=a__ , repr=a__ ) def __call__( self ): return self.pa_type def __a ( self , a ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if isinstance(a , a ): UpperCamelCase__ = np.array(a ) if isinstance(a , a ): return {"path": value, "bytes": None} elif isinstance(a , a ): return {"path": None, "bytes": value} elif isinstance(a , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(a ) elif isinstance(a , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(a ) elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def __a ( self , a , a=None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Image(decode=True) instead." ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support decoding images, please install 'Pillow'." ) if token_per_repo_id is None: UpperCamelCase__ = {} UpperCamelCase__ , UpperCamelCase__ = value["path"], value["bytes"] if bytes_ is None: if path is None: raise ValueError(f'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) else: if is_local_path(a ): UpperCamelCase__ = PIL.Image.open(a ) else: UpperCamelCase__ = path.split("::" )[-1] try: UpperCamelCase__ = string_to_dict(a , config.HUB_DATASETS_URL )["repo_id"] UpperCamelCase__ = token_per_repo_id.get(a ) except ValueError: UpperCamelCase__ = None with xopen(a , "rb" , use_auth_token=a ) as f: UpperCamelCase__ = BytesIO(f.read() ) UpperCamelCase__ = PIL.Image.open(bytes_ ) else: UpperCamelCase__ = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __a ( self ): from .features import Value return ( self if self.decode else { "bytes": Value("binary" ), "path": Value("string" ), } ) def __a ( self , a ): if pa.types.is_string(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCamelCase__ = storage.field("bytes" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCamelCase__ = storage.field("path" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): UpperCamelCase__ = pa.array( [encode_np_array(np.array(a ) )["bytes"] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays( [bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def __a ( self , a ): @no_op_if_value_is_null def path_to_bytes(a ): with xopen(a , "rb" ) as f: UpperCamelCase__ = f.read() return bytes_ UpperCamelCase__ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCamelCase__ = pa.array( [os.path.basename(a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def _UpperCamelCase ( ) -> List[str]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() UpperCamelCase__ = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def _UpperCamelCase ( __A ) -> bytes: '''simple docstring''' UpperCamelCase__ = BytesIO() if image.format in list_image_compression_formats(): UpperCamelCase__ = image.format else: UpperCamelCase__ = "PNG" if image.mode in ["1", "L", "LA", "RGB", "RGBA"] else "TIFF" image.save(__A , format=__A ) return buffer.getvalue() def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if hasattr(__A , "filename" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) UpperCamelCase__ = array.dtype UpperCamelCase__ = dtype.byteorder if dtype.byteorder != "=" else _NATIVE_BYTEORDER UpperCamelCase__ = dtype.kind UpperCamelCase__ = dtype.itemsize UpperCamelCase__ = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: UpperCamelCase__ = np.dtype("|u1" ) if dtype_kind not in ["u", "i"]: raise TypeError( F'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.''' ) if dtype is not dest_dtype: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: UpperCamelCase__ = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: UpperCamelCase__ = dtype_byteorder + dtype_kind + str(__A ) UpperCamelCase__ = np.dtype(__A ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}''' ) UpperCamelCase__ = PIL.Image.fromarray(array.astype(__A ) ) return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> List[dict]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if objs: UpperCamelCase__ , UpperCamelCase__ = first_non_null_value(__A ) if isinstance(__A , __A ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__A , np.ndarray ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] elif isinstance(__A , PIL.Image.Image ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] else: return objs else: return objs
80
1
'''simple docstring''' import math import sys def _UpperCamelCase ( __A ) -> str: '''simple docstring''' UpperCamelCase__ = "" try: with open(__A , "rb" ) as binary_file: UpperCamelCase__ = binary_file.read() for dat in data: UpperCamelCase__ = F'''{dat:08b}''' result += curr_byte return result except OSError: print("File not accessible" ) sys.exit() def _UpperCamelCase ( __A ) -> str: '''simple docstring''' UpperCamelCase__ = {"0": "0", "1": "1"} UpperCamelCase__ , UpperCamelCase__ = "", "" UpperCamelCase__ = len(__A ) for i in range(len(__A ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue UpperCamelCase__ = lexicon[curr_string] result += last_match_id UpperCamelCase__ = last_match_id + "0" if math.loga(__A ).is_integer(): UpperCamelCase__ = {} for curr_key in list(__A ): UpperCamelCase__ = lexicon.pop(__A ) UpperCamelCase__ = new_lex UpperCamelCase__ = last_match_id + "1" index += 1 UpperCamelCase__ = "" return result def _UpperCamelCase ( __A , __A ) -> None: '''simple docstring''' UpperCamelCase__ = 8 try: with open(__A , "wb" ) as opened_file: UpperCamelCase__ = [ to_write[i : i + byte_length] for i in range(0 , len(__A ) , __A ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("10000000" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(__A , 2 ).to_bytes(1 , byteorder="big" ) ) except OSError: print("File not accessible" ) sys.exit() def _UpperCamelCase ( __A ) -> str: '''simple docstring''' UpperCamelCase__ = 0 for letter in data_bits: if letter == "1": break counter += 1 UpperCamelCase__ = data_bits[counter:] UpperCamelCase__ = data_bits[counter + 1 :] return data_bits def _UpperCamelCase ( __A , __A ) -> None: '''simple docstring''' UpperCamelCase__ = read_file_binary(__A ) UpperCamelCase__ = remove_prefix(__A ) UpperCamelCase__ = decompress_data(__A ) write_file_binary(__A , __A ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
80
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> int: '''simple docstring''' if depth < 0: raise ValueError("Depth cannot be less than 0" ) if not scores: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) ) def _UpperCamelCase ( ) -> None: '''simple docstring''' UpperCamelCase__ = [90, 23, 6, 33, 21, 65, 123, 34423] UpperCamelCase__ = math.log(len(__A ) , 2 ) print(F'''Optimal value : {minimax(0 , 0 , __A , __A , __A )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
80
1
'''simple docstring''' a__ : List[Any] = { 'Pillow': 'Pillow<10.0.0', 'accelerate': 'accelerate>=0.20.3', 'av': 'av==9.2.0', 'beautifulsoup4': 'beautifulsoup4', 'black': 'black~=23.1', 'codecarbon': 'codecarbon==1.2.0', 'cookiecutter': 'cookiecutter==1.7.3', 'dataclasses': 'dataclasses', 'datasets': 'datasets!=2.5.0', 'decord': 'decord==0.6.0', 'deepspeed': 'deepspeed>=0.9.3', 'diffusers': 'diffusers', 'dill': 'dill<0.3.5', 'evaluate': 'evaluate>=0.2.0', 'fairscale': 'fairscale>0.3', 'faiss-cpu': 'faiss-cpu', 'fastapi': 'fastapi', 'filelock': 'filelock', 'flax': 'flax>=0.4.1,<=0.7.0', 'ftfy': 'ftfy', 'fugashi': 'fugashi>=1.0', 'GitPython': 'GitPython<3.1.19', 'hf-doc-builder': 'hf-doc-builder>=0.3.0', 'huggingface-hub': 'huggingface-hub>=0.14.1,<1.0', 'importlib_metadata': 'importlib_metadata', 'ipadic': 'ipadic>=1.0.0,<2.0', 'isort': 'isort>=5.5.4', 'jax': 'jax>=0.2.8,!=0.3.2,<=0.4.13', 'jaxlib': 'jaxlib>=0.1.65,<=0.4.13', 'jieba': 'jieba', 'kenlm': 'kenlm', 'keras-nlp': 'keras-nlp>=0.3.1', 'librosa': 'librosa', 'nltk': 'nltk', 'natten': 'natten>=0.14.6', 'numpy': 'numpy>=1.17', 'onnxconverter-common': 'onnxconverter-common', 'onnxruntime-tools': 'onnxruntime-tools>=1.4.2', 'onnxruntime': 'onnxruntime>=1.4.0', 'opencv-python': 'opencv-python', 'optuna': 'optuna', 'optax': 'optax>=0.0.8,<=0.1.4', 'packaging': 'packaging>=20.0', 'parameterized': 'parameterized', 'phonemizer': 'phonemizer', 'protobuf': 'protobuf', 'psutil': 'psutil', 'pyyaml': 'pyyaml>=5.1', 'pydantic': 'pydantic<2', 'pytest': 'pytest>=7.2.0', 'pytest-timeout': 'pytest-timeout', 'pytest-xdist': 'pytest-xdist', 'python': 'python>=3.8.0', 'ray[tune]': 'ray[tune]', 'regex': 'regex!=2019.12.17', 'requests': 'requests', 'rhoknp': 'rhoknp>=1.1.0,<1.3.1', 'rjieba': 'rjieba', 'rouge-score': 'rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1', 'ruff': 'ruff>=0.0.241,<=0.0.259', 'sacrebleu': 'sacrebleu>=1.4.12,<2.0.0', 'sacremoses': 'sacremoses', 'safetensors': 'safetensors>=0.3.1', 'sagemaker': 'sagemaker>=2.31.0', 'scikit-learn': 'scikit-learn', 'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92', 'sigopt': 'sigopt', 'starlette': 'starlette', 'sudachipy': 'sudachipy>=0.6.6', 'sudachidict_core': 'sudachidict_core>=20220729', 'tensorflow-cpu': 'tensorflow-cpu>=2.6,<2.14', 'tensorflow': 'tensorflow>=2.6,<2.14', 'tensorflow-text': 'tensorflow-text<2.14', 'tf2onnx': 'tf2onnx', 'timeout-decorator': 'timeout-decorator', 'timm': 'timm', 'tokenizers': 'tokenizers>=0.11.1,!=0.11.3,<0.14', 'torch': 'torch>=1.9,!=1.12.0', 'torchaudio': 'torchaudio', 'torchvision': 'torchvision', 'pyctcdecode': 'pyctcdecode>=0.4.0', 'tqdm': 'tqdm>=4.27', 'unidic': 'unidic>=1.0.2', 'unidic_lite': 'unidic_lite>=1.0.7', 'urllib3': 'urllib3<2.0.0', 'uvicorn': 'uvicorn', }
80
'''simple docstring''' def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def _UpperCamelCase ( __A = 100 ) -> int: '''simple docstring''' UpperCamelCase__ = 1 UpperCamelCase__ = 2 for i in range(2 , max_n + 1 ): UpperCamelCase__ = pre_numerator UpperCamelCase__ = 2 * i // 3 if i % 3 == 0 else 1 UpperCamelCase__ = cur_numerator UpperCamelCase__ = e_cont * pre_numerator + temp return sum_digits(__A ) if __name__ == "__main__": print(F"""{solution() = }""")
80
1
'''simple docstring''' import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class lowercase_ ( nn.Module ): __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0.0 __UpperCAmelCase = 1 __UpperCAmelCase = 1 __UpperCAmelCase = True __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = jnp.floataa def __a ( self ): UpperCamelCase__ = [] UpperCamelCase__ = [] for i in range(self.num_layers ): UpperCamelCase__ = self.in_channels if i == 0 else self.out_channels UpperCamelCase__ = FlaxResnetBlockaD( in_channels=a , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(a ) UpperCamelCase__ = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(a ) UpperCamelCase__ = resnets UpperCamelCase__ = attentions if self.add_downsample: UpperCamelCase__ = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , a , a , a , a=True ): UpperCamelCase__ = () for resnet, attn in zip(self.resnets , self.attentions ): UpperCamelCase__ = resnet(a , a , deterministic=a ) UpperCamelCase__ = attn(a , a , deterministic=a ) output_states += (hidden_states,) if self.add_downsample: UpperCamelCase__ = self.downsamplers_a(a ) output_states += (hidden_states,) return hidden_states, output_states class lowercase_ ( nn.Module ): __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0.0 __UpperCAmelCase = 1 __UpperCAmelCase = True __UpperCAmelCase = jnp.floataa def __a ( self ): UpperCamelCase__ = [] for i in range(self.num_layers ): UpperCamelCase__ = self.in_channels if i == 0 else self.out_channels UpperCamelCase__ = FlaxResnetBlockaD( in_channels=a , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(a ) UpperCamelCase__ = resnets if self.add_downsample: UpperCamelCase__ = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , a , a , a=True ): UpperCamelCase__ = () for resnet in self.resnets: UpperCamelCase__ = resnet(a , a , deterministic=a ) output_states += (hidden_states,) if self.add_downsample: UpperCamelCase__ = self.downsamplers_a(a ) output_states += (hidden_states,) return hidden_states, output_states class lowercase_ ( nn.Module ): __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0.0 __UpperCAmelCase = 1 __UpperCAmelCase = 1 __UpperCAmelCase = True __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = jnp.floataa def __a ( self ): UpperCamelCase__ = [] UpperCamelCase__ = [] for i in range(self.num_layers ): UpperCamelCase__ = self.in_channels if (i == self.num_layers - 1) else self.out_channels UpperCamelCase__ = self.prev_output_channel if i == 0 else self.out_channels UpperCamelCase__ = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(a ) UpperCamelCase__ = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(a ) UpperCamelCase__ = resnets UpperCamelCase__ = attentions if self.add_upsample: UpperCamelCase__ = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , a , a , a , a , a=True ): for resnet, attn in zip(self.resnets , self.attentions ): # pop res hidden states UpperCamelCase__ = res_hidden_states_tuple[-1] UpperCamelCase__ = res_hidden_states_tuple[:-1] UpperCamelCase__ = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) UpperCamelCase__ = resnet(a , a , deterministic=a ) UpperCamelCase__ = attn(a , a , deterministic=a ) if self.add_upsample: UpperCamelCase__ = self.upsamplers_a(a ) return hidden_states class lowercase_ ( nn.Module ): __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0.0 __UpperCAmelCase = 1 __UpperCAmelCase = True __UpperCAmelCase = jnp.floataa def __a ( self ): UpperCamelCase__ = [] for i in range(self.num_layers ): UpperCamelCase__ = self.in_channels if (i == self.num_layers - 1) else self.out_channels UpperCamelCase__ = self.prev_output_channel if i == 0 else self.out_channels UpperCamelCase__ = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(a ) UpperCamelCase__ = resnets if self.add_upsample: UpperCamelCase__ = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , a , a , a , a=True ): for resnet in self.resnets: # pop res hidden states UpperCamelCase__ = res_hidden_states_tuple[-1] UpperCamelCase__ = res_hidden_states_tuple[:-1] UpperCamelCase__ = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) UpperCamelCase__ = resnet(a , a , deterministic=a ) if self.add_upsample: UpperCamelCase__ = self.upsamplers_a(a ) return hidden_states class lowercase_ ( nn.Module ): __UpperCAmelCase = 42 __UpperCAmelCase = 0.0 __UpperCAmelCase = 1 __UpperCAmelCase = 1 __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = jnp.floataa def __a ( self ): # there is always at least one resnet UpperCamelCase__ = [ FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) ] UpperCamelCase__ = [] for _ in range(self.num_layers ): UpperCamelCase__ = FlaxTransformeraDModel( in_channels=self.in_channels , n_heads=self.num_attention_heads , d_head=self.in_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(a ) UpperCamelCase__ = FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(a ) UpperCamelCase__ = resnets UpperCamelCase__ = attentions def __call__( self , a , a , a , a=True ): UpperCamelCase__ = self.resnets[0](a , a ) for attn, resnet in zip(self.attentions , self.resnets[1:] ): UpperCamelCase__ = attn(a , a , deterministic=a ) UpperCamelCase__ = resnet(a , a , deterministic=a ) return hidden_states
80
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' with open(__A ) as metadata_file: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = LukeConfig(use_entity_aware_attention=__A , **metadata["model_config"] ) # Load in the weights from the checkpoint_path UpperCamelCase__ = torch.load(__A , map_location="cpu" )["module"] # Load the entity vocab file UpperCamelCase__ = load_original_entity_vocab(__A ) # add an entry for [MASK2] UpperCamelCase__ = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase__ = XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase__ = AddedToken("<ent>" , lstrip=__A , rstrip=__A ) UpperCamelCase__ = AddedToken("<ent2>" , lstrip=__A , rstrip=__A ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'''Saving tokenizer to {pytorch_dump_folder_path}''' ) tokenizer.save_pretrained(__A ) with open(os.path.join(__A , "tokenizer_config.json" ) , "r" ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = "MLukeTokenizer" with open(os.path.join(__A , "tokenizer_config.json" ) , "w" ) as f: json.dump(__A , __A ) with open(os.path.join(__A , MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(__A , __A ) UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) # Initialize the embeddings of the special tokens UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["@"] )[0] UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["#"] )[0] UpperCamelCase__ = state_dict["embeddings.word_embeddings.weight"] UpperCamelCase__ = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase__ = state_dict[bias_name] UpperCamelCase__ = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: UpperCamelCase__ = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase__ = state_dict["entity_embeddings.entity_embeddings.weight"] UpperCamelCase__ = entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase__ = state_dict["entity_predictions.bias"] UpperCamelCase__ = entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase__ = LukeForMaskedLM(config=__A ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) UpperCamelCase__ = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): UpperCamelCase__ = state_dict[key] else: UpperCamelCase__ = state_dict[key] UpperCamelCase__ , UpperCamelCase__ = model.load_state_dict(__A , strict=__A ) if set(__A ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(__A ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A , task="entity_classification" ) UpperCamelCase__ = "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." UpperCamelCase__ = (0, 9) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 33, 768) ) UpperCamelCase__ = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}''' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 1, 768) ) UpperCamelCase__ = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is''' F''' {expected_shape}''' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) UpperCamelCase__ = "Tokyo is the capital of <mask>." UpperCamelCase__ = (24, 30) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) UpperCamelCase__ = encoding["input_ids"][0].tolist() UpperCamelCase__ = input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) UpperCamelCase__ = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(__A ) UpperCamelCase__ = outputs.entity_logits[0][0].argmax().item() UpperCamelCase__ = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(__A ) ) model.save_pretrained(__A ) def _UpperCamelCase ( __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = ["[MASK]", "[PAD]", "[UNK]"] UpperCamelCase__ = [json.loads(__A ) for line in open(__A )] UpperCamelCase__ = {} for entry in data: UpperCamelCase__ = entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase__ = entity_id break UpperCamelCase__ = F'''{language}:{entity_name}''' UpperCamelCase__ = entity_id return new_mapping if __name__ == "__main__": a__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) a__ : Any = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
80
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. import argparse import os from accelerate.test_utils import execute_subprocess_async def _UpperCamelCase ( __A=None ) -> List[Any]: '''simple docstring''' if subparsers is not None: UpperCamelCase__ = subparsers.add_parser("test" ) else: UpperCamelCase__ = argparse.ArgumentParser("Accelerate test command" ) parser.add_argument( "--config_file" , default=__A , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=__A ) return parser def _UpperCamelCase ( __A ) -> Any: '''simple docstring''' UpperCamelCase__ = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["test_utils", "scripts", "test_script.py"] ) if args.config_file is None: UpperCamelCase__ = script_name else: UpperCamelCase__ = F'''--config_file={args.config_file} {script_name}''' UpperCamelCase__ = ["accelerate-launch"] + test_args.split() UpperCamelCase__ = execute_subprocess_async(__A , env=os.environ.copy() ) if result.returncode == 0: print("Test is a success! You are ready for your distributed training!" ) def _UpperCamelCase ( ) -> int: '''simple docstring''' UpperCamelCase__ = test_command_parser() UpperCamelCase__ = parser.parse_args() test_command(__A ) if __name__ == "__main__": main()
80
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Any = logging.get_logger(__name__) a__ : str = { 'SCUT-DLVCLab/lilt-roberta-en-base': ( 'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json' ), } class lowercase_ ( a__ ): __UpperCAmelCase = 'lilt' def __init__( self , a=3_05_22 , a=7_68 , a=12 , a=12 , a=30_72 , a="gelu" , a=0.1 , a=0.1 , a=5_12 , a=2 , a=0.02 , a=1e-12 , a=0 , a="absolute" , a=None , a=4 , a=10_24 , **a , ): super().__init__(pad_token_id=a , **a ) UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = position_embedding_type UpperCamelCase__ = classifier_dropout UpperCamelCase__ = channel_shrink_ratio UpperCamelCase__ = max_ad_position_embeddings
80
1
'''simple docstring''' import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoModelWithLMHead, AutoTokenizer, PretrainedConfig, PreTrainedTokenizer, ) from transformers.optimization import ( Adafactor, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.utils.versions import require_version a__ : List[Any] = logging.getLogger(__name__) require_version('pytorch_lightning>=1.0.4') a__ : Tuple = { 'base': AutoModel, 'sequence-classification': AutoModelForSequenceClassification, 'question-answering': AutoModelForQuestionAnswering, 'pretraining': AutoModelForPreTraining, 'token-classification': AutoModelForTokenClassification, 'language-modeling': AutoModelWithLMHead, 'summarization': AutoModelForSeqaSeqLM, 'translation': AutoModelForSeqaSeqLM, } # update this and the import above to support new schedulers from transformers.optimization a__ : str = { 'linear': get_linear_schedule_with_warmup, 'cosine': get_cosine_schedule_with_warmup, 'cosine_w_restarts': get_cosine_with_hard_restarts_schedule_with_warmup, 'polynomial': get_polynomial_decay_schedule_with_warmup, # '': get_constant_schedule, # not supported for now # '': get_constant_schedule_with_warmup, # not supported for now } a__ : Union[str, Any] = sorted(arg_to_scheduler.keys()) a__ : Optional[int] = '{' + ', '.join(arg_to_scheduler_choices) + '}' class lowercase_ ( pl.LightningModule ): def __init__( self , a , a=None , a="base" , a=None , a=None , a=None , **a , ): super().__init__() # TODO: move to self.save_hyperparameters() # self.save_hyperparameters() # can also expand arguments into trainer signature for easier reading self.save_hyperparameters(a ) UpperCamelCase__ = 0 UpperCamelCase__ = Path(self.hparams.output_dir ) UpperCamelCase__ = self.hparams.cache_dir if self.hparams.cache_dir else None if config is None: UpperCamelCase__ = AutoConfig.from_pretrained( self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path , **({"num_labels": num_labels} if num_labels is not None else {}) , cache_dir=a , **a , ) else: UpperCamelCase__ = config UpperCamelCase__ = ("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout") for p in extra_model_params: if getattr(self.hparams , a , a ): assert hasattr(self.config , a ), f'''model config doesn\'t have a `{p}` attribute''' setattr(self.config , a , getattr(self.hparams , a ) ) if tokenizer is None: UpperCamelCase__ = AutoTokenizer.from_pretrained( self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path , cache_dir=a , ) else: UpperCamelCase__ = tokenizer UpperCamelCase__ = MODEL_MODES[mode] if model is None: UpperCamelCase__ = self.model_type.from_pretrained( self.hparams.model_name_or_path , from_tf=bool(".ckpt" in self.hparams.model_name_or_path ) , config=self.config , cache_dir=a , ) else: UpperCamelCase__ = model def __a ( self , *a , **a ): UpperCamelCase__ = self.model_type.from_pretrained(*a , **a ) def __a ( self ): UpperCamelCase__ = arg_to_scheduler[self.hparams.lr_scheduler] UpperCamelCase__ = get_schedule_func( self.opt , num_warmup_steps=self.hparams.warmup_steps , num_training_steps=self.total_steps() ) UpperCamelCase__ = {"scheduler": scheduler, "interval": "step", "frequency": 1} return scheduler def __a ( self ): UpperCamelCase__ = self.model UpperCamelCase__ = ["bias", "LayerNorm.weight"] UpperCamelCase__ = [ { "params": [ p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay ) ], # check this named paramters "weight_decay": self.hparams.weight_decay, }, { "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay )], "weight_decay": 0.0, }, ] if self.hparams.adafactor: UpperCamelCase__ = Adafactor( a , lr=self.hparams.learning_rate , scale_parameter=a , relative_step=a ) else: UpperCamelCase__ = AdamW( a , lr=self.hparams.learning_rate , eps=self.hparams.adam_epsilon ) UpperCamelCase__ = optimizer UpperCamelCase__ = self.get_lr_scheduler() return [optimizer], [scheduler] def __a ( self , a , a ): return self.validation_step(a , a ) def __a ( self , a ): return self.validation_end(a ) def __a ( self ): UpperCamelCase__ = max(1 , self.hparams.gpus ) # TODO: consider num_tpu_cores UpperCamelCase__ = self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs def __a ( self , a ): if stage == "test": UpperCamelCase__ = len(self.test_dataloader().dataset ) else: UpperCamelCase__ = self.get_dataloader("train" , self.hparams.train_batch_size , shuffle=a ) UpperCamelCase__ = len(self.train_dataloader().dataset ) def __a ( self , a , a , a = False ): raise NotImplementedError("You must implement this for your task" ) def __a ( self ): return self.train_loader def __a ( self ): return self.get_dataloader("dev" , self.hparams.eval_batch_size , shuffle=a ) def __a ( self ): return self.get_dataloader("test" , self.hparams.eval_batch_size , shuffle=a ) def __a ( self , a ): return os.path.join( self.hparams.data_dir , "cached_{}_{}_{}".format( a , list(filter(a , self.hparams.model_name_or_path.split("/" ) ) ).pop() , str(self.hparams.max_seq_length ) , ) , ) @pl.utilities.rank_zero_only def __a ( self , a ): UpperCamelCase__ = self.output_dir.joinpath("best_tfmr" ) UpperCamelCase__ = self.step_count self.model.save_pretrained(a ) self.tokenizer.save_pretrained(a ) @staticmethod def __a ( a , a ): parser.add_argument( "--model_name_or_path" , default=a , type=a , required=a , help="Path to pretrained model or model identifier from huggingface.co/models" , ) parser.add_argument( "--config_name" , default="" , type=a , help="Pretrained config name or path if not the same as model_name" ) parser.add_argument( "--tokenizer_name" , default=a , type=a , help="Pretrained tokenizer name or path if not the same as model_name" , ) parser.add_argument( "--cache_dir" , default=str(Path(a ).parent / "test_run" / "cache" ) , type=a , help="Where do you want to store the pre-trained models downloaded from huggingface.co" , ) parser.add_argument( "--encoder_layerdrop" , type=a , help="Encoder layer dropout probability (Optional). Goes into model.config" , ) parser.add_argument( "--decoder_layerdrop" , type=a , help="Decoder layer dropout probability (Optional). Goes into model.config" , ) parser.add_argument( "--dropout" , type=a , help="Dropout probability (Optional). Goes into model.config" , ) parser.add_argument( "--attention_dropout" , type=a , help="Attention dropout probability (Optional). Goes into model.config" , ) parser.add_argument("--learning_rate" , default=5e-5 , type=a , help="The initial learning rate for Adam." ) parser.add_argument( "--lr_scheduler" , default="linear" , choices=a , metavar=a , type=a , help="Learning rate scheduler" , ) parser.add_argument("--weight_decay" , default=0.0 , type=a , help="Weight decay if we apply some." ) parser.add_argument("--adam_epsilon" , default=1e-8 , type=a , help="Epsilon for Adam optimizer." ) parser.add_argument("--warmup_steps" , default=0 , type=a , help="Linear warmup over warmup_steps." ) parser.add_argument("--num_workers" , default=4 , type=a , help="kwarg passed to DataLoader" ) parser.add_argument("--num_train_epochs" , dest="max_epochs" , default=3 , type=a ) parser.add_argument("--train_batch_size" , default=32 , type=a ) parser.add_argument("--eval_batch_size" , default=32 , type=a ) parser.add_argument("--adafactor" , action="store_true" ) class lowercase_ ( pl.Callback ): def __a ( self , a , a ): if ( trainer.is_global_zero and trainer.global_rank == 0 ): # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed. pl_module.model.rag.retriever.init_retrieval() # better to use hook functions. class lowercase_ ( pl.Callback ): def __a ( self , a , a ): # print(pl_module.model.rag) for name, param in pl_module.model.rag.named_parameters(): if param.grad is None: print(a ) class lowercase_ ( pl.Callback ): def __a ( self , a , a ): UpperCamelCase__ = trainer.lr_schedulers[0]["scheduler"] UpperCamelCase__ = {f'''lr_group_{i}''': lr for i, lr in enumerate(lr_scheduler.get_lr() )} pl_module.logger.log_metrics(a ) def __a ( self , a , a ): rank_zero_info("***** Validation results *****" ) UpperCamelCase__ = trainer.callback_metrics # Log results for key in sorted(a ): if key not in ["log", "progress_bar"]: rank_zero_info("{} = {}\n".format(a , str(metrics[key] ) ) ) def __a ( self , a , a ): rank_zero_info("***** Test results *****" ) UpperCamelCase__ = trainer.callback_metrics # Log and save results to file UpperCamelCase__ = os.path.join(pl_module.hparams.output_dir , "test_results.txt" ) with open(a , "w" ) as writer: for key in sorted(a ): if key not in ["log", "progress_bar"]: rank_zero_info("{} = {}\n".format(a , str(metrics[key] ) ) ) writer.write("{} = {}\n".format(a , str(metrics[key] ) ) ) def _UpperCamelCase ( __A , __A ) -> None: '''simple docstring''' parser.add_argument( "--output_dir" , default=str(Path(__A ).parent / "test_run" / "model_checkpoints" ) , type=__A , help="The output directory where the model predictions and checkpoints will be written." , ) parser.add_argument( "--fp16" , action="store_true" , help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit" , ) parser.add_argument( "--fp16_opt_level" , type=__A , default="O2" , help=( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html" ) , ) parser.add_argument("--n_tpu_cores" , dest="tpu_cores" , type=__A ) parser.add_argument("--max_grad_norm" , dest="gradient_clip_val" , default=1.0 , type=__A , help="Max gradient norm" ) parser.add_argument("--do_train" , action="store_true" , help="Whether to run training." ) parser.add_argument("--do_predict" , action="store_true" , help="Whether to run predictions on the test set." ) parser.add_argument( "--gradient_accumulation_steps" , dest="accumulate_grad_batches" , type=__A , default=1 , help="Number of updates steps to accumulate before performing a backward/update pass." , ) parser.add_argument("--seed" , type=__A , default=42 , help="random seed for initialization" ) parser.add_argument( "--data_dir" , default=str(Path(__A ).parent / "test_run" / "dummy-train-data" ) , type=__A , help="The input data dir. Should contain the training files for the CoNLL-2003 NER task." , ) def _UpperCamelCase ( __A , __A , __A=None , __A=True , __A=[] , __A=None , __A=None , **__A , ) -> int: '''simple docstring''' pl.seed_everything(args.seed ) # init model UpperCamelCase__ = Path(model.hparams.output_dir ) odir.mkdir(exist_ok=__A ) # add custom checkpoints if checkpoint_callback is None: UpperCamelCase__ = pl.callbacks.ModelCheckpoint( filepath=args.output_dir , prefix="checkpoint" , monitor="val_loss" , mode="min" , save_top_k=1 ) if early_stopping_callback: extra_callbacks.append(__A ) if logging_callback is None: UpperCamelCase__ = LoggingCallback() UpperCamelCase__ = {} if args.fpaa: UpperCamelCase__ = 16 if args.gpus > 1: UpperCamelCase__ = "auto" UpperCamelCase__ = "ddp" UpperCamelCase__ = args.accumulate_grad_batches UpperCamelCase__ = None UpperCamelCase__ = "auto" UpperCamelCase__ = pl.Trainer.from_argparse_args( __A , weights_summary=__A , callbacks=[logging_callback] + extra_callbacks + [InitCallback()] + [checkpoint_callback] , logger=__A , val_check_interval=1 , num_sanity_val_steps=2 , **__A , ) if args.do_train: trainer.fit(__A ) else: print("RAG modeling tests with new set functions successfuly executed!" ) return trainer
80
'''simple docstring''' a__ : Union[str, Any] = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution a__ : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 a__ : Optional[Any] = True a__ : Optional[Any] = False def _UpperCamelCase ( __A ) -> bool: '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__A ) ) UpperCamelCase__ = number_chain while number < 10000000: UpperCamelCase__ = number_chain number *= 10 return number_chain def _UpperCamelCase ( __A = 10000000 ) -> int: '''simple docstring''' for i in range(1 , __A ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__A ) if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution() = }""")
80
1
'''simple docstring''' import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis_float32 (there's also the fix_lavis branch) # also note: to convert Vicuna checkpoints, we had to include /home/niels/python_projects/checkpoints/FastChat/vicuna-7b in lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml # same for Vicuna-13b from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipImageProcessor, InstructBlipConfig, InstructBlipForConditionalGeneration, InstructBlipProcessor, InstructBlipQFormerConfig, InstructBlipVisionConfig, LlamaConfig, LlamaTokenizerFast, TaConfig, TaTokenizerFast, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def _UpperCamelCase ( ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = "https://raw.githubusercontent.com/salesforce/LAVIS/main/docs/_static/Confusing-Pictures.jpg" UpperCamelCase__ = Image.open(requests.get(__A , stream=__A ).raw ).convert("RGB" ) return image def _UpperCamelCase ( __A ) -> List[str]: '''simple docstring''' UpperCamelCase__ = [] # fmt: off # vision encoder rename_keys.append(("visual_encoder.cls_token", "vision_model.embeddings.class_embedding") ) rename_keys.append(("visual_encoder.pos_embed", "vision_model.embeddings.position_embedding") ) rename_keys.append(("visual_encoder.patch_embed.proj.weight", "vision_model.embeddings.patch_embedding.weight") ) rename_keys.append(("visual_encoder.patch_embed.proj.bias", "vision_model.embeddings.patch_embedding.bias") ) rename_keys.append(("ln_vision.weight", "vision_model.post_layernorm.weight") ) rename_keys.append(("ln_vision.bias", "vision_model.post_layernorm.bias") ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.weight''', F'''vision_model.encoder.layers.{i}.layer_norm1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.bias''', F'''vision_model.encoder.layers.{i}.layer_norm1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.weight''', F'''vision_model.encoder.layers.{i}.layer_norm2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.bias''', F'''vision_model.encoder.layers.{i}.layer_norm2.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.qkv.weight''', F'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.weight''', F'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',) ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.bias''', F'''vision_model.encoder.layers.{i}.self_attn.projection.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc2.bias''') ) # QFormer rename_keys.append(("Qformer.bert.embeddings.LayerNorm.weight", "qformer.embeddings.layernorm.weight") ) rename_keys.append(("Qformer.bert.embeddings.LayerNorm.bias", "qformer.embeddings.layernorm.bias") ) # fmt: on return rename_keys def _UpperCamelCase ( __A , __A , __A ) -> int: '''simple docstring''' UpperCamelCase__ = dct.pop(__A ) UpperCamelCase__ = val def _UpperCamelCase ( __A , __A ) -> Optional[Any]: '''simple docstring''' for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases UpperCamelCase__ = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.q_bias''' ) UpperCamelCase__ = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.v_bias''' ) # next, set bias in the state dict UpperCamelCase__ = torch.cat((q_bias, torch.zeros_like(__A , requires_grad=__A ), v_bias) ) UpperCamelCase__ = qkv_bias def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = 364 if "coco" in model_name else 224 UpperCamelCase__ = InstructBlipVisionConfig(image_size=__A ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "t5-xl" in model_name: UpperCamelCase__ = TaConfig.from_pretrained("google/flan-t5-xl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: UpperCamelCase__ = TaConfig.from_pretrained("google/flan-t5-xxl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() elif "vicuna-7b" in model_name: UpperCamelCase__ = LlamaConfig.from_pretrained("decapoda-research/llama-7b-hf" , vocab_size=32001 ).to_dict() elif "vicuna-13b" in model_name: UpperCamelCase__ = LlamaConfig.from_pretrained("decapoda-research/llama-13b-hf" , vocab_size=32001 ).to_dict() else: raise ValueError("Model name not supported" ) # the authors add one special "[DEC]" token to the vocab of Q-Former, hence vocab size = 30522 + 1 UpperCamelCase__ = InstructBlipQFormerConfig(vocab_size=30523 ).to_dict() UpperCamelCase__ = InstructBlipConfig(vision_config=__A , text_config=__A , qformer_config=__A ) return config, image_size @torch.no_grad() def _UpperCamelCase ( __A , __A=None , __A=False ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = AutoTokenizer.from_pretrained("bert-base-uncased" , truncation_side="left" ) qformer_tokenizer.add_special_tokens({"bos_token": "[DEC]"} ) if "t5" in model_name: UpperCamelCase__ = TaTokenizerFast.from_pretrained("google/flan-t5-xl" , truncation_side="left" ) elif "vicuna" in model_name: # the following was used in the original implementation: # tokenizer = LlamaTokenizer.from_pretrained("huggyllama/llama-7b", use_fast=False, truncation_side="left") # tokenizer.add_special_tokens({"pad_token": "[PAD]"}) # tokenizer.add_special_tokens({"bos_token": "</s>"}) # tokenizer.add_special_tokens({"eos_token": "</s>"}) # tokenizer.add_special_tokens({"unk_token": "</s>"}) UpperCamelCase__ = LlamaTokenizerFast.from_pretrained( "huggyllama/llama-7b" , truncation_side="left" , bos_token="</s>" , unk_token="</s>" ) tokenizer.add_special_tokens({"pad_token": "[PAD]"} ) UpperCamelCase__ , UpperCamelCase__ = get_blipa_config(__A ) UpperCamelCase__ = InstructBlipForConditionalGeneration(__A ).eval() UpperCamelCase__ = { "instructblip-vicuna-7b": ("blip2_vicuna_instruct", "vicuna7b"), "instructblip-vicuna-13b": ("blip2_vicuna_instruct", "vicuna13b"), "instructblip-flan-t5-xl": ("blip2_t5_instruct", "flant5xl"), "instructblip-flan-t5-xxl": ("blip2_t5_instruct", "flant5xxl"), } UpperCamelCase__ , UpperCamelCase__ = model_name_to_original[model_name] # load original model print("Loading original model..." ) UpperCamelCase__ = "cuda:1" if torch.cuda.is_available() else "cpu" UpperCamelCase__ = "cuda:2" if torch.cuda.is_available() else "cpu" UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = load_model_and_preprocess( name=__A , model_type=__A , is_eval=__A , device=__A ) original_model.eval() print("Done!" ) # update state dict keys UpperCamelCase__ = original_model.state_dict() UpperCamelCase__ = create_rename_keys(__A ) for src, dest in rename_keys: rename_key(__A , __A , __A ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): UpperCamelCase__ = state_dict.pop(__A ) if key.startswith("Qformer.bert" ): UpperCamelCase__ = key.replace("Qformer.bert" , "qformer" ) if "attention.self" in key: UpperCamelCase__ = key.replace("self" , "attention" ) if "llm_proj" in key: UpperCamelCase__ = key.replace("llm_proj" , "language_projection" ) if "t5_proj" in key: UpperCamelCase__ = key.replace("t5_proj" , "language_projection" ) if key.startswith("llm_model" ): UpperCamelCase__ = key.replace("llm_model" , "language_model" ) if key.startswith("t5" ): UpperCamelCase__ = key.replace("t5" , "language" ) UpperCamelCase__ = val # read in qv biases read_in_q_v_bias(__A , __A ) # note: weights get loaded in torch.float32 by default hf_model.load_state_dict(__A , strict=__A ) UpperCamelCase__ = load_demo_image() UpperCamelCase__ = "What is unusual about this image?" # create processor UpperCamelCase__ = BlipImageProcessor( size={"height": image_size, "width": image_size} , image_mean=__A , image_std=__A ) UpperCamelCase__ = InstructBlipProcessor( image_processor=__A , tokenizer=__A , qformer_tokenizer=__A , ) UpperCamelCase__ = processor(images=__A , text=__A , return_tensors="pt" ).to(__A ) # make sure processor creates exact same pixel values UpperCamelCase__ = vis_processors["eval"](__A ).unsqueeze(0 ).to(__A ) UpperCamelCase__ = inputs.pixel_values assert torch.allclose(original_pixel_values.to(pixel_values.device ) , __A ) original_model.to(__A ) hf_model.to(__A ) with torch.no_grad(): if "vicuna" in model_name: UpperCamelCase__ = original_model({"image": original_pixel_values, "text_input": [prompt]} ).logits UpperCamelCase__ = hf_model(**__A ).logits else: UpperCamelCase__ = original_model( {"image": original_pixel_values, "text_input": [prompt], "text_output": ["\n"]} ).logits UpperCamelCase__ = tokenizer("\n" , return_tensors="pt" ).input_ids.to(__A ) UpperCamelCase__ = label_input_ids.masked_fill(label_input_ids == tokenizer.pad_token_id , -100 ) UpperCamelCase__ = hf_model(**__A , labels=__A ).logits print("First values of original logits:" , original_logits[0, :3, :3] ) print("First values of HF logits:" , logits[0, :3, :3] ) # assert values assert original_logits.shape == logits.shape UpperCamelCase__ = 1E-4 if "vicuna" in model_name else 1E-5 assert torch.allclose(original_logits.to(logits.device ) , __A , atol=__A ) print("Looks ok!" ) print("Generating with original model..." ) UpperCamelCase__ = original_model.generate({"image": original_pixel_values, "prompt": prompt} , num_beams=5 ) # important: we need to cast the weights of the HF model to the appropriate type print("Generating with HF model..." ) UpperCamelCase__ = hf_model.generate( **__A , do_sample=__A , num_beams=5 , max_length=256 , min_length=1 , top_p=0.9 , repetition_penalty=1.5 , length_penalty=1.0 , temperature=1 , ) if "vicuna" in model_name: # convert output id 0 to 2 (eos_token_id) # TODO add this in the generate method? UpperCamelCase__ = 2 print("Original generation:" , __A ) UpperCamelCase__ = processor.batch_decode(__A , skip_special_tokens=__A ) UpperCamelCase__ = [text.strip() for text in output_text] print("HF generation:" , __A ) if pytorch_dump_folder_path is not None: processor.save_pretrained(__A ) hf_model.save_pretrained(__A ) if push_to_hub: processor.push_to_hub(F'''Salesforce/{model_name}''' ) hf_model.push_to_hub(F'''Salesforce/{model_name}''' ) if __name__ == "__main__": a__ : int = argparse.ArgumentParser() a__ : int = [ 'instructblip-vicuna-7b', 'instructblip-vicuna-13b', 'instructblip-flan-t5-xl', 'instructblip-flan-t5-xxl', ] parser.add_argument( '--model_name', default='instructblip-flan-t5-xl', choices=choices, type=str, help='Path to hf config.json of model to convert', ) parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub after converting', ) a__ : int = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
80
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def _UpperCamelCase ( __A , __A , __A=1024 , __A=1024 , __A=False , **__A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = AutoTokenizer.from_pretrained(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="train" , **__A ) UpperCamelCase__ = tok.pad_token_id def get_lens(__A ): UpperCamelCase__ = tqdm( DataLoader(__A , batch_size=512 , num_workers=8 , shuffle=__A , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) UpperCamelCase__ = [] for batch in dl: UpperCamelCase__ = batch["input_ids"].ne(__A ).sum(1 ).tolist() UpperCamelCase__ = batch["labels"].ne(__A ).sum(1 ).tolist() if consider_target: for src, tgt in zip(__A , __A ): max_lens.append(max(__A , __A ) ) else: max_lens.extend(__A ) return max_lens UpperCamelCase__ = get_lens(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="val" , **__A ) UpperCamelCase__ = get_lens(__A ) pickle_save(__A , train_ds.len_file ) pickle_save(__A , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
80
1
'''simple docstring''' from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def _UpperCamelCase ( __A , __A , __A = 1 / sqrt(2 ) ) -> IIRFilter: '''simple docstring''' UpperCamelCase__ = tau * frequency / samplerate UpperCamelCase__ = sin(__A ) UpperCamelCase__ = cos(__A ) UpperCamelCase__ = _sin / (2 * q_factor) UpperCamelCase__ = (1 - _cos) / 2 UpperCamelCase__ = 1 - _cos UpperCamelCase__ = 1 + alpha UpperCamelCase__ = -2 * _cos UpperCamelCase__ = 1 - alpha UpperCamelCase__ = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _UpperCamelCase ( __A , __A , __A = 1 / sqrt(2 ) ) -> IIRFilter: '''simple docstring''' UpperCamelCase__ = tau * frequency / samplerate UpperCamelCase__ = sin(__A ) UpperCamelCase__ = cos(__A ) UpperCamelCase__ = _sin / (2 * q_factor) UpperCamelCase__ = (1 + _cos) / 2 UpperCamelCase__ = -1 - _cos UpperCamelCase__ = 1 + alpha UpperCamelCase__ = -2 * _cos UpperCamelCase__ = 1 - alpha UpperCamelCase__ = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _UpperCamelCase ( __A , __A , __A = 1 / sqrt(2 ) ) -> IIRFilter: '''simple docstring''' UpperCamelCase__ = tau * frequency / samplerate UpperCamelCase__ = sin(__A ) UpperCamelCase__ = cos(__A ) UpperCamelCase__ = _sin / (2 * q_factor) UpperCamelCase__ = _sin / 2 UpperCamelCase__ = 0 UpperCamelCase__ = -ba UpperCamelCase__ = 1 + alpha UpperCamelCase__ = -2 * _cos UpperCamelCase__ = 1 - alpha UpperCamelCase__ = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _UpperCamelCase ( __A , __A , __A = 1 / sqrt(2 ) ) -> IIRFilter: '''simple docstring''' UpperCamelCase__ = tau * frequency / samplerate UpperCamelCase__ = sin(__A ) UpperCamelCase__ = cos(__A ) UpperCamelCase__ = _sin / (2 * q_factor) UpperCamelCase__ = 1 - alpha UpperCamelCase__ = -2 * _cos UpperCamelCase__ = 1 + alpha UpperCamelCase__ = IIRFilter(2 ) filt.set_coefficients([ba, ba, ba] , [ba, ba, ba] ) return filt def _UpperCamelCase ( __A , __A , __A , __A = 1 / sqrt(2 ) , ) -> IIRFilter: '''simple docstring''' UpperCamelCase__ = tau * frequency / samplerate UpperCamelCase__ = sin(__A ) UpperCamelCase__ = cos(__A ) UpperCamelCase__ = _sin / (2 * q_factor) UpperCamelCase__ = 10 ** (gain_db / 40) UpperCamelCase__ = 1 + alpha * big_a UpperCamelCase__ = -2 * _cos UpperCamelCase__ = 1 - alpha * big_a UpperCamelCase__ = 1 + alpha / big_a UpperCamelCase__ = -2 * _cos UpperCamelCase__ = 1 - alpha / big_a UpperCamelCase__ = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _UpperCamelCase ( __A , __A , __A , __A = 1 / sqrt(2 ) , ) -> IIRFilter: '''simple docstring''' UpperCamelCase__ = tau * frequency / samplerate UpperCamelCase__ = sin(__A ) UpperCamelCase__ = cos(__A ) UpperCamelCase__ = _sin / (2 * q_factor) UpperCamelCase__ = 10 ** (gain_db / 40) UpperCamelCase__ = (big_a + 1) - (big_a - 1) * _cos UpperCamelCase__ = (big_a + 1) + (big_a - 1) * _cos UpperCamelCase__ = (big_a - 1) - (big_a + 1) * _cos UpperCamelCase__ = (big_a - 1) + (big_a + 1) * _cos UpperCamelCase__ = 2 * sqrt(__A ) * alpha UpperCamelCase__ = big_a * (pmc + aaa) UpperCamelCase__ = 2 * big_a * mpc UpperCamelCase__ = big_a * (pmc - aaa) UpperCamelCase__ = ppmc + aaa UpperCamelCase__ = -2 * pmpc UpperCamelCase__ = ppmc - aaa UpperCamelCase__ = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _UpperCamelCase ( __A , __A , __A , __A = 1 / sqrt(2 ) , ) -> IIRFilter: '''simple docstring''' UpperCamelCase__ = tau * frequency / samplerate UpperCamelCase__ = sin(__A ) UpperCamelCase__ = cos(__A ) UpperCamelCase__ = _sin / (2 * q_factor) UpperCamelCase__ = 10 ** (gain_db / 40) UpperCamelCase__ = (big_a + 1) - (big_a - 1) * _cos UpperCamelCase__ = (big_a + 1) + (big_a - 1) * _cos UpperCamelCase__ = (big_a - 1) - (big_a + 1) * _cos UpperCamelCase__ = (big_a - 1) + (big_a + 1) * _cos UpperCamelCase__ = 2 * sqrt(__A ) * alpha UpperCamelCase__ = big_a * (ppmc + aaa) UpperCamelCase__ = -2 * big_a * pmpc UpperCamelCase__ = big_a * (ppmc - aaa) UpperCamelCase__ = pmc + aaa UpperCamelCase__ = 2 * mpc UpperCamelCase__ = pmc - aaa UpperCamelCase__ = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt
80
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer a__ : int = logging.get_logger(__name__) a__ : List[str] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a__ : List[Any] = { 'vocab_file': { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt' ), } } a__ : Optional[Any] = { 'junnyu/roformer_chinese_small': 1_5_3_6, 'junnyu/roformer_chinese_base': 1_5_3_6, 'junnyu/roformer_chinese_char_small': 5_1_2, 'junnyu/roformer_chinese_char_base': 5_1_2, 'junnyu/roformer_small_discriminator': 1_2_8, 'junnyu/roformer_small_generator': 1_2_8, } a__ : str = { 'junnyu/roformer_chinese_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_base': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_base': {'do_lower_case': True}, 'junnyu/roformer_small_discriminator': {'do_lower_case': True}, 'junnyu/roformer_small_generator': {'do_lower_case': True}, } class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase = RoFormerTokenizer def __init__( self , a=None , a=None , a=True , a="[UNK]" , a="[SEP]" , a="[PAD]" , a="[CLS]" , a="[MASK]" , a=True , a=None , **a , ): super().__init__( a , tokenizer_file=a , do_lower_case=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , tokenize_chinese_chars=a , strip_accents=a , **a , ) UpperCamelCase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , a ) != do_lower_case or pre_tok_state.get("strip_accents" , a ) != strip_accents ): UpperCamelCase__ = getattr(a , pre_tok_state.pop("type" ) ) UpperCamelCase__ = do_lower_case UpperCamelCase__ = strip_accents UpperCamelCase__ = pre_tok_class(**a ) UpperCamelCase__ = do_lower_case def __getstate__( self ): UpperCamelCase__ = self.__dict__.copy() UpperCamelCase__ = BertPreTokenizer() return state def __setstate__( self , a ): UpperCamelCase__ = d UpperCamelCase__ = self.__dict__["_tokenizer"].get_vocab() UpperCamelCase__ = PreTokenizer.custom(JiebaPreTokenizer(a ) ) def __a ( self , a , a=None ): UpperCamelCase__ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __a ( self , a , a = None ): UpperCamelCase__ = [self.sep_token_id] UpperCamelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __a ( self , a , a = None ): UpperCamelCase__ = self._tokenizer.model.save(a , name=a ) return tuple(a ) def __a ( self , a , a=None , a=None , a=False , **a , ): UpperCamelCase__ = BertPreTokenizer() return super().save_pretrained(a , a , a , a , **a )
80
1
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A , __A = None , __A = None ) -> None: '''simple docstring''' if start is None: UpperCamelCase__ = 0 if end is None: UpperCamelCase__ = len(__A ) - 1 if start >= end: return UpperCamelCase__ = (start + end) // 2 slowsort(__A , __A , __A ) slowsort(__A , mid + 1 , __A ) if sequence[end] < sequence[mid]: UpperCamelCase__ , UpperCamelCase__ = sequence[mid], sequence[end] slowsort(__A , __A , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
80
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : Optional[int] = {'vocab_file': 'vocab.txt'} a__ : Optional[Any] = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } a__ : Optional[int] = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def _UpperCamelCase ( __A ) -> str: '''simple docstring''' with open(__A , "r" ) as f: UpperCamelCase__ = f.read().splitlines() return [l.strip() for l in lines] class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self , a , a="<unk>" , a="<cls>" , a="<pad>" , a="<mask>" , a="<eos>" , **a , ): super().__init__(**a ) UpperCamelCase__ = load_vocab_file(a ) UpperCamelCase__ = dict(enumerate(self.all_tokens ) ) UpperCamelCase__ = {tok: ind for ind, tok in enumerate(self.all_tokens )} UpperCamelCase__ = unk_token UpperCamelCase__ = cls_token UpperCamelCase__ = pad_token UpperCamelCase__ = mask_token UpperCamelCase__ = eos_token UpperCamelCase__ = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a , **a ): return text.split() def __a ( self , a=False ): return len(self._id_to_token ) def __a ( self ): return {token: i for i, token in enumerate(self.all_tokens )} def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a , a = None ): UpperCamelCase__ = [self.cls_token_id] UpperCamelCase__ = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError("Cannot tokenize multiple sequences when EOS token is not set!" ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __a ( self , a , a = None , a = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] UpperCamelCase__ = [1] + ([0] * len(a )) + [1] if token_ids_a is not None: mask += [0] * len(a ) + [1] return mask def __a ( self , a , a ): UpperCamelCase__ = os.path.join(a , (filename_prefix + "-" if filename_prefix else "") + "vocab.txt" ) with open(a , "w" ) as f: f.write("\n".join(self.all_tokens ) ) return (vocab_file,) @property def __a ( self ): return self.get_vocab_size(with_added_tokens=a ) def __a ( self , a , a = False ): return super()._add_tokens(a , special_tokens=a )
80
1
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class lowercase_ ( unittest.TestCase ): def __a ( self ): # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. UpperCamelCase__ = [[1, 2, 4], [1, 2, 3, 4]] UpperCamelCase__ = DisjunctiveConstraint(a ) self.assertTrue(isinstance(dc.token_ids , a ) ) with self.assertRaises(a ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(a ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __a ( self ): # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). UpperCamelCase__ = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(a ): DisjunctiveConstraint(a ) # fails here def __a ( self ): UpperCamelCase__ = [[1, 2, 3], [1, 2, 4]] UpperCamelCase__ = DisjunctiveConstraint(a ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = dc.update(1 ) UpperCamelCase__ = stepped is True and completed is False and reset is False self.assertTrue(a ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = dc.update(2 ) UpperCamelCase__ = stepped is True and completed is False and reset is False self.assertTrue(a ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = dc.update(3 ) UpperCamelCase__ = stepped is True and completed is True and reset is False self.assertTrue(a ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __a ( self ): UpperCamelCase__ = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] UpperCamelCase__ = DisjunctiveConstraint(a ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
80
'''simple docstring''' from math import factorial, pi def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_sin() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(__A ) ) def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_cos() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(__A ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(1_0)) print(maclaurin_sin(-1_0)) print(maclaurin_sin(1_0, 1_5)) print(maclaurin_sin(-1_0, 1_5)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(1_0, 1_5)) print(maclaurin_cos(-1_0, 1_5))
80
1
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger("transformers.models.speecht5") def _a ( a :Any , a :List[str] , a :Tuple ) -> int: hf_model.apply_weight_norm() a = checkpoint['''input_conv.weight_g'''] a = checkpoint['''input_conv.weight_v'''] a = checkpoint['''input_conv.bias'''] for i in range(len(config.upsample_rates ) ): a = checkpoint[F"""upsamples.{i}.1.weight_g"""] a = checkpoint[F"""upsamples.{i}.1.weight_v"""] a = checkpoint[F"""upsamples.{i}.1.bias"""] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): a = checkpoint[F"""blocks.{i}.convs1.{j}.1.weight_g"""] a = checkpoint[F"""blocks.{i}.convs1.{j}.1.weight_v"""] a = checkpoint[F"""blocks.{i}.convs1.{j}.1.bias"""] a = checkpoint[F"""blocks.{i}.convs2.{j}.1.weight_g"""] a = checkpoint[F"""blocks.{i}.convs2.{j}.1.weight_v"""] a = checkpoint[F"""blocks.{i}.convs2.{j}.1.bias"""] a = checkpoint['''output_conv.1.weight_g'''] a = checkpoint['''output_conv.1.weight_v'''] a = checkpoint['''output_conv.1.bias'''] hf_model.remove_weight_norm() @torch.no_grad() def _a ( a :Dict , a :int , a :Tuple , a :Dict=None , a :List[Any]=None , ) -> Optional[Any]: if config_path is not None: a = SpeechTaHifiGanConfig.from_pretrained(a ) else: a = SpeechTaHifiGanConfig() a = SpeechTaHifiGan(a ) a = torch.load(a ) load_weights(orig_checkpoint['''model''']['''generator'''] , a , a ) a = np.load(a ) a = stats[0].reshape(-1 ) a = stats[1].reshape(-1 ) a = torch.from_numpy(a ).float() a = torch.from_numpy(a ).float() model.save_pretrained(a ) if repo_id: print('''Pushing to the hub...''' ) model.push_to_hub(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint") parser.add_argument("--stats_path", required=True, default=None, type=str, help="Path to stats.npy file") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model." ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) UpperCAmelCase__ = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
0
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class lowercase_ ( a__ ): def __init__( self , a , a , a = None , a = None , a = False , **a , ): super().__init__(features=a , cache_dir=a , keep_in_memory=a , **a ) UpperCamelCase__ = Sql( cache_dir=a , features=a , sql=a , con=a , **a , ) def __a ( self ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None self.builder.download_and_prepare( download_config=a , download_mode=a , verification_mode=a , base_path=a , ) # Build dataset for splits UpperCamelCase__ = self.builder.as_dataset( split="train" , verification_mode=a , in_memory=self.keep_in_memory ) return dataset class lowercase_ : def __init__( self , a , a , a , a = None , a = None , **a , ): if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) UpperCamelCase__ = dataset UpperCamelCase__ = name UpperCamelCase__ = con UpperCamelCase__ = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE UpperCamelCase__ = num_proc UpperCamelCase__ = to_sql_kwargs def __a ( self ): UpperCamelCase__ = self.to_sql_kwargs.pop("sql" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("con" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("index" , a ) UpperCamelCase__ = self._write(index=a , **self.to_sql_kwargs ) return written def __a ( self , a ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = args UpperCamelCase__ = {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs UpperCamelCase__ = query_table( table=self.dataset.data , key=slice(a , offset + self.batch_size ) , indices=self.dataset._indices , ) UpperCamelCase__ = batch.to_pandas() UpperCamelCase__ = df.to_sql(self.name , self.con , index=a , **a ) return num_rows or len(a ) def __a ( self , a , **a ): UpperCamelCase__ = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: UpperCamelCase__ , UpperCamelCase__ = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , a , a )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += num_rows return written
80
0
'''simple docstring''' import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class __A ( unittest.TestCase , UpperCamelCase__ ): def _lowercase (self : Any ): UpperCAmelCase_ = load_tool("text-classification" ) self.tool.setup() UpperCAmelCase_ = load_tool("text-classification" , remote=__a ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = self.tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(__a , "positive" ) def _lowercase (self : List[Any] ): UpperCAmelCase_ = self.remote_tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(__a , "positive" ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(__a , "positive" ) def _lowercase (self : List[Any] ): UpperCAmelCase_ = self.remote_tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(__a , "positive" )
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. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu a__ : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def _UpperCamelCase ( __A , __A=None , __A=None , __A=None ) -> int: '''simple docstring''' UpperCamelCase__ = True while ask_again: UpperCamelCase__ = input(__A ) try: if default is not None and len(__A ) == 0: return default return convert_value(__A ) if convert_value is not None else result except Exception: if error_message is not None: print(__A ) def _UpperCamelCase ( __A , __A=[] , __A=None , __A=0 ) -> Any: '''simple docstring''' UpperCamelCase__ = BulletMenu(__A , __A ) UpperCamelCase__ = menu.run(default_choice=__A ) return convert_value(__A ) if convert_value is not None else result def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value] ) def _UpperCamelCase ( __A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = int(__A ) return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def _UpperCamelCase ( __A ) -> str: '''simple docstring''' UpperCamelCase__ = int(__A ) return PrecisionType(["no", "fp16", "bf16", "fp8"][value] ) def _UpperCamelCase ( __A ) -> Any: '''simple docstring''' UpperCamelCase__ = int(__A ) return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' return {"yes": True, "no": False}[value.lower()] class lowercase_ ( argparse.RawDescriptionHelpFormatter ): def __a ( self , a , a , a , a ): UpperCamelCase__ = super()._format_usage(a , a , a , a ) UpperCamelCase__ = usage.replace("<command> [<args>] " , "" ) return usage
80
0
'''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 : str = logging.get_logger(__name__) lowerCamelCase : List[str] = { '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 _SCREAMING_SNAKE_CASE (A , A , A , A , A ) -> List[str]: """simple docstring""" for attribute in key.split('''.''' ): lowercase__ = getattr(A , A ) if weight_type is not None: lowercase__ = getattr(A , A ).shape else: lowercase__ = 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": lowercase__ = value elif weight_type == "weight_g": lowercase__ = value elif weight_type == "weight_v": lowercase__ = value elif weight_type == "bias": lowercase__ = value else: lowercase__ = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def _SCREAMING_SNAKE_CASE (A , A ) -> Optional[Any]: """simple docstring""" lowercase__ = [] lowercase__ = fairseq_model.state_dict() lowercase__ = hf_model.feature_extractor for name, value in fairseq_dict.items(): lowercase__ = False if "conv_layers" in name: load_conv_layer( A , A , A , A , hf_model.config.feat_extract_norm == '''group''' , ) lowercase__ = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: lowercase__ = True if "*" in mapped_key: lowercase__ = name.split(A )[0].split('''.''' )[-2] lowercase__ = mapped_key.replace('''*''' , A ) if "weight_g" in name: lowercase__ = '''weight_g''' elif "weight_v" in name: lowercase__ = '''weight_v''' elif "bias" in name and "relative_attention_bias" not in name: lowercase__ = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj lowercase__ = '''weight''' else: lowercase__ = None set_recursively(A , A , A , A , A ) continue if not is_used: unused_weights.append(A ) logger.warning(f"Unused weights: {unused_weights}" ) def _SCREAMING_SNAKE_CASE (A , A , A , A , A ) -> List[str]: """simple docstring""" lowercase__ = full_name.split('''conv_layers.''' )[-1] lowercase__ = name.split('''.''' ) lowercase__ = int(items[0] ) lowercase__ = 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." ) lowercase__ = 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." ) lowercase__ = 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." ) lowercase__ = 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." ) lowercase__ = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(A ) @torch.no_grad() def _SCREAMING_SNAKE_CASE (A , A , A=None ) -> Union[str, Any]: """simple docstring""" lowercase__ = torch.load(A ) lowercase__ = WavLMConfigOrig(checkpoint['''cfg'''] ) lowercase__ = WavLMOrig(A ) model.load_state_dict(checkpoint['''model'''] ) model.eval() if config_path is not None: lowercase__ = WavLMConfig.from_pretrained(A ) else: lowercase__ = WavLMConfig() lowercase__ = WavLMModel(A ) recursively_load_weights(A , A ) hf_wavlm.save_pretrained(A ) if __name__ == "__main__": lowerCamelCase : Any = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') lowerCamelCase : int = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
2
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: if resistor <= 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative or zero value!''' raise ValueError(__A ) first_sum += 1 / float(__A ) index += 1 return 1 / first_sum def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: sum_r += resistor if resistor < 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative value!''' raise ValueError(__A ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
80
0
'''simple docstring''' def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if length <= 0 or not isinstance(snake_case__ , snake_case__ ): raise ValueError('''Length must be a positive integer.''' ) return [n * (2 * n - 1) for n in range(snake_case__ )] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
3
'''simple docstring''' import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class lowercase_ ( enum.Enum ): __UpperCAmelCase = 0 __UpperCAmelCase = 1 __UpperCAmelCase = 2 @add_end_docstrings(a__ ) class lowercase_ ( a__ ): __UpperCAmelCase = '\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n ' def __init__( self , *a , **a ): super().__init__(*a , **a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. UpperCamelCase__ = None if self.model.config.prefix is not None: UpperCamelCase__ = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. UpperCamelCase__ = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._sanitize_parameters(prefix=a , **self._forward_params ) UpperCamelCase__ = {**self._preprocess_params, **preprocess_params} UpperCamelCase__ = {**self._forward_params, **forward_params} def __a ( self , a=None , a=None , a=None , a=None , a=None , a=None , a=None , a=None , **a , ): UpperCamelCase__ = {} if prefix is not None: UpperCamelCase__ = prefix if prefix: UpperCamelCase__ = self.tokenizer( a , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = prefix_inputs["input_ids"].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' " [None, 'hole']" ) UpperCamelCase__ = handle_long_generation preprocess_params.update(a ) UpperCamelCase__ = generate_kwargs UpperCamelCase__ = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("`return_text` is mutually exclusive with `return_full_text`" ) if return_tensors is not None: raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`" ) UpperCamelCase__ = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("`return_text` is mutually exclusive with `return_tensors`" ) UpperCamelCase__ = ReturnType.TENSORS if return_type is not None: UpperCamelCase__ = return_type if clean_up_tokenization_spaces is not None: UpperCamelCase__ = clean_up_tokenization_spaces if stop_sequence is not None: UpperCamelCase__ = self.tokenizer.encode(a , add_special_tokens=a ) if len(a ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) UpperCamelCase__ = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __a ( self , *a , **a ): # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"add_space_before_punct_symbol": True} ) return super()._parse_and_tokenize(*a , **a ) def __call__( self , a , **a ): return super().__call__(a , **a ) def __a ( self , a , a="" , a=None , **a ): UpperCamelCase__ = self.tokenizer( prefix + prompt_text , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = prompt_text if handle_long_generation == "hole": UpperCamelCase__ = inputs["input_ids"].shape[-1] if "max_new_tokens" in generate_kwargs: UpperCamelCase__ = generate_kwargs["max_new_tokens"] else: UpperCamelCase__ = generate_kwargs.get("max_length" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("We cannot infer how many new tokens are expected" ) if cur_len + new_tokens > self.tokenizer.model_max_length: UpperCamelCase__ = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( "We cannot use `hole` to handle this generation the number of desired tokens exceeds the" " models max length" ) UpperCamelCase__ = inputs["input_ids"][:, -keep_length:] if "attention_mask" in inputs: UpperCamelCase__ = inputs["attention_mask"][:, -keep_length:] return inputs def __a ( self , a , **a ): UpperCamelCase__ = model_inputs["input_ids"] UpperCamelCase__ = model_inputs.get("attention_mask" , a ) # Allow empty prompts if input_ids.shape[1] == 0: UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = 1 else: UpperCamelCase__ = input_ids.shape[0] UpperCamelCase__ = model_inputs.pop("prompt_text" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. UpperCamelCase__ = generate_kwargs.pop("prefix_length" , 0 ) if prefix_length > 0: UpperCamelCase__ = "max_new_tokens" in generate_kwargs or ( "generation_config" in generate_kwargs and generate_kwargs["generation_config"].max_new_tokens is not None ) if not has_max_new_tokens: UpperCamelCase__ = generate_kwargs.get("max_length" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length UpperCamelCase__ = "min_new_tokens" in generate_kwargs or ( "generation_config" in generate_kwargs and generate_kwargs["generation_config"].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL UpperCamelCase__ = self.model.generate(input_ids=a , attention_mask=a , **a ) UpperCamelCase__ = generated_sequence.shape[0] if self.framework == "pt": UpperCamelCase__ = generated_sequence.reshape(a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": UpperCamelCase__ = tf.reshape(a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def __a ( self , a , a=ReturnType.FULL_TEXT , a=True ): UpperCamelCase__ = model_outputs["generated_sequence"][0] UpperCamelCase__ = model_outputs["input_ids"] UpperCamelCase__ = model_outputs["prompt_text"] UpperCamelCase__ = generated_sequence.numpy().tolist() UpperCamelCase__ = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: UpperCamelCase__ = {"generated_token_ids": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text UpperCamelCase__ = self.tokenizer.decode( a , skip_special_tokens=a , clean_up_tokenization_spaces=a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: UpperCamelCase__ = 0 else: UpperCamelCase__ = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=a , clean_up_tokenization_spaces=a , ) ) if return_type == ReturnType.FULL_TEXT: UpperCamelCase__ = prompt_text + text[prompt_length:] else: UpperCamelCase__ = text[prompt_length:] UpperCamelCase__ = {"generated_text": all_text} records.append(a ) return records
80
0
'''simple docstring''' import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __snake_case =get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class UpperCAmelCase_ ( __lowercase , unittest.TestCase ): lowerCamelCase : Union[str, Any] = XLMRobertaTokenizer lowerCamelCase : Dict = XLMRobertaTokenizerFast lowerCamelCase : str = True lowerCamelCase : Optional[int] = True def __UpperCAmelCase ( self : Dict ) -> str: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase = XLMRobertaTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self : List[Any] ) -> Union[str, Any]: lowerCAmelCase = '<pad>' lowerCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def __UpperCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: lowerCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(UpperCAmelCase__ ) , 1_0_0_2 ) def __UpperCAmelCase ( self : Union[str, Any] ) -> Tuple: self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_2 ) def __UpperCAmelCase ( self : Optional[int] ) -> List[str]: lowerCAmelCase = XLMRobertaTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) lowerCAmelCase = tokenizer.tokenize('This is a test' ) self.assertListEqual(UpperCAmelCase__ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) lowerCAmelCase = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( UpperCAmelCase__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCAmelCase = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) lowerCAmelCase = tokenizer.convert_ids_to_tokens(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [ 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 __UpperCAmelCase ( self : List[Any] ) -> str: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return lowerCAmelCase = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-xlm-roberta', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowerCAmelCase = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) lowerCAmelCase = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) lowerCAmelCase = tempfile.mkdtemp() lowerCAmelCase = tokenizer_r.save_pretrained(UpperCAmelCase__ ) lowerCAmelCase = tokenizer_p.save_pretrained(UpperCAmelCase__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) lowerCAmelCase = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Checks everything loads correctly in the same way lowerCAmelCase = tokenizer_r.from_pretrained(UpperCAmelCase__ ) lowerCAmelCase = tokenizer_p.from_pretrained(UpperCAmelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCAmelCase__ , UpperCAmelCase__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(UpperCAmelCase__ ) # Save tokenizer rust, legacy_format=True lowerCAmelCase = tempfile.mkdtemp() lowerCAmelCase = tokenizer_r.save_pretrained(UpperCAmelCase__ , legacy_format=UpperCAmelCase__ ) lowerCAmelCase = tokenizer_p.save_pretrained(UpperCAmelCase__ ) # Checks it save with the same files self.assertSequenceEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Checks everything loads correctly in the same way lowerCAmelCase = tokenizer_r.from_pretrained(UpperCAmelCase__ ) lowerCAmelCase = tokenizer_p.from_pretrained(UpperCAmelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCAmelCase__ , UpperCAmelCase__ ) ) shutil.rmtree(UpperCAmelCase__ ) # Save tokenizer rust, legacy_format=False lowerCAmelCase = tempfile.mkdtemp() lowerCAmelCase = tokenizer_r.save_pretrained(UpperCAmelCase__ , legacy_format=UpperCAmelCase__ ) lowerCAmelCase = tokenizer_p.save_pretrained(UpperCAmelCase__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way lowerCAmelCase = tokenizer_r.from_pretrained(UpperCAmelCase__ ) lowerCAmelCase = tokenizer_p.from_pretrained(UpperCAmelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCAmelCase__ , UpperCAmelCase__ ) ) shutil.rmtree(UpperCAmelCase__ ) @cached_property def __UpperCAmelCase ( self : Union[str, Any] ) -> Dict: return XLMRobertaTokenizer.from_pretrained('xlm-roberta-base' ) def __UpperCAmelCase ( self : int ) -> Union[str, Any]: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(UpperCAmelCase__ , f.name ) lowerCAmelCase = XLMRobertaTokenizer(f.name , keep_accents=UpperCAmelCase__ ) lowerCAmelCase = pickle.dumps(UpperCAmelCase__ ) pickle.loads(UpperCAmelCase__ ) def __UpperCAmelCase ( self : Optional[int] ) -> Dict: if not self.test_rust_tokenizer: return lowerCAmelCase = self.get_tokenizer() lowerCAmelCase = self.get_rust_tokenizer() lowerCAmelCase = 'I was born in 92000, and this is falsé.' lowerCAmelCase = tokenizer.tokenize(UpperCAmelCase__ ) lowerCAmelCase = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) lowerCAmelCase = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = self.get_rust_tokenizer() lowerCAmelCase = tokenizer.encode(UpperCAmelCase__ ) lowerCAmelCase = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def __UpperCAmelCase ( self : Optional[Any] ) -> Any: lowerCAmelCase = 'Hello World!' lowerCAmelCase = [0, 3_5_3_7_8, 6_6_6_1, 3_8, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(UpperCAmelCase__ , self.big_tokenizer.encode(UpperCAmelCase__ ) ) @slow def __UpperCAmelCase ( self : Tuple ) -> Optional[int]: lowerCAmelCase = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) lowerCAmelCase = [ 0, 3_2_9_3, 8_3, 1_0, 4_5_5_2, 4_9_8_9, 7_9_8_6, 6_7_8, 1_0, 5_9_1_5, 1_1_1, 1_7_9_4_5_9, 1_2_4_8_5_0, 4, 6_0_4_4, 2_3_7, 1_2, 6, 5, 6, 4, 6_7_8_0, 7_0_5, 1_5, 1_3_8_8, 4_4, 3_7_8, 1_0_1_1_4, 7_1_1, 1_5_2, 2_0, 6, 5, 2_2_3_7_6, 6_4_2, 1_2_2_1, 1_5_1_9_0, 3_4_1_5_3, 4_5_0, 5_6_0_8, 9_5_9, 1_1_1_9, 5_7_7_0_2, 1_3_6, 1_8_6, 4_7, 1_0_9_8, 2_9_3_6_7, 4_7, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 6_0_4_4, 2_3_7, 6_2_8_4, 5_0_9_0_1, 5_2_8, 3_1, 9_0, 3_4, 9_2_7, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(UpperCAmelCase__ , self.big_tokenizer.encode(UpperCAmelCase__ ) ) @slow def __UpperCAmelCase ( self : str ) -> Tuple: # fmt: off lowerCAmelCase = {'input_ids': [[0, 1_1_0_6_2, 8_2_7_7_2, 7, 1_5, 8_2_7_7_2, 5_3_8, 5_1_5_2_9, 2_3_7, 1_7_1_9_8, 1_2_9_0, 2_0_6, 9, 2_1_5_1_7_5, 1_3_1_4, 1_3_6, 1_7_1_9_8, 1_2_9_0, 2_0_6, 9, 5_6_3_5_9, 4_2, 1_2_2_0_0_9, 9, 1_6_4_6_6, 1_6, 8_7_3_4_4, 4_5_3_7, 9, 4_7_1_7, 7_8_3_8_1, 6, 1_5_9_9_5_8, 7, 1_5, 2_4_4_8_0, 6_1_8, 4, 5_2_7, 2_2_6_9_3, 5_4_2_8, 4, 2_7_7_7, 2_4_4_8_0, 9_8_7_4, 4, 4_3_5_2_3, 5_9_4, 4, 8_0_3, 1_8_3_9_2, 3_3_1_8_9, 1_8, 4, 4_3_5_2_3, 2_4_4_4_7, 1_2_3_9_9, 1_0_0, 2_4_9_5_5, 8_3_6_5_8, 9_6_2_6, 1_4_4_0_5_7, 1_5, 8_3_9, 2_2_3_3_5, 1_6, 1_3_6, 2_4_9_5_5, 8_3_6_5_8, 8_3_4_7_9, 1_5, 3_9_1_0_2, 7_2_4, 1_6, 6_7_8, 6_4_5, 2_7_8_9, 1_3_2_8, 4_5_8_9, 4_2, 1_2_2_0_0_9, 1_1_5_7_7_4, 2_3, 8_0_5, 1_3_2_8, 4_6_8_7_6, 7, 1_3_6, 5_3_8_9_4, 1_9_4_0, 4_2_2_2_7, 4_1_1_5_9, 1_7_7_2_1, 8_2_3, 4_2_5, 4, 2_7_5_1_2, 9_8_7_2_2, 2_0_6, 1_3_6, 5_5_3_1, 4_9_7_0, 9_1_9, 1_7_3_3_6, 5, 2], [0, 2_0_0_8_0, 6_1_8, 8_3, 8_2_7_7_5, 4_7, 4_7_9, 9, 1_5_1_7, 7_3, 5_3_8_9_4, 3_3_3, 8_0_5_8_1, 1_1_0_1_1_7, 1_8_8_1_1, 5_2_5_6, 1_2_9_5, 5_1, 1_5_2_5_2_6, 2_9_7, 7_9_8_6, 3_9_0, 1_2_4_4_1_6, 5_3_8, 3_5_4_3_1, 2_1_4, 9_8, 1_5_0_4_4, 2_5_7_3_7, 1_3_6, 7_1_0_8, 4_3_7_0_1, 2_3, 7_5_6, 1_3_5_3_5_5, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 5_8_1, 6_3_7_7_3, 1_1_9_4_5_5, 6, 1_4_7_7_9_7, 8_8_2_0_3, 7, 6_4_5, 7_0, 2_1, 3_2_8_5, 1_0_2_6_9, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name='xlm-roberta-base' , revision='d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3' , )
4
'''simple docstring''' from ....utils import logging a__ : Optional[Any] = logging.get_logger(__name__) class lowercase_ ( a__ ): def __init__( self , a , a=None , a=20_48 ): UpperCamelCase__ = config.__dict__ UpperCamelCase__ = modal_hidden_size if num_labels: UpperCamelCase__ = num_labels
80
0
import math def UpperCAmelCase_ ( __snake_case , __snake_case ) -> float: """simple docstring""" if initial_intensity < 0: raise ValueError('''The value of intensity cannot be negative''' ) # handling of negative values of initial intensity if angle < 0 or angle > 360: raise ValueError('''In Malus Law, the angle is in the range 0-360 degrees''' ) # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(__snake_case ) ) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name='''malus_law''')
5
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent a__ : Tuple = {'UserAgent': UserAgent().random} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' UpperCamelCase__ = script.contents[0] UpperCamelCase__ = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class lowercase_ : def __init__( self , a ): UpperCamelCase__ = f'''https://www.instagram.com/{username}/''' UpperCamelCase__ = self.get_json() def __a ( self ): UpperCamelCase__ = requests.get(self.url , headers=a ).text UpperCamelCase__ = BeautifulSoup(a , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self ): return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self ): return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def __a ( self ): return self.user_data["username"] @property def __a ( self ): return self.user_data["full_name"] @property def __a ( self ): return self.user_data["biography"] @property def __a ( self ): return self.user_data["business_email"] @property def __a ( self ): return self.user_data["external_url"] @property def __a ( self ): return self.user_data["edge_followed_by"]["count"] @property def __a ( self ): return self.user_data["edge_follow"]["count"] @property def __a ( self ): return self.user_data["edge_owner_to_timeline_media"]["count"] @property def __a ( self ): return self.user_data["profile_pic_url_hd"] @property def __a ( self ): return self.user_data["is_verified"] @property def __a ( self ): return self.user_data["is_private"] def _UpperCamelCase ( __A = "github" ) -> None: '''simple docstring''' import os if os.environ.get("CI" ): return # test failing on GitHub Actions UpperCamelCase__ = InstagramUser(__A ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __A ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() a__ : Any = InstagramUser('github') print(instagram_user) print(F"""{instagram_user.number_of_posts = }""") print(F"""{instagram_user.number_of_followers = }""") print(F"""{instagram_user.number_of_followings = }""") print(F"""{instagram_user.email = }""") print(F"""{instagram_user.website = }""") print(F"""{instagram_user.profile_picture_url = }""") print(F"""{instagram_user.is_verified = }""") print(F"""{instagram_user.is_private = }""")
80
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging A : Tuple = logging.get_logger(__name__) A : Dict = { 'Salesforce/blip-vqa-base': 'https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json', 'Salesforce/blip-vqa-capfit-large': ( 'https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json' ), 'Salesforce/blip-image-captioning-base': ( 'https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json' ), 'Salesforce/blip-image-captioning-large': ( 'https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json' ), 'Salesforce/blip-itm-base-coco': 'https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json', 'Salesforce/blip-itm-large-coco': 'https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json', 'Salesforce/blip-itm-base-flikr': 'https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json', 'Salesforce/blip-itm-large-flikr': ( 'https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json' ), } class __A( a ): snake_case_ = '''blip_text_model''' def __init__( self , _snake_case=30_524 , _snake_case=768 , _snake_case=768 , _snake_case=3_072 , _snake_case=768 , _snake_case=12 , _snake_case=8 , _snake_case=512 , _snake_case="gelu" , _snake_case=1E-12 , _snake_case=0.0 , _snake_case=0.0 , _snake_case=0.02 , _snake_case=30_522 , _snake_case=2 , _snake_case=0 , _snake_case=102 , _snake_case=True , _snake_case=True , **_snake_case , ) -> Optional[int]: '''simple docstring''' super().__init__( pad_token_id=_snake_case , bos_token_id=_snake_case , eos_token_id=_snake_case , sep_token_id=_snake_case , **_snake_case , ) __a = vocab_size __a = hidden_size __a = encoder_hidden_size __a = intermediate_size __a = projection_dim __a = hidden_dropout_prob __a = num_hidden_layers __a = num_attention_heads __a = max_position_embeddings __a = layer_norm_eps __a = hidden_act __a = initializer_range __a = attention_probs_dropout_prob __a = is_decoder __a = use_cache @classmethod def SCREAMING_SNAKE_CASE_ ( cls , _snake_case , **_snake_case ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(_snake_case ) __a , __a = cls.get_config_dict(_snake_case , **_snake_case ) # get the text config dict if we are loading from BlipConfig if config_dict.get('''model_type''' ) == "blip": __a = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(_snake_case , **_snake_case ) class __A( a ): snake_case_ = '''blip_vision_model''' def __init__( self , _snake_case=768 , _snake_case=3_072 , _snake_case=512 , _snake_case=12 , _snake_case=12 , _snake_case=384 , _snake_case=16 , _snake_case="gelu" , _snake_case=1E-5 , _snake_case=0.0 , _snake_case=1E-10 , **_snake_case , ) -> Optional[Any]: '''simple docstring''' super().__init__(**_snake_case ) __a = hidden_size __a = intermediate_size __a = projection_dim __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 @classmethod def SCREAMING_SNAKE_CASE_ ( cls , _snake_case , **_snake_case ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(_snake_case ) __a , __a = cls.get_config_dict(_snake_case , **_snake_case ) # get the vision config dict if we are loading from BlipConfig if config_dict.get('''model_type''' ) == "blip": __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(_snake_case , **_snake_case ) class __A( a ): snake_case_ = '''blip''' snake_case_ = True def __init__( self , _snake_case=None , _snake_case=None , _snake_case=512 , _snake_case=2.6592 , _snake_case=256 , **_snake_case , ) -> Optional[int]: '''simple docstring''' super().__init__(**_snake_case ) if text_config is None: __a = {} logger.info('''`text_config` is `None`. Initializing the `BlipTextConfig` with default values.''' ) if vision_config is None: __a = {} logger.info('''`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.''' ) __a = BlipTextConfig(**_snake_case ) __a = BlipVisionConfig(**_snake_case ) __a = self.vision_config.hidden_size __a = projection_dim __a = logit_scale_init_value __a = 1.0 __a = 0.02 __a = image_text_hidden_size @classmethod def SCREAMING_SNAKE_CASE_ ( cls , _snake_case , _snake_case , **_snake_case ) -> str: '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' __a = copy.deepcopy(self.__dict__ ) __a = self.text_config.to_dict() __a = self.vision_config.to_dict() __a = self.__class__.model_type return output
6
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A , __A , __A ) -> dict[str, float]: '''simple docstring''' if (voltage, current, resistance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if resistance < 0: raise ValueError("Resistance cannot be negative" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
80
0
import multiprocessing import os from typing import BinaryIO, Optional, Union import fsspec from .. import Dataset, Features, NamedSplit, config from ..formatting import query_table from ..packaged_modules.json.json import Json from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class A ( _UpperCAmelCase ): """simple docstring""" def __init__( self : str,lowercase_ : NestedDataStructureLike[PathLike],lowercase_ : Optional[NamedSplit] = None,lowercase_ : Optional[Features] = None,lowercase_ : str = None,lowercase_ : bool = False,lowercase_ : bool = False,lowercase_ : Optional[str] = None,lowercase_ : Optional[int] = None,**lowercase_ : int,)-> Any: '''simple docstring''' super().__init__( lowercase_,split=lowercase_,features=lowercase_,cache_dir=lowercase_,keep_in_memory=lowercase_,streaming=lowercase_,num_proc=lowercase_,**lowercase_,) A__ = field A__ = path_or_paths if isinstance(lowercase_,lowercase_ ) else {self.split: path_or_paths} A__ = Json( cache_dir=lowercase_,data_files=lowercase_,features=lowercase_,field=lowercase_,**lowercase_,) def snake_case__ ( self : Any )-> str: '''simple docstring''' if self.streaming: A__ = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: A__ = None A__ = None A__ = None A__ = None self.builder.download_and_prepare( download_config=lowercase_,download_mode=lowercase_,verification_mode=lowercase_,base_path=lowercase_,num_proc=self.num_proc,) A__ = self.builder.as_dataset( split=self.split,verification_mode=lowercase_,in_memory=self.keep_in_memory ) return dataset class A : """simple docstring""" def __init__( self : Tuple,lowercase_ : Dataset,lowercase_ : Union[PathLike, BinaryIO],lowercase_ : Optional[int] = None,lowercase_ : Optional[int] = None,**lowercase_ : Tuple,)-> Union[str, Any]: '''simple docstring''' if num_proc is not None and num_proc <= 0: raise ValueError(F'num_proc {num_proc} must be an integer > 0.' ) A__ = dataset A__ = path_or_buf A__ = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE A__ = num_proc A__ = 'utf-8' A__ = to_json_kwargs def snake_case__ ( self : List[Any] )-> int: '''simple docstring''' A__ = self.to_json_kwargs.pop('path_or_buf',lowercase_ ) A__ = self.to_json_kwargs.pop('orient','records' ) A__ = self.to_json_kwargs.pop('lines',True if orient == 'records' else False ) A__ = self.to_json_kwargs.pop('index',False if orient in ['split', 'table'] else True ) A__ = self.to_json_kwargs.pop('compression',lowercase_ ) if compression not in [None, "infer", "gzip", "bz2", "xz"]: raise NotImplementedError(F'`datasets` currently does not support {compression} compression' ) if isinstance(self.path_or_buf,(str, bytes, os.PathLike) ): with fsspec.open(self.path_or_buf,'wb',compression=lowercase_ ) as buffer: A__ = self._write(file_obj=lowercase_,orient=lowercase_,lines=lowercase_,index=lowercase_,**self.to_json_kwargs ) else: if compression: raise NotImplementedError( F'The compression parameter is not supported when writing to a buffer, but compression={compression}' ' was passed. Please provide a local path instead.' ) A__ = self._write( file_obj=self.path_or_buf,orient=lowercase_,lines=lowercase_,index=lowercase_,**self.to_json_kwargs ) return written def snake_case__ ( self : List[Any],lowercase_ : int )-> Dict: '''simple docstring''' A__ , A__ , A__ , A__ , A__ = args A__ = query_table( table=self.dataset.data,key=slice(lowercase_,offset + self.batch_size ),indices=self.dataset._indices,) A__ = batch.to_pandas().to_json( path_or_buf=lowercase_,orient=lowercase_,lines=lowercase_,index=lowercase_,**lowercase_ ) if not json_str.endswith('\n' ): json_str += "\n" return json_str.encode(self.encoding ) def snake_case__ ( self : Any,lowercase_ : BinaryIO,lowercase_ : Optional[Any],lowercase_ : Optional[int],lowercase_ : Optional[Any],**lowercase_ : Optional[Any],)-> int: '''simple docstring''' A__ = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0,len(self.dataset ),self.batch_size ),unit='ba',disable=not logging.is_progress_bar_enabled(),desc='Creating json from Arrow format',): A__ = self._batch_json((offset, orient, lines, index, to_json_kwargs) ) written += file_obj.write(lowercase_ ) else: A__ , A__ = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for json_str in logging.tqdm( pool.imap( self._batch_json,[(offset, orient, lines, index, to_json_kwargs) for offset in range(0,lowercase_,lowercase_ )],),total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size,unit='ba',disable=not logging.is_progress_bar_enabled(),desc='Creating json from Arrow format',): written += file_obj.write(lowercase_ ) return written
7
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Union[str, Any] = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys a__ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
80
0
import json import os import torch from diffusers import UNetaDModel os.makedirs('''hub/hopper-medium-v2/unet/hor32''', exist_ok=True) os.makedirs('''hub/hopper-medium-v2/unet/hor128''', exist_ok=True) os.makedirs('''hub/hopper-medium-v2/value_function''', exist_ok=True) def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): if hor == 128: snake_case_ = ('''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''') snake_case_ = (32, 128, 256) snake_case_ = ('''UpResnetBlock1D''', '''UpResnetBlock1D''') elif hor == 32: snake_case_ = ('''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''') snake_case_ = (32, 64, 128, 256) snake_case_ = ('''UpResnetBlock1D''', '''UpResnetBlock1D''', '''UpResnetBlock1D''') snake_case_ = torch.load(F'''/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch''' ) snake_case_ = model.state_dict() snake_case_ = { '''down_block_types''': down_block_types, '''block_out_channels''': block_out_channels, '''up_block_types''': up_block_types, '''layers_per_block''': 1, '''use_timestep_embedding''': True, '''out_block_type''': '''OutConv1DBlock''', '''norm_num_groups''': 8, '''downsample_each_block''': False, '''in_channels''': 14, '''out_channels''': 14, '''extra_in_channels''': 0, '''time_embedding_type''': '''positional''', '''flip_sin_to_cos''': False, '''freq_shift''': 1, '''sample_size''': 65536, '''mid_block_type''': '''MidResTemporalBlock1D''', '''act_fn''': '''mish''', } snake_case_ = UNetaDModel(**SCREAMING_SNAKE_CASE__ ) print(F'''length of state dict: {len(state_dict.keys() )}''' ) print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' ) snake_case_ = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): snake_case_ = state_dict.pop(SCREAMING_SNAKE_CASE__ ) hf_value_function.load_state_dict(SCREAMING_SNAKE_CASE__ ) torch.save(hf_value_function.state_dict() , F'''hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin''' ) with open(F'''hub/hopper-medium-v2/unet/hor{hor}/config.json''' , '''w''' ) as f: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __SCREAMING_SNAKE_CASE (): snake_case_ = { '''in_channels''': 14, '''down_block_types''': ('''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D'''), '''up_block_types''': (), '''out_block_type''': '''ValueFunction''', '''mid_block_type''': '''ValueFunctionMidBlock1D''', '''block_out_channels''': (32, 64, 128, 256), '''layers_per_block''': 1, '''downsample_each_block''': True, '''sample_size''': 65536, '''out_channels''': 14, '''extra_in_channels''': 0, '''time_embedding_type''': '''positional''', '''use_timestep_embedding''': True, '''flip_sin_to_cos''': False, '''freq_shift''': 1, '''norm_num_groups''': 8, '''act_fn''': '''mish''', } snake_case_ = torch.load('''/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch''' ) snake_case_ = model snake_case_ = UNetaDModel(**SCREAMING_SNAKE_CASE__ ) print(F'''length of state dict: {len(state_dict.keys() )}''' ) print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' ) snake_case_ = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): snake_case_ = state_dict.pop(SCREAMING_SNAKE_CASE__ ) hf_value_function.load_state_dict(SCREAMING_SNAKE_CASE__ ) torch.save(hf_value_function.state_dict() , '''hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin''' ) with open('''hub/hopper-medium-v2/value_function/config.json''' , '''w''' ) as f: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": unet(32) # unet(128) value_function()
8
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if len(__A ) != 2 or len(a[0] ) != 2 or len(__A ) != 2 or len(b[0] ) != 2: raise Exception("Matrices are not 2x2" ) UpperCamelCase__ = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _UpperCamelCase ( __A , __A ) -> str: '''simple docstring''' return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A ) -> tuple[list, list, list, list]: '''simple docstring''' if len(__A ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception("Odd matrices are not supported!" ) UpperCamelCase__ = len(__A ) UpperCamelCase__ = matrix_length // 2 UpperCamelCase__ = [[a[i][j] for j in range(__A , __A )] for i in range(__A )] UpperCamelCase__ = [ [a[i][j] for j in range(__A , __A )] for i in range(__A , __A ) ] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A )] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A , __A )] return top_left, top_right, bot_left, bot_right def _UpperCamelCase ( __A ) -> tuple[int, int]: '''simple docstring''' return len(__A ), len(matrix[0] ) def _UpperCamelCase ( __A ) -> None: '''simple docstring''' print("\n".join(str(__A ) for line in matrix ) ) def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A ) == (2, 2): return default_matrix_multiplication(__A , __A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = matrix_addition(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_subtraction(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) # construct the new matrix from our 4 quadrants UpperCamelCase__ = [] for i in range(len(__A ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(__A ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A )[1] != matrix_dimensions(__A )[0]: UpperCamelCase__ = ( "Unable to multiply these matrices, please check the dimensions.\n" F'''Matrix A: {matrixa}\n''' F'''Matrix B: {matrixa}''' ) raise Exception(__A ) UpperCamelCase__ = matrix_dimensions(__A ) UpperCamelCase__ = matrix_dimensions(__A ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] UpperCamelCase__ = max(*__A , *__A ) UpperCamelCase__ = int(math.pow(2 , math.ceil(math.loga(__A ) ) ) ) UpperCamelCase__ = matrixa UpperCamelCase__ = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) UpperCamelCase__ = actual_strassen(__A , __A ) # Removing the additional zeros for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a__ : int = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a__ : str = [[0, 2, 1, 1], [1_6, 2, 3, 3], [2, 2, 7, 7], [1_3, 1_1, 2_2, 4]] print(strassen(matrixa, matrixa))
80
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowerCAmelCase : int =logging.get_logger(__name__) __lowerCAmelCase : List[str] ={ 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json', # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = '''convbert''' def __init__( self :Dict , lowerCAmelCase__ :Tuple=30_522 , lowerCAmelCase__ :Optional[Any]=768 , lowerCAmelCase__ :int=12 , lowerCAmelCase__ :List[str]=12 , lowerCAmelCase__ :Optional[int]=3_072 , lowerCAmelCase__ :str="gelu" , lowerCAmelCase__ :int=0.1 , lowerCAmelCase__ :List[Any]=0.1 , lowerCAmelCase__ :List[Any]=512 , lowerCAmelCase__ :Dict=2 , lowerCAmelCase__ :Optional[int]=0.02 , lowerCAmelCase__ :List[Any]=1E-1_2 , lowerCAmelCase__ :List[str]=1 , lowerCAmelCase__ :Dict=0 , lowerCAmelCase__ :Dict=2 , lowerCAmelCase__ :int=768 , lowerCAmelCase__ :str=2 , lowerCAmelCase__ :Tuple=9 , lowerCAmelCase__ :Optional[int]=1 , lowerCAmelCase__ :List[Any]=None , **lowerCAmelCase__ :Union[str, Any] , ) -> int: super().__init__( pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ , ) __SCREAMING_SNAKE_CASE : Optional[Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[Any] = hidden_size __SCREAMING_SNAKE_CASE : List[str] = num_hidden_layers __SCREAMING_SNAKE_CASE : List[str] = num_attention_heads __SCREAMING_SNAKE_CASE : Union[str, Any] = intermediate_size __SCREAMING_SNAKE_CASE : Any = hidden_act __SCREAMING_SNAKE_CASE : Any = hidden_dropout_prob __SCREAMING_SNAKE_CASE : List[str] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = type_vocab_size __SCREAMING_SNAKE_CASE : int = initializer_range __SCREAMING_SNAKE_CASE : Any = layer_norm_eps __SCREAMING_SNAKE_CASE : str = embedding_size __SCREAMING_SNAKE_CASE : List[str] = head_ratio __SCREAMING_SNAKE_CASE : Optional[Any] = conv_kernel_size __SCREAMING_SNAKE_CASE : int = num_groups __SCREAMING_SNAKE_CASE : int = classifier_dropout class _lowercase ( A__ ): '''simple docstring''' @property def __magic_name__( self :Optional[Any] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE : Tuple = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __SCREAMING_SNAKE_CASE : Tuple = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
9
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging a__ : List[str] = logging.get_logger(__name__) if is_vision_available(): import PIL class lowercase_ ( a__ ): __UpperCAmelCase = ['pixel_values'] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = None , a = True , a = 1 / 2_55 , a = True , a = None , a = None , a = True , **a , ): super().__init__(**a ) UpperCamelCase__ = size if size is not None else {"shortest_edge": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a ) UpperCamelCase__ = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a , param_name="crop_size" ) UpperCamelCase__ = do_resize UpperCamelCase__ = size UpperCamelCase__ = resample UpperCamelCase__ = do_center_crop UpperCamelCase__ = crop_size UpperCamelCase__ = do_rescale UpperCamelCase__ = rescale_factor UpperCamelCase__ = do_normalize UpperCamelCase__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN UpperCamelCase__ = image_std if image_std is not None else OPENAI_CLIP_STD UpperCamelCase__ = do_convert_rgb def __a ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ): UpperCamelCase__ = get_size_dict(a , default_to_square=a ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) UpperCamelCase__ = get_resize_output_image_size(a , size=size["shortest_edge"] , default_to_square=a ) return resize(a , size=a , resample=a , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): UpperCamelCase__ = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(a , size=(size["height"], size["width"]) , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): return rescale(a , scale=a , data_format=a , **a ) def __a ( self , a , a , a , a = None , **a , ): return normalize(a , mean=a , std=a , data_format=a , **a ) def __a ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ): UpperCamelCase__ = do_resize if do_resize is not None else self.do_resize UpperCamelCase__ = size if size is not None else self.size UpperCamelCase__ = get_size_dict(a , param_name="size" , default_to_square=a ) UpperCamelCase__ = resample if resample is not None else self.resample UpperCamelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase__ = crop_size if crop_size is not None else self.crop_size UpperCamelCase__ = get_size_dict(a , param_name="crop_size" , default_to_square=a ) UpperCamelCase__ = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase__ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase__ = image_mean if image_mean is not None else self.image_mean UpperCamelCase__ = image_std if image_std is not None else self.image_std UpperCamelCase__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase__ = make_list_of_images(a ) if not valid_images(a ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase__ = [convert_to_rgb(a ) for image in images] # All transformations expect numpy arrays. UpperCamelCase__ = [to_numpy_array(a ) for image in images] if do_resize: UpperCamelCase__ = [self.resize(image=a , size=a , resample=a ) for image in images] if do_center_crop: UpperCamelCase__ = [self.center_crop(image=a , size=a ) for image in images] if do_rescale: UpperCamelCase__ = [self.rescale(image=a , scale=a ) for image in images] if do_normalize: UpperCamelCase__ = [self.normalize(image=a , mean=a , std=a ) for image in images] UpperCamelCase__ = [to_channel_dimension_format(a , a ) for image in images] UpperCamelCase__ = {"pixel_values": images} return BatchFeature(data=a , tensor_type=a )
80
0
import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 __A = { "return_dict": False, "output_hidden_states": True, "output_attentions": True, "torchscript": True, "torch_dtype": "float16", "use_bfloat16": True, "tf_legacy_loss": True, "pruned_heads": {"a": 1}, "tie_word_embeddings": False, "is_decoder": True, "cross_attention_hidden_size": 128, "add_cross_attention": True, "tie_encoder_decoder": True, "max_length": 50, "min_length": 3, "do_sample": True, "early_stopping": True, "num_beams": 3, "num_beam_groups": 3, "diversity_penalty": 0.5, "temperature": 2.0, "top_k": 10, "top_p": 0.7, "typical_p": 0.2, "repetition_penalty": 0.8, "length_penalty": 0.8, "no_repeat_ngram_size": 5, "encoder_no_repeat_ngram_size": 5, "bad_words_ids": [1, 2, 3], "num_return_sequences": 3, "chunk_size_feed_forward": 5, "output_scores": True, "return_dict_in_generate": True, "forced_bos_token_id": 2, "forced_eos_token_id": 3, "remove_invalid_values": True, "architectures": ["BertModel"], "finetuning_task": "translation", "id2label": {0: "label"}, "label2id": {"label": "0"}, "tokenizer_class": "BertTokenizerFast", "prefix": "prefix", "bos_token_id": 6, "pad_token_id": 7, "eos_token_id": 8, "sep_token_id": 9, "decoder_start_token_id": 10, "exponential_decay_length_penalty": (5, 1.0_1), "suppress_tokens": [0, 1], "begin_suppress_tokens": 2, "task_specific_params": {"translation": "some_params"}, "problem_type": "regression", } @is_staging_test class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @classmethod def SCREAMING_SNAKE_CASE_ (cls : Optional[Any]) ->str: '''simple docstring''' lowerCamelCase__: Tuple =TOKEN HfFolder.save_token(UpperCAmelCase_) @classmethod def SCREAMING_SNAKE_CASE_ (cls : List[str]) ->str: '''simple docstring''' try: delete_repo(token=cls._token , repo_id="test-config") except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-config-org") except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-config") except HTTPError: pass def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: List[Any] =BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37) config.push_to_hub("test-config" , use_auth_token=self._token) lowerCamelCase__: Dict =BertConfig.from_pretrained(F"""{USER}/test-config""") for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase_ , getattr(UpperCAmelCase_ , UpperCAmelCase_)) # Reset repo delete_repo(token=self._token , repo_id="test-config") # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(UpperCAmelCase_ , repo_id="test-config" , push_to_hub=UpperCAmelCase_ , use_auth_token=self._token) lowerCamelCase__: Optional[int] =BertConfig.from_pretrained(F"""{USER}/test-config""") for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase_ , getattr(UpperCAmelCase_ , UpperCAmelCase_)) def SCREAMING_SNAKE_CASE_ (self : Any) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[int] =BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37) config.push_to_hub("valid_org/test-config-org" , use_auth_token=self._token) lowerCamelCase__: Optional[int] =BertConfig.from_pretrained("valid_org/test-config-org") for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase_ , getattr(UpperCAmelCase_ , UpperCAmelCase_)) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-config-org") # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( UpperCAmelCase_ , repo_id="valid_org/test-config-org" , push_to_hub=UpperCAmelCase_ , use_auth_token=self._token) lowerCamelCase__: List[str] =BertConfig.from_pretrained("valid_org/test-config-org") for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase_ , getattr(UpperCAmelCase_ , UpperCAmelCase_)) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]: '''simple docstring''' CustomConfig.register_for_auto_class() lowerCamelCase__: Optional[Any] =CustomConfig(attribute=42) config.push_to_hub("test-dynamic-config" , use_auth_token=self._token) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {"AutoConfig": "custom_configuration.CustomConfig"}) lowerCamelCase__: List[str] =AutoConfig.from_pretrained(F"""{USER}/test-dynamic-config""" , trust_remote_code=UpperCAmelCase_) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , "CustomConfig") self.assertEqual(new_config.attribute , 42) class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Dict: '''simple docstring''' lowerCamelCase__: Tuple =GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated lowerCamelCase__: Tuple =c.n_embd + 1 # int lowerCamelCase__: Optional[int] =c.resid_pdrop + 1.0 # float lowerCamelCase__: Dict =not c.scale_attn_weights # bool lowerCamelCase__: Any =c.summary_type + "foo" # str c.update_from_string( F"""n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}""") self.assertEqual(UpperCAmelCase_ , c.n_embd , "mismatch for key: n_embd") self.assertEqual(UpperCAmelCase_ , c.resid_pdrop , "mismatch for key: resid_pdrop") self.assertEqual(UpperCAmelCase_ , c.scale_attn_weights , "mismatch for key: scale_attn_weights") self.assertEqual(UpperCAmelCase_ , c.summary_type , "mismatch for key: summary_type") def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =PretrainedConfig() lowerCamelCase__: str =[key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( UpperCAmelCase_ , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"]) lowerCamelCase__: int =[key for key, value in config_common_kwargs.items() if value == getattr(UpperCAmelCase_ , UpperCAmelCase_)] if len(UpperCAmelCase_) > 0: raise ValueError( "The following keys are set with the default values in" " `test_configuration_common.config_common_kwargs` pick another value for them:" F""" {", ".join(UpperCAmelCase_)}.""") def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Any: '''simple docstring''' with self.assertRaises(UpperCAmelCase_): # config is in subfolder, the following should not work without specifying the subfolder lowerCamelCase__: Tuple =BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder") lowerCamelCase__: Union[str, Any] =BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" , subfolder="bert") self.assertIsNotNone(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Tuple =mock.Mock() lowerCamelCase__: Tuple =500 lowerCamelCase__: Union[str, Any] ={} lowerCamelCase__: str =HTTPError lowerCamelCase__: Tuple ={} # Download this model to make sure it's in the cache. lowerCamelCase__: str =BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request" , return_value=UpperCAmelCase_) as mock_head: lowerCamelCase__: List[str] =BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") # This check we did call the fake head request mock_head.assert_called() def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Optional[Any] =BertConfig.from_pretrained( "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json") def SCREAMING_SNAKE_CASE_ (self : Tuple) ->int: '''simple docstring''' lowerCamelCase__: Union[str, Any] =AutoConfig.from_pretrained("bert-base-cased") lowerCamelCase__: Any =["config.4.0.0.json"] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(UpperCAmelCase_) lowerCamelCase__: List[Any] =2 json.dump(configuration.to_dict() , open(os.path.join(UpperCAmelCase_ , "config.4.0.0.json") , "w")) # This should pick the new configuration file as the version of Transformers is > 4.0.0 lowerCamelCase__: Optional[Any] =AutoConfig.from_pretrained(UpperCAmelCase_) self.assertEqual(new_configuration.hidden_size , 2) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 lowerCamelCase__: Any =["config.42.0.0.json"] lowerCamelCase__: List[Any] =768 configuration.save_pretrained(UpperCAmelCase_) shutil.move(os.path.join(UpperCAmelCase_ , "config.4.0.0.json") , os.path.join(UpperCAmelCase_ , "config.42.0.0.json")) lowerCamelCase__: Optional[int] =AutoConfig.from_pretrained(UpperCAmelCase_) self.assertEqual(new_configuration.hidden_size , 768) def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: List[str] ="hf-internal-testing/test-two-configs" import transformers as new_transformers lowerCamelCase__: Dict ="v4.0.0" lowerCamelCase__ , lowerCamelCase__: Optional[int] =new_transformers.models.auto.AutoConfig.from_pretrained( UpperCAmelCase_ , return_unused_kwargs=UpperCAmelCase_) self.assertEqual(new_configuration.hidden_size , 2) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(UpperCAmelCase_ , {}) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers lowerCamelCase__: str ="v3.0.0" lowerCamelCase__: Tuple =old_transformers.models.auto.AutoConfig.from_pretrained(UpperCAmelCase_) self.assertEqual(old_configuration.hidden_size , 768)
10
'''simple docstring''' import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase_ ( a__ , unittest.TestCase ): __UpperCAmelCase = CLIPTokenizer __UpperCAmelCase = CLIPTokenizerFast __UpperCAmelCase = True __UpperCAmelCase = {} __UpperCAmelCase = False def __a ( self ): super().setUp() # fmt: off UpperCamelCase__ = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on UpperCamelCase__ = dict(zip(a , range(len(a ) ) ) ) UpperCamelCase__ = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] UpperCamelCase__ = {"unk_token": "<unk>"} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(a ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(a ) ) def __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def __a ( self , a ): UpperCamelCase__ = "lower newer" UpperCamelCase__ = "lower newer" return input_text, output_text def __a ( self ): UpperCamelCase__ = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = "lower newer" UpperCamelCase__ = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] UpperCamelCase__ = tokenizer.tokenize(a ) self.assertListEqual(a , a ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def __a ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = self.tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways UpperCamelCase__ = "xa\u0303y" + " " + "x\xe3y" UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type UpperCamelCase__ = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type UpperCamelCase__ = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def __a ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = "hello" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = f'''{text_of_1_token} {text_of_1_token}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) UpperCamelCase__ = f''' {text}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def __a ( self ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def __a ( self ): super().test_tokenization_python_rust_equals() def __a ( self ): # CLIP always lower cases letters pass
80
0
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
11
'''simple docstring''' import argparse import collections import json import os import re import string import sys import numpy as np a__ : Optional[int] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a__ : int = None def _UpperCamelCase ( ) -> Dict: '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0." ) parser.add_argument("data_file" , metavar="data.json" , help="Input data JSON file." ) parser.add_argument("pred_file" , metavar="pred.json" , help="Model predictions." ) parser.add_argument( "--out-file" , "-o" , metavar="eval.json" , help="Write accuracy metrics to file (default is stdout)." ) parser.add_argument( "--na-prob-file" , "-n" , metavar="na_prob.json" , help="Model estimates of probability of no answer." ) parser.add_argument( "--na-prob-thresh" , "-t" , type=__A , default=1.0 , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)." , ) parser.add_argument( "--out-image-dir" , "-p" , metavar="out_images" , default=__A , help="Save precision-recall curves to directory." ) parser.add_argument("--verbose" , "-v" , action="store_true" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = bool(qa["answers"]["text"] ) return qid_to_has_ans def _UpperCamelCase ( __A ) -> Optional[Any]: '''simple docstring''' def remove_articles(__A ): return ARTICLES_REGEX.sub(" " , __A ) def white_space_fix(__A ): return " ".join(text.split() ) def remove_punc(__A ): UpperCamelCase__ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__A ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__A ) ) ) ) def _UpperCamelCase ( __A ) -> int: '''simple docstring''' if not s: return [] return normalize_answer(__A ).split() def _UpperCamelCase ( __A , __A ) -> List[Any]: '''simple docstring''' return int(normalize_answer(__A ) == normalize_answer(__A ) ) def _UpperCamelCase ( __A , __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = collections.Counter(__A ) & collections.Counter(__A ) UpperCamelCase__ = sum(common.values() ) if len(__A ) == 0 or len(__A ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = (2 * precision * recall) / (precision + recall) return fa def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = qa["id"] UpperCamelCase__ = [t for t in qa["answers"]["text"] if normalize_answer(__A )] if not gold_answers: # For unanswerable questions, only correct answer is empty string UpperCamelCase__ = [""] if qid not in preds: print(F'''Missing prediction for {qid}''' ) continue UpperCamelCase__ = preds[qid] # Take max over all gold answers UpperCamelCase__ = max(compute_exact(__A , __A ) for a in gold_answers ) UpperCamelCase__ = max(compute_fa(__A , __A ) for a in gold_answers ) return exact_scores, fa_scores def _UpperCamelCase ( __A , __A , __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} for qid, s in scores.items(): UpperCamelCase__ = na_probs[qid] > na_prob_thresh if pred_na: UpperCamelCase__ = float(not qid_to_has_ans[qid] ) else: UpperCamelCase__ = s return new_scores def _UpperCamelCase ( __A , __A , __A=None ) -> List[Any]: '''simple docstring''' if not qid_list: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores.values() ) / total), ("f1", 100.0 * sum(fa_scores.values() ) / total), ("total", total), ] ) else: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("f1", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("total", total), ] ) def _UpperCamelCase ( __A , __A , __A ) -> Optional[int]: '''simple docstring''' for k in new_eval: UpperCamelCase__ = new_eval[k] def _UpperCamelCase ( __A , __A , __A , __A ) -> Optional[int]: '''simple docstring''' plt.step(__A , __A , color="b" , alpha=0.2 , where="post" ) plt.fill_between(__A , __A , step="post" , alpha=0.2 , color="b" ) plt.xlabel("Recall" ) plt.ylabel("Precision" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__A ) plt.savefig(__A ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A , __A=None , __A=None ) -> Any: '''simple docstring''' UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) UpperCamelCase__ = 0.0 UpperCamelCase__ = 1.0 UpperCamelCase__ = 0.0 UpperCamelCase__ = [1.0] UpperCamelCase__ = [0.0] UpperCamelCase__ = 0.0 for i, qid in enumerate(__A ): if qid_to_has_ans[qid]: true_pos += scores[qid] UpperCamelCase__ = true_pos / float(i + 1 ) UpperCamelCase__ = true_pos / float(__A ) if i == len(__A ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__A ) recalls.append(__A ) if out_image: plot_pr_curve(__A , __A , __A , __A ) return {"ap": 100.0 * avg_prec} def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if out_image_dir and not os.path.exists(__A ): os.makedirs(__A ) UpperCamelCase__ = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_exact.png" ) , title="Precision-Recall curve for Exact Match score" , ) UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_f1.png" ) , title="Precision-Recall curve for F1 score" , ) UpperCamelCase__ = {k: float(__A ) for k, v in qid_to_has_ans.items()} UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_oracle.png" ) , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)" , ) merge_eval(__A , __A , "pr_exact" ) merge_eval(__A , __A , "pr_f1" ) merge_eval(__A , __A , "pr_oracle" ) def _UpperCamelCase ( __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if not qid_list: return UpperCamelCase__ = [na_probs[k] for k in qid_list] UpperCamelCase__ = np.ones_like(__A ) / float(len(__A ) ) plt.hist(__A , weights=__A , bins=20 , range=(0.0, 1.0) ) plt.xlabel("Model probability of no-answer" ) plt.ylabel("Proportion of dataset" ) plt.title(F'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__A , F'''na_prob_hist_{name}.png''' ) ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A ) -> Tuple: '''simple docstring''' UpperCamelCase__ = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) UpperCamelCase__ = num_no_ans UpperCamelCase__ = cur_score UpperCamelCase__ = 0.0 UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) for i, qid in enumerate(__A ): if qid not in scores: continue if qid_to_has_ans[qid]: UpperCamelCase__ = scores[qid] else: if preds[qid]: UpperCamelCase__ = -1 else: UpperCamelCase__ = 0 cur_score += diff if cur_score > best_score: UpperCamelCase__ = cur_score UpperCamelCase__ = na_probs[qid] return 100.0 * best_score / len(__A ), best_thresh def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> Dict: '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ = best_exact UpperCamelCase__ = exact_thresh UpperCamelCase__ = best_fa UpperCamelCase__ = fa_thresh def _UpperCamelCase ( ) -> Any: '''simple docstring''' with open(OPTS.data_file ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = dataset_json["data"] with open(OPTS.pred_file ) as f: UpperCamelCase__ = json.load(__A ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: UpperCamelCase__ = json.load(__A ) else: UpperCamelCase__ = {k: 0.0 for k in preds} UpperCamelCase__ = make_qid_to_has_ans(__A ) # maps qid to True/False UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if v] UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if not v] UpperCamelCase__ , UpperCamelCase__ = get_raw_scores(__A , __A ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = make_eval_dict(__A , __A ) if has_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "HasAns" ) if no_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "NoAns" ) if OPTS.na_prob_file: find_all_best_thresh(__A , __A , __A , __A , __A , __A ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__A , __A , __A , __A , __A , OPTS.out_image_dir ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "hasAns" ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "noAns" ) if OPTS.out_file: with open(OPTS.out_file , "w" ) as f: json.dump(__A , __A ) else: print(json.dumps(__A , indent=2 ) ) if __name__ == "__main__": a__ : Optional[int] = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
80
0
from __future__ import annotations from math import pi, sqrt def lowerCamelCase__ ( A__ : float , A__ : float ): '''simple docstring''' if inductance <= 0: raise ValueError("""Inductance cannot be 0 or negative""" ) elif capacitance <= 0: raise ValueError("""Capacitance cannot be 0 or negative""" ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
12
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType a__ : Optional[List[str]] = None a__ : Dict = '<' if sys.byteorder == 'little' else '>' # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image a__ : Any = [ np.dtype('|b1'), np.dtype('|u1'), np.dtype('<u2'), np.dtype('>u2'), np.dtype('<i2'), np.dtype('>i2'), np.dtype('<u4'), np.dtype('>u4'), np.dtype('<i4'), np.dtype('>i4'), np.dtype('<f4'), np.dtype('>f4'), np.dtype('<f8'), np.dtype('>f8'), ] @dataclass class lowercase_ : __UpperCAmelCase = True __UpperCAmelCase = None # Automatically constructed __UpperCAmelCase = "PIL.Image.Image" __UpperCAmelCase = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) __UpperCAmelCase = field(default='Image' , init=a__ , repr=a__ ) def __call__( self ): return self.pa_type def __a ( self , a ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if isinstance(a , a ): UpperCamelCase__ = np.array(a ) if isinstance(a , a ): return {"path": value, "bytes": None} elif isinstance(a , a ): return {"path": None, "bytes": value} elif isinstance(a , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(a ) elif isinstance(a , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(a ) elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def __a ( self , a , a=None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Image(decode=True) instead." ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support decoding images, please install 'Pillow'." ) if token_per_repo_id is None: UpperCamelCase__ = {} UpperCamelCase__ , UpperCamelCase__ = value["path"], value["bytes"] if bytes_ is None: if path is None: raise ValueError(f'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) else: if is_local_path(a ): UpperCamelCase__ = PIL.Image.open(a ) else: UpperCamelCase__ = path.split("::" )[-1] try: UpperCamelCase__ = string_to_dict(a , config.HUB_DATASETS_URL )["repo_id"] UpperCamelCase__ = token_per_repo_id.get(a ) except ValueError: UpperCamelCase__ = None with xopen(a , "rb" , use_auth_token=a ) as f: UpperCamelCase__ = BytesIO(f.read() ) UpperCamelCase__ = PIL.Image.open(bytes_ ) else: UpperCamelCase__ = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __a ( self ): from .features import Value return ( self if self.decode else { "bytes": Value("binary" ), "path": Value("string" ), } ) def __a ( self , a ): if pa.types.is_string(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCamelCase__ = storage.field("bytes" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCamelCase__ = storage.field("path" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): UpperCamelCase__ = pa.array( [encode_np_array(np.array(a ) )["bytes"] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays( [bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def __a ( self , a ): @no_op_if_value_is_null def path_to_bytes(a ): with xopen(a , "rb" ) as f: UpperCamelCase__ = f.read() return bytes_ UpperCamelCase__ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCamelCase__ = pa.array( [os.path.basename(a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def _UpperCamelCase ( ) -> List[str]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() UpperCamelCase__ = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def _UpperCamelCase ( __A ) -> bytes: '''simple docstring''' UpperCamelCase__ = BytesIO() if image.format in list_image_compression_formats(): UpperCamelCase__ = image.format else: UpperCamelCase__ = "PNG" if image.mode in ["1", "L", "LA", "RGB", "RGBA"] else "TIFF" image.save(__A , format=__A ) return buffer.getvalue() def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if hasattr(__A , "filename" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) UpperCamelCase__ = array.dtype UpperCamelCase__ = dtype.byteorder if dtype.byteorder != "=" else _NATIVE_BYTEORDER UpperCamelCase__ = dtype.kind UpperCamelCase__ = dtype.itemsize UpperCamelCase__ = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: UpperCamelCase__ = np.dtype("|u1" ) if dtype_kind not in ["u", "i"]: raise TypeError( F'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.''' ) if dtype is not dest_dtype: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: UpperCamelCase__ = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: UpperCamelCase__ = dtype_byteorder + dtype_kind + str(__A ) UpperCamelCase__ = np.dtype(__A ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}''' ) UpperCamelCase__ = PIL.Image.fromarray(array.astype(__A ) ) return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> List[dict]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if objs: UpperCamelCase__ , UpperCamelCase__ = first_non_null_value(__A ) if isinstance(__A , __A ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__A , np.ndarray ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] elif isinstance(__A , PIL.Image.Image ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] else: return objs else: return objs
80
0
import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class __lowercase ( nn.Module ): """simple docstring""" _UpperCAmelCase : int _UpperCAmelCase : int _UpperCAmelCase : float = 0.0 _UpperCAmelCase : int = 1 _UpperCAmelCase : int = 1 _UpperCAmelCase : bool = True _UpperCAmelCase : bool = False _UpperCAmelCase : bool = False _UpperCAmelCase : bool = False _UpperCAmelCase : jnp.dtype = jnp.floataa def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: Any = [] SCREAMING_SNAKE_CASE_: str = [] for i in range(self.num_layers): SCREAMING_SNAKE_CASE_: Optional[Any] = self.in_channels if i == 0 else self.out_channels SCREAMING_SNAKE_CASE_: int = FlaxResnetBlockaD( in_channels=lowerCAmelCase__ , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: int = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[Any] = resnets SCREAMING_SNAKE_CASE_: str = attentions if self.add_downsample: SCREAMING_SNAKE_CASE_: List[Any] = FlaxDownsampleaD(self.out_channels , dtype=self.dtype) def __call__( self : Dict , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Dict , lowerCAmelCase__ : str=True): SCREAMING_SNAKE_CASE_: Optional[Any] = () for resnet, attn in zip(self.resnets , self.attentions): SCREAMING_SNAKE_CASE_: int = resnet(lowerCAmelCase__ , lowerCAmelCase__ , deterministic=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: str = attn(lowerCAmelCase__ , lowerCAmelCase__ , deterministic=lowerCAmelCase__) output_states += (hidden_states,) if self.add_downsample: SCREAMING_SNAKE_CASE_: Optional[Any] = self.downsamplers_a(lowerCAmelCase__) output_states += (hidden_states,) return hidden_states, output_states class __lowercase ( nn.Module ): """simple docstring""" _UpperCAmelCase : int _UpperCAmelCase : int _UpperCAmelCase : float = 0.0 _UpperCAmelCase : int = 1 _UpperCAmelCase : bool = True _UpperCAmelCase : jnp.dtype = jnp.floataa def _SCREAMING_SNAKE_CASE ( self : Optional[int]): SCREAMING_SNAKE_CASE_: List[str] = [] for i in range(self.num_layers): SCREAMING_SNAKE_CASE_: Optional[int] = self.in_channels if i == 0 else self.out_channels SCREAMING_SNAKE_CASE_: Union[str, Any] = FlaxResnetBlockaD( in_channels=lowerCAmelCase__ , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Union[str, Any] = resnets if self.add_downsample: SCREAMING_SNAKE_CASE_: Union[str, Any] = FlaxDownsampleaD(self.out_channels , dtype=self.dtype) def __call__( self : List[str] , lowerCAmelCase__ : int , lowerCAmelCase__ : str , lowerCAmelCase__ : int=True): SCREAMING_SNAKE_CASE_: int = () for resnet in self.resnets: SCREAMING_SNAKE_CASE_: Tuple = resnet(lowerCAmelCase__ , lowerCAmelCase__ , deterministic=lowerCAmelCase__) output_states += (hidden_states,) if self.add_downsample: SCREAMING_SNAKE_CASE_: Any = self.downsamplers_a(lowerCAmelCase__) output_states += (hidden_states,) return hidden_states, output_states class __lowercase ( nn.Module ): """simple docstring""" _UpperCAmelCase : int _UpperCAmelCase : int _UpperCAmelCase : int _UpperCAmelCase : float = 0.0 _UpperCAmelCase : int = 1 _UpperCAmelCase : int = 1 _UpperCAmelCase : bool = True _UpperCAmelCase : bool = False _UpperCAmelCase : bool = False _UpperCAmelCase : bool = False _UpperCAmelCase : jnp.dtype = jnp.floataa def _SCREAMING_SNAKE_CASE ( self : Optional[int]): SCREAMING_SNAKE_CASE_: int = [] SCREAMING_SNAKE_CASE_: List[Any] = [] for i in range(self.num_layers): SCREAMING_SNAKE_CASE_: int = self.in_channels if (i == self.num_layers - 1) else self.out_channels SCREAMING_SNAKE_CASE_: List[str] = self.prev_output_channel if i == 0 else self.out_channels SCREAMING_SNAKE_CASE_: Tuple = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: int = resnets SCREAMING_SNAKE_CASE_: Union[str, Any] = attentions if self.add_upsample: SCREAMING_SNAKE_CASE_: str = FlaxUpsampleaD(self.out_channels , dtype=self.dtype) def __call__( self : List[str] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : str , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict=True): for resnet, attn in zip(self.resnets , self.attentions): # pop res hidden states SCREAMING_SNAKE_CASE_: Tuple = res_hidden_states_tuple[-1] SCREAMING_SNAKE_CASE_: int = res_hidden_states_tuple[:-1] SCREAMING_SNAKE_CASE_: Tuple = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1) SCREAMING_SNAKE_CASE_: Tuple = resnet(lowerCAmelCase__ , lowerCAmelCase__ , deterministic=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[Any] = attn(lowerCAmelCase__ , lowerCAmelCase__ , deterministic=lowerCAmelCase__) if self.add_upsample: SCREAMING_SNAKE_CASE_: str = self.upsamplers_a(lowerCAmelCase__) return hidden_states class __lowercase ( nn.Module ): """simple docstring""" _UpperCAmelCase : int _UpperCAmelCase : int _UpperCAmelCase : int _UpperCAmelCase : float = 0.0 _UpperCAmelCase : int = 1 _UpperCAmelCase : bool = True _UpperCAmelCase : jnp.dtype = jnp.floataa def _SCREAMING_SNAKE_CASE ( self : List[Any]): SCREAMING_SNAKE_CASE_: str = [] for i in range(self.num_layers): SCREAMING_SNAKE_CASE_: int = self.in_channels if (i == self.num_layers - 1) else self.out_channels SCREAMING_SNAKE_CASE_: List[str] = self.prev_output_channel if i == 0 else self.out_channels SCREAMING_SNAKE_CASE_: Dict = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: int = resnets if self.add_upsample: SCREAMING_SNAKE_CASE_: Dict = FlaxUpsampleaD(self.out_channels , dtype=self.dtype) def __call__( self : int , lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Union[str, Any]=True): for resnet in self.resnets: # pop res hidden states SCREAMING_SNAKE_CASE_: Union[str, Any] = res_hidden_states_tuple[-1] SCREAMING_SNAKE_CASE_: int = res_hidden_states_tuple[:-1] SCREAMING_SNAKE_CASE_: Optional[Any] = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1) SCREAMING_SNAKE_CASE_: Dict = resnet(lowerCAmelCase__ , lowerCAmelCase__ , deterministic=lowerCAmelCase__) if self.add_upsample: SCREAMING_SNAKE_CASE_: Optional[Any] = self.upsamplers_a(lowerCAmelCase__) return hidden_states class __lowercase ( nn.Module ): """simple docstring""" _UpperCAmelCase : int _UpperCAmelCase : float = 0.0 _UpperCAmelCase : int = 1 _UpperCAmelCase : int = 1 _UpperCAmelCase : bool = False _UpperCAmelCase : bool = False _UpperCAmelCase : jnp.dtype = jnp.floataa def _SCREAMING_SNAKE_CASE ( self : List[Any]): # there is always at least one resnet SCREAMING_SNAKE_CASE_: Union[str, Any] = [ FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) ] SCREAMING_SNAKE_CASE_: List[Any] = [] for _ in range(self.num_layers): SCREAMING_SNAKE_CASE_: str = FlaxTransformeraDModel( in_channels=self.in_channels , n_heads=self.num_attention_heads , d_head=self.in_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Any = FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[Any] = resnets SCREAMING_SNAKE_CASE_: Dict = attentions def __call__( self : Optional[int] , lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Tuple=True): SCREAMING_SNAKE_CASE_: Optional[int] = self.resnets[0](lowerCAmelCase__ , lowerCAmelCase__) for attn, resnet in zip(self.attentions , self.resnets[1:]): SCREAMING_SNAKE_CASE_: Any = attn(lowerCAmelCase__ , lowerCAmelCase__ , deterministic=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Any = resnet(lowerCAmelCase__ , lowerCAmelCase__ , deterministic=lowerCAmelCase__) return hidden_states
13
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> int: '''simple docstring''' if depth < 0: raise ValueError("Depth cannot be less than 0" ) if not scores: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) ) def _UpperCamelCase ( ) -> None: '''simple docstring''' UpperCamelCase__ = [90, 23, 6, 33, 21, 65, 123, 34423] UpperCamelCase__ = math.log(len(__A ) , 2 ) print(F'''Optimal value : {minimax(0 , 0 , __A , __A , __A )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
80
0
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint _lowerCamelCase : Tuple = { """169M""": 12, """430M""": 24, """1B5""": 24, """3B""": 32, """7B""": 32, """14B""": 40, } _lowerCamelCase : List[Any] = { """169M""": 768, """430M""": 1024, """1B5""": 2048, """3B""": 2560, """7B""": 4096, """14B""": 5120, } def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" A__ = list(state_dict.keys() ) for name in state_dict_keys: A__ = state_dict.pop(lowercase_ ) # emb -> embedding if name.startswith('''emb.''' ): A__ = name.replace('''emb.''' , '''embeddings.''' ) # ln_0 -> pre_ln (only present at block 0) if name.startswith('''blocks.0.ln0''' ): A__ = name.replace('''blocks.0.ln0''' , '''blocks.0.pre_ln''' ) # att -> attention A__ = re.sub(R'''blocks\.(\d+)\.att''' , R'''blocks.\1.attention''' , lowercase_ ) # ffn -> feed_forward A__ = re.sub(R'''blocks\.(\d+)\.ffn''' , R'''blocks.\1.feed_forward''' , lowercase_ ) # time_mix_k -> time_mix_key and reshape if name.endswith('''.time_mix_k''' ): A__ = name.replace('''.time_mix_k''' , '''.time_mix_key''' ) # time_mix_v -> time_mix_value and reshape if name.endswith('''.time_mix_v''' ): A__ = name.replace('''.time_mix_v''' , '''.time_mix_value''' ) # time_mix_r -> time_mix_key and reshape if name.endswith('''.time_mix_r''' ): A__ = name.replace('''.time_mix_r''' , '''.time_mix_receptance''' ) if name != "head.weight": A__ = '''rwkv.''' + name A__ = weight return state_dict def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_=None , lowercase_=None , lowercase_=False , lowercase_=None ) -> Any: """simple docstring""" if tokenizer_file is None: print('''No `--tokenizer_file` provided, we will use the default tokenizer.''' ) A__ = 50_277 A__ = AutoTokenizer.from_pretrained('''EleutherAI/gpt-neox-20b''' ) else: A__ = PreTrainedTokenizerFast(tokenizer_file=lowercase_ ) A__ = len(lowercase_ ) tokenizer.save_pretrained(lowercase_ ) # 2. Build the config A__ = list(NUM_HIDDEN_LAYERS_MAPPING.keys() ) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: A__ = candidate break if size is None: raise ValueError('''Could not infer the size, please provide it with the `--size` argument.''' ) if size not in possible_sizes: raise ValueError(f"""`size` should be one of {possible_sizes}, got {size}.""" ) A__ = RwkvConfig( vocab_size=lowercase_ , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(lowercase_ ) # 3. Download model file then convert state_dict A__ = hf_hub_download(lowercase_ , lowercase_ ) A__ = torch.load(lowercase_ , map_location='''cpu''' ) A__ = convert_state_dict(lowercase_ ) # 4. Split in shards and save A__ , A__ = shard_checkpoint(lowercase_ ) for shard_file, shard in shards.items(): torch.save(lowercase_ , os.path.join(lowercase_ , lowercase_ ) ) if index is not None: A__ = os.path.join(lowercase_ , lowercase_ ) # Save the index as well with open(lowercase_ , '''w''' , encoding='''utf-8''' ) as f: A__ = json.dumps(lowercase_ , indent=2 , sort_keys=lowercase_ ) + '''\n''' f.write(lowercase_ ) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( '''Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.''' ) A__ = list(shards.keys() ) del state_dict del shards gc.collect() for shard_file in shard_files: A__ = torch.load(os.path.join(lowercase_ , lowercase_ ) ) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(lowercase_ , lowercase_ ) ) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('''Please provide a `model_name` to push the model to the Hub.''' ) A__ = AutoModelForCausalLM.from_pretrained(lowercase_ ) model.push_to_hub(lowercase_ , max_shard_size='''2GB''' ) tokenizer.push_to_hub(lowercase_ ) if __name__ == "__main__": _lowerCamelCase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--repo_id""", default=None, type=str, required=True, help="""Repo ID from which to pull the checkpoint.""" ) parser.add_argument( """--checkpoint_file""", default=None, type=str, required=True, help="""Name of the checkpoint file in the repo.""" ) parser.add_argument( """--output_dir""", default=None, type=str, required=True, help="""Where to save the converted model.""" ) parser.add_argument( """--tokenizer_file""", default=None, type=str, help="""Path to the tokenizer file to use (if not provided, only the model is converted).""", ) parser.add_argument( """--size""", default=None, type=str, help="""Size of the model. Will be inferred from the `checkpoint_file` if not passed.""", ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Push to the Hub the converted model.""", ) parser.add_argument( """--model_name""", default=None, type=str, help="""Name of the pushed model on the Hub, including the username / organization.""", ) _lowerCamelCase : str = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
14
'''simple docstring''' def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def _UpperCamelCase ( __A = 100 ) -> int: '''simple docstring''' UpperCamelCase__ = 1 UpperCamelCase__ = 2 for i in range(2 , max_n + 1 ): UpperCamelCase__ = pre_numerator UpperCamelCase__ = 2 * i // 3 if i % 3 == 0 else 1 UpperCamelCase__ = cur_numerator UpperCamelCase__ = e_cont * pre_numerator + temp return sum_digits(__A ) if __name__ == "__main__": print(F"""{solution() = }""")
80
0
from typing import List import numpy as np def UpperCAmelCase ( a_ ) -> int: """simple docstring""" __A = {key: len(a_ ) for key, value in gen_kwargs.items() if isinstance(a_ , a_ )} if len(set(lists_lengths.values() ) ) > 1: raise RuntimeError( ( "Sharding is ambiguous for this dataset: " + "we found several data sources lists of different lengths, and we don't know over which list we should parallelize:\n" + "\n".join(F'''\t- key {key} has length {length}''' for key, length in lists_lengths.items() ) + "\nTo fix this, check the 'gen_kwargs' and make sure to use lists only for data sources, " + "and use tuples otherwise. In the end there should only be one single list, or several lists with the same length." ) ) __A = max(lists_lengths.values() , default=0 ) return max(1 , a_ ) def UpperCAmelCase ( a_ , a_ ) -> List[range]: """simple docstring""" __A = [] for group_idx in range(a_ ): __A = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs)) if num_shards_to_add == 0: break __A = shards_indices_per_group[-1].stop if shards_indices_per_group else 0 __A = range(a_ , start + num_shards_to_add ) shards_indices_per_group.append(a_ ) return shards_indices_per_group def UpperCAmelCase ( a_ , a_ ) -> List[dict]: """simple docstring""" __A = _number_of_shards_in_gen_kwargs(a_ ) if num_shards == 1: return [dict(a_ )] else: __A = _distribute_shards(num_shards=a_ , max_num_jobs=a_ ) return [ { key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]] if isinstance(a_ , a_ ) else value for key, value in gen_kwargs.items() } for group_idx in range(len(a_ ) ) ] def UpperCAmelCase ( a_ ) -> dict: """simple docstring""" return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key] , a_ ) else gen_kwargs_list[0][key] for key in gen_kwargs_list[0] } def UpperCAmelCase ( a_ , a_ ) -> dict: """simple docstring""" __A = {len(a_ ) for value in gen_kwargs.values() if isinstance(a_ , a_ )} __A = {} for size in list_sizes: __A = list(range(a_ ) ) rng.shuffle(indices_per_size[size] ) # Now let's copy the gen_kwargs and shuffle the lists based on their sizes __A = dict(a_ ) for key, value in shuffled_kwargs.items(): if isinstance(a_ , a_ ): __A = [value[i] for i in indices_per_size[len(a_ )]] return shuffled_kwargs
15
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' with open(__A ) as metadata_file: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = LukeConfig(use_entity_aware_attention=__A , **metadata["model_config"] ) # Load in the weights from the checkpoint_path UpperCamelCase__ = torch.load(__A , map_location="cpu" )["module"] # Load the entity vocab file UpperCamelCase__ = load_original_entity_vocab(__A ) # add an entry for [MASK2] UpperCamelCase__ = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase__ = XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase__ = AddedToken("<ent>" , lstrip=__A , rstrip=__A ) UpperCamelCase__ = AddedToken("<ent2>" , lstrip=__A , rstrip=__A ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'''Saving tokenizer to {pytorch_dump_folder_path}''' ) tokenizer.save_pretrained(__A ) with open(os.path.join(__A , "tokenizer_config.json" ) , "r" ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = "MLukeTokenizer" with open(os.path.join(__A , "tokenizer_config.json" ) , "w" ) as f: json.dump(__A , __A ) with open(os.path.join(__A , MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(__A , __A ) UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) # Initialize the embeddings of the special tokens UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["@"] )[0] UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["#"] )[0] UpperCamelCase__ = state_dict["embeddings.word_embeddings.weight"] UpperCamelCase__ = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase__ = state_dict[bias_name] UpperCamelCase__ = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: UpperCamelCase__ = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase__ = state_dict["entity_embeddings.entity_embeddings.weight"] UpperCamelCase__ = entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase__ = state_dict["entity_predictions.bias"] UpperCamelCase__ = entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase__ = LukeForMaskedLM(config=__A ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) UpperCamelCase__ = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): UpperCamelCase__ = state_dict[key] else: UpperCamelCase__ = state_dict[key] UpperCamelCase__ , UpperCamelCase__ = model.load_state_dict(__A , strict=__A ) if set(__A ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(__A ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A , task="entity_classification" ) UpperCamelCase__ = "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." UpperCamelCase__ = (0, 9) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 33, 768) ) UpperCamelCase__ = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}''' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 1, 768) ) UpperCamelCase__ = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is''' F''' {expected_shape}''' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) UpperCamelCase__ = "Tokyo is the capital of <mask>." UpperCamelCase__ = (24, 30) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) UpperCamelCase__ = encoding["input_ids"][0].tolist() UpperCamelCase__ = input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) UpperCamelCase__ = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(__A ) UpperCamelCase__ = outputs.entity_logits[0][0].argmax().item() UpperCamelCase__ = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(__A ) ) model.save_pretrained(__A ) def _UpperCamelCase ( __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = ["[MASK]", "[PAD]", "[UNK]"] UpperCamelCase__ = [json.loads(__A ) for line in open(__A )] UpperCamelCase__ = {} for entry in data: UpperCamelCase__ = entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase__ = entity_id break UpperCamelCase__ = F'''{language}:{entity_name}''' UpperCamelCase__ = entity_id return new_mapping if __name__ == "__main__": a__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) a__ : Any = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
80
0
"""simple docstring""" from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar lowerCAmelCase_ = TypeVar('T') lowerCAmelCase_ = TypeVar('U') class __A ( Generic[T, U] ): '''simple docstring''' def __init__( self : Any ,_snake_case : T | None ,_snake_case : U | None ) -> int: """simple docstring""" lowercase__ : Union[str, Any] = key lowercase__ : Dict = val lowercase__ : DoubleLinkedListNode[T, U] | None = None lowercase__ : DoubleLinkedListNode[T, U] | None = None def __repr__( self : Any ) -> str: """simple docstring""" return ( f"""Node: key: {self.key}, val: {self.val}, """ f"""has next: {bool(self.next )}, has prev: {bool(self.prev )}""" ) class __A ( Generic[T, U] ): '''simple docstring''' def __init__( self : List[str] ) -> None: """simple docstring""" lowercase__ : DoubleLinkedListNode[T, U] = DoubleLinkedListNode(_snake_case ,_snake_case ) lowercase__ : DoubleLinkedListNode[T, U] = DoubleLinkedListNode(_snake_case ,_snake_case ) lowercase__ , lowercase__ : Any = self.rear, self.head def __repr__( self : Optional[Any] ) -> str: """simple docstring""" lowercase__ : Any = ['''DoubleLinkedList'''] lowercase__ : Dict = self.head while node.next is not None: rep.append(str(_snake_case ) ) lowercase__ : str = node.next rep.append(str(self.rear ) ) return ",\n ".join(_snake_case ) def UpperCAmelCase ( self : int ,_snake_case : DoubleLinkedListNode[T, U] ) -> None: """simple docstring""" lowercase__ : Dict = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None lowercase__ : str = node lowercase__ : str = previous lowercase__ : List[Any] = node lowercase__ : Tuple = self.rear def UpperCAmelCase ( self : Optional[Any] ,_snake_case : DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: """simple docstring""" if node.prev is None or node.next is None: return None lowercase__ : Dict = node.next lowercase__ : Any = node.prev lowercase__ : int = None lowercase__ : int = None return node class __A ( Generic[T, U] ): '''simple docstring''' lowerCAmelCase : dict[Callable[[T], U], LRUCache[T, U]] = {} def __init__( self : Any ,_snake_case : int ) -> Any: """simple docstring""" lowercase__ : DoubleLinkedList[T, U] = DoubleLinkedList() lowercase__ : Optional[Any] = capacity lowercase__ : Tuple = 0 lowercase__ : List[str] = 0 lowercase__ : Dict = 0 lowercase__ : dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__( self : str ) -> str: """simple docstring""" return ( f"""CacheInfo(hits={self.hits}, misses={self.miss}, """ f"""capacity={self.capacity}, current size={self.num_keys})""" ) def __contains__( self : Optional[int] ,_snake_case : T ) -> bool: """simple docstring""" return key in self.cache def UpperCAmelCase ( self : Any ,_snake_case : T ) -> U | None: """simple docstring""" if key in self.cache: self.hits += 1 lowercase__ : DoubleLinkedListNode[T, U] = self.cache[key] lowercase__ : Dict = self.list.remove(self.cache[key] ) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(_snake_case ) return node.val self.miss += 1 return None def UpperCAmelCase ( self : int ,_snake_case : T ,_snake_case : U ) -> None: """simple docstring""" if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity lowercase__ : Dict = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(_snake_case ) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 lowercase__ : Union[str, Any] = DoubleLinkedListNode(_snake_case ,_snake_case ) self.list.add(self.cache[key] ) self.num_keys += 1 else: # bump node to the end of the list, update value lowercase__ : List[str] = self.list.remove(self.cache[key] ) assert node is not None # node guaranteed to be in list lowercase__ : str = value self.list.add(_snake_case ) @classmethod def UpperCAmelCase ( cls : Union[str, Any] ,_snake_case : int = 128 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: """simple docstring""" def cache_decorator_inner(_snake_case : Callable[[T], U] ) -> Callable[..., U]: def cache_decorator_wrapper(*_snake_case : T ) -> U: if func not in cls.decorator_function_to_instance_map: lowercase__ : Tuple = LRUCache(_snake_case ) lowercase__ : Union[str, Any] = cls.decorator_function_to_instance_map[func].get(args[0] ) if result is None: lowercase__ : List[str] = func(*_snake_case ) cls.decorator_function_to_instance_map[func].put(args[0] ,_snake_case ) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(_snake_case ,'''cache_info''' ,_snake_case ) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
16
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Any = logging.get_logger(__name__) a__ : str = { 'SCUT-DLVCLab/lilt-roberta-en-base': ( 'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json' ), } class lowercase_ ( a__ ): __UpperCAmelCase = 'lilt' def __init__( self , a=3_05_22 , a=7_68 , a=12 , a=12 , a=30_72 , a="gelu" , a=0.1 , a=0.1 , a=5_12 , a=2 , a=0.02 , a=1e-12 , a=0 , a="absolute" , a=None , a=4 , a=10_24 , **a , ): super().__init__(pad_token_id=a , **a ) UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = position_embedding_type UpperCamelCase__ = classifier_dropout UpperCamelCase__ = channel_shrink_ratio UpperCamelCase__ = max_ad_position_embeddings
80
0
"""simple docstring""" import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration _a = 50_00_00 _a , _a = os.path.split(__file__) _a = os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json')) @get_duration def _A ( UpperCamelCase_ : datasets.Dataset, **UpperCamelCase_ : Tuple) -> Optional[Any]: '''simple docstring''' __lowercase = dataset.map(**UpperCamelCase_) @get_duration def _A ( UpperCamelCase_ : datasets.Dataset, **UpperCamelCase_ : str) -> Tuple: '''simple docstring''' __lowercase = dataset.filter(**UpperCamelCase_) def _A ( ) -> Optional[int]: '''simple docstring''' __lowercase = {"num examples": SPEED_TEST_N_EXAMPLES} with tempfile.TemporaryDirectory() as tmp_dir: __lowercase = datasets.Features({"text": datasets.Value("string"), "numbers": datasets.Value("float32")}) __lowercase = generate_example_dataset( os.path.join(UpperCamelCase_, "dataset.arrow"), UpperCamelCase_, num_examples=UpperCamelCase_) __lowercase = transformers.AutoTokenizer.from_pretrained("bert-base-cased", use_fast=UpperCamelCase_) def tokenize(UpperCamelCase_ : int): return tokenizer(examples["text"]) __lowercase = map(UpperCamelCase_) __lowercase = map(UpperCamelCase_, batched=UpperCamelCase_) __lowercase = map(UpperCamelCase_, function=lambda UpperCamelCase_: None, batched=UpperCamelCase_) with dataset.formatted_as(type="numpy"): __lowercase = map(UpperCamelCase_, function=lambda UpperCamelCase_: None, batched=UpperCamelCase_) with dataset.formatted_as(type="pandas"): __lowercase = map(UpperCamelCase_, function=lambda UpperCamelCase_: None, batched=UpperCamelCase_) with dataset.formatted_as(type="torch", columns="numbers"): __lowercase = map(UpperCamelCase_, function=lambda UpperCamelCase_: None, batched=UpperCamelCase_) with dataset.formatted_as(type="tensorflow", columns="numbers"): __lowercase = map(UpperCamelCase_, function=lambda UpperCamelCase_: None, batched=UpperCamelCase_) __lowercase = map(UpperCamelCase_, function=UpperCamelCase_, batched=UpperCamelCase_) __lowercase = filter(UpperCamelCase_) # Activate later when tokenizer support batched inputs # with dataset.formatted_as(type='numpy'): # times[func.__name__ + " fast-tokenizer batched numpy"] = func(dataset, function=tokenize, batched=True) with open(UpperCamelCase_, "wb") as f: f.write(json.dumps(UpperCamelCase_).encode("utf-8")) if __name__ == "__main__": # useful to run the profiler benchmark_map_filter()
17
'''simple docstring''' a__ : Union[str, Any] = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution a__ : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 a__ : Optional[Any] = True a__ : Optional[Any] = False def _UpperCamelCase ( __A ) -> bool: '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__A ) ) UpperCamelCase__ = number_chain while number < 10000000: UpperCamelCase__ = number_chain number *= 10 return number_chain def _UpperCamelCase ( __A = 10000000 ) -> int: '''simple docstring''' for i in range(1 , __A ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__A ) if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution() = }""")
80
0
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar __lowerCamelCase : Union[str, Any] = TypeVar('''T''') def _snake_case ( lowerCAmelCase : int ): """simple docstring""" return (position - 1) // 2 def _snake_case ( lowerCAmelCase : int ): """simple docstring""" return (2 * position) + 1 def _snake_case ( lowerCAmelCase : int ): """simple docstring""" return (2 * position) + 2 class a__ ( Generic[T] ): def __init__( self : str ): """simple docstring""" SCREAMING_SNAKE_CASE_ : list[tuple[T, int]] = [] SCREAMING_SNAKE_CASE_ : dict[T, int] = {} SCREAMING_SNAKE_CASE_ : int = 0 def __len__( self : List[str] ): """simple docstring""" return self.elements def __repr__( self : Dict ): """simple docstring""" return str(self.heap ) def __UpperCamelCase ( self : int ): """simple docstring""" return self.elements == 0 def __UpperCamelCase ( self : str,_A : T,_A : int ): """simple docstring""" self.heap.append((elem, weight) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.elements self.elements += 1 self._bubble_up(_A ) def __UpperCamelCase ( self : List[Any] ): """simple docstring""" if self.elements > 1: self._swap_nodes(0,self.elements - 1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.heap[0] self._bubble_down(_A ) return elem def __UpperCamelCase ( self : Union[str, Any],_A : T,_A : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.position_map[elem] SCREAMING_SNAKE_CASE_ : int = (elem, weight) if position > 0: SCREAMING_SNAKE_CASE_ : int = get_parent_position(_A ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = self.heap[parent_position] if parent_weight > weight: self._bubble_up(_A ) else: self._bubble_down(_A ) else: self._bubble_down(_A ) def __UpperCamelCase ( self : List[Any],_A : T ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.position_map[elem] if curr_pos == 0: return None SCREAMING_SNAKE_CASE_ : Tuple = get_parent_position(_A ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = self.heap[curr_pos] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(_A,_A ) return self._bubble_up(_A ) return None def __UpperCamelCase ( self : Optional[Any],_A : T ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.position_map[elem] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self.heap[curr_pos] SCREAMING_SNAKE_CASE_ : Optional[int] = get_child_left_position(_A ) SCREAMING_SNAKE_CASE_ : int = get_child_right_position(_A ) if child_left_position < self.elements and child_right_position < self.elements: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self.heap[child_left_position] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(_A,_A ) return self._bubble_down(_A ) if child_left_position < self.elements: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(_A,_A ) return self._bubble_down(_A ) else: return None if child_right_position < self.elements: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(_A,_A ) return self._bubble_down(_A ) return None def __UpperCamelCase ( self : Optional[int],_A : int,_A : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.heap[nodea_pos][0] SCREAMING_SNAKE_CASE_ : List[Any] = self.heap[nodea_pos][0] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = ( self.heap[nodea_pos], self.heap[nodea_pos], ) SCREAMING_SNAKE_CASE_ : Tuple = nodea_pos SCREAMING_SNAKE_CASE_ : List[Any] = nodea_pos class a__ ( Generic[T] ): def __init__( self : Any ): """simple docstring""" SCREAMING_SNAKE_CASE_ : dict[T, dict[T, int]] = {} SCREAMING_SNAKE_CASE_ : int = 0 def __repr__( self : Optional[Any] ): """simple docstring""" return str(self.connections ) def __len__( self : str ): """simple docstring""" return self.nodes def __UpperCamelCase ( self : Tuple,_A : T ): """simple docstring""" if node not in self.connections: SCREAMING_SNAKE_CASE_ : Optional[int] = {} self.nodes += 1 def __UpperCamelCase ( self : Tuple,_A : T,_A : T,_A : int ): """simple docstring""" self.add_node(_A ) self.add_node(_A ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = weight SCREAMING_SNAKE_CASE_ : Union[str, Any] = weight def _snake_case ( lowerCAmelCase : GraphUndirectedWeighted[T] , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : dict[T, int] = {node: maxsize for node in graph.connections} SCREAMING_SNAKE_CASE_ : dict[T, T | None] = {node: None for node in graph.connections} SCREAMING_SNAKE_CASE_ : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(lowerCAmelCase , lowerCAmelCase ) if priority_queue.is_empty(): return dist, parent # initialization SCREAMING_SNAKE_CASE_ : Optional[Any] = priority_queue.extract_min() SCREAMING_SNAKE_CASE_ : Dict = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: SCREAMING_SNAKE_CASE_ : int = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCAmelCase , dist[neighbour] ) SCREAMING_SNAKE_CASE_ : Optional[int] = node # running prim's algorithm while not priority_queue.is_empty(): SCREAMING_SNAKE_CASE_ : Any = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: SCREAMING_SNAKE_CASE_ : Dict = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCAmelCase , dist[neighbour] ) SCREAMING_SNAKE_CASE_ : int = node return dist, parent
18
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def _UpperCamelCase ( __A , __A , __A=1024 , __A=1024 , __A=False , **__A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = AutoTokenizer.from_pretrained(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="train" , **__A ) UpperCamelCase__ = tok.pad_token_id def get_lens(__A ): UpperCamelCase__ = tqdm( DataLoader(__A , batch_size=512 , num_workers=8 , shuffle=__A , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) UpperCamelCase__ = [] for batch in dl: UpperCamelCase__ = batch["input_ids"].ne(__A ).sum(1 ).tolist() UpperCamelCase__ = batch["labels"].ne(__A ).sum(1 ).tolist() if consider_target: for src, tgt in zip(__A , __A ): max_lens.append(max(__A , __A ) ) else: max_lens.extend(__A ) return max_lens UpperCamelCase__ = get_lens(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="val" , **__A ) UpperCamelCase__ = get_lens(__A ) pickle_save(__A , train_ds.len_file ) pickle_save(__A , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
80
0
import argparse import os import re __A ='''src/diffusers''' # Pattern that looks at the indentation in a line. __A =re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A =re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A =re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A =re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A =re.compile(R'''\[([^\]]+)\]''') def lowerCamelCase_ ( lowerCamelCase__ ): lowerCamelCase_ = _re_indent.search(lowerCamelCase__ ) return "" if search is None else search.groups()[0] def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__="" , lowerCamelCase__=None , lowerCamelCase__=None ): lowerCamelCase_ = 0 lowerCamelCase_ = code.split("\n" ) if start_prompt is not None: while not lines[index].startswith(lowerCamelCase__ ): index += 1 lowerCamelCase_ = ["\n".join(lines[:index] )] else: lowerCamelCase_ = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowerCamelCase_ = [lines[index]] index += 1 while index < len(lowerCamelCase__ ) and (end_prompt is None or not lines[index].startswith(lowerCamelCase__ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(lowerCamelCase__ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + " " ): current_block.append(lines[index] ) blocks.append("\n".join(lowerCamelCase__ ) ) if index < len(lowerCamelCase__ ) - 1: lowerCamelCase_ = [lines[index + 1]] index += 1 else: lowerCamelCase_ = [] else: blocks.append("\n".join(lowerCamelCase__ ) ) lowerCamelCase_ = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(lowerCamelCase__ ) > 0: blocks.append("\n".join(lowerCamelCase__ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(lowerCamelCase__ ): blocks.append("\n".join(lines[index:] ) ) return blocks def lowerCamelCase_ ( lowerCamelCase__ ): def _inner(lowerCamelCase__ ): return key(lowerCamelCase__ ).lower().replace("_" , "" ) return _inner def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__=None ): # If no key is provided, we use a noop. def noop(lowerCamelCase__ ): return x if key is None: lowerCamelCase_ = noop # Constants are all uppercase, they go first. lowerCamelCase_ = [obj for obj in objects if key(lowerCamelCase__ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowerCamelCase_ = [obj for obj in objects if key(lowerCamelCase__ )[0].isupper() and not key(lowerCamelCase__ ).isupper()] # Functions begin with a lowercase, they go last. lowerCamelCase_ = [obj for obj in objects if not key(lowerCamelCase__ )[0].isupper()] lowerCamelCase_ = ignore_underscore(lowerCamelCase__ ) return sorted(lowerCamelCase__ , key=lowerCamelCase__ ) + sorted(lowerCamelCase__ , key=lowerCamelCase__ ) + sorted(lowerCamelCase__ , key=lowerCamelCase__ ) def lowerCamelCase_ ( lowerCamelCase__ ): # This inner function sort imports between [ ]. def _replace(lowerCamelCase__ ): lowerCamelCase_ = match.groups()[0] if "," not in imports: return F'[{imports}]' lowerCamelCase_ = [part.strip().replace("\"" , "" ) for part in imports.split("," )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase_ = keys[:-1] return "[" + ", ".join([F'"{k}"' for k in sort_objects(lowerCamelCase__ )] ) + "]" lowerCamelCase_ = import_statement.split("\n" ) if len(lowerCamelCase__ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. lowerCamelCase_ = 2 if lines[1].strip() == "[" else 1 lowerCamelCase_ = [(i, _re_strip_line.search(lowerCamelCase__ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowerCamelCase_ = sort_objects(lowerCamelCase__ , key=lambda lowerCamelCase__ : x[1] ) lowerCamelCase_ = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(lowerCamelCase__ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: lowerCamelCase_ = _re_bracket_content.sub(_replace , lines[1] ) else: lowerCamelCase_ = [part.strip().replace("\"" , "" ) for part in lines[1].split("," )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase_ = keys[:-1] lowerCamelCase_ = get_indent(lines[1] ) + ", ".join([F'"{k}"' for k in sort_objects(lowerCamelCase__ )] ) return "\n".join(lowerCamelCase__ ) else: # Finally we have to deal with imports fitting on one line lowerCamelCase_ = _re_bracket_content.sub(_replace , lowerCamelCase__ ) return import_statement def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__=True ): with open(lowerCamelCase__ , "r" ) as f: lowerCamelCase_ = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowerCamelCase_ = split_code_in_indented_blocks( lowerCamelCase__ , start_prompt="_import_structure = {" , end_prompt="if TYPE_CHECKING:" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(lowerCamelCase__ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowerCamelCase_ = main_blocks[block_idx] lowerCamelCase_ = block.split("\n" ) # Get to the start of the imports. lowerCamelCase_ = 0 while line_idx < len(lowerCamelCase__ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: lowerCamelCase_ = len(lowerCamelCase__ ) else: line_idx += 1 if line_idx >= len(lowerCamelCase__ ): continue # Ignore beginning and last line: they don't contain anything. lowerCamelCase_ = "\n".join(block_lines[line_idx:-1] ) lowerCamelCase_ = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowerCamelCase_ = split_code_in_indented_blocks(lowerCamelCase__ , indent_level=lowerCamelCase__ ) # We have two categories of import key: list or _import_structure[key].append/extend lowerCamelCase_ = _re_direct_key if "_import_structure" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. lowerCamelCase_ = [(pattern.search(lowerCamelCase__ ).groups()[0] if pattern.search(lowerCamelCase__ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. lowerCamelCase_ = [(i, key) for i, key in enumerate(lowerCamelCase__ ) if key is not None] lowerCamelCase_ = [x[0] for x in sorted(lowerCamelCase__ , key=lambda lowerCamelCase__ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. lowerCamelCase_ = 0 lowerCamelCase_ = [] for i in range(len(lowerCamelCase__ ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: lowerCamelCase_ = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(lowerCamelCase__ ) count += 1 # And we put our main block back together with its first and last line. lowerCamelCase_ = "\n".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(lowerCamelCase__ ): if check_only: return True else: print(F'Overwriting {file}.' ) with open(lowerCamelCase__ , "w" ) as f: f.write("\n".join(lowerCamelCase__ ) ) def lowerCamelCase_ ( lowerCamelCase__=True ): lowerCamelCase_ = [] for root, _, files in os.walk(lowerCamelCase__ ): if "__init__.py" in files: lowerCamelCase_ = sort_imports(os.path.join(lowerCamelCase__ , "__init__.py" ) , check_only=lowerCamelCase__ ) if result: lowerCamelCase_ = [os.path.join(lowerCamelCase__ , "__init__.py" )] if len(lowerCamelCase__ ) > 0: raise ValueError(F'Would overwrite {len(lowerCamelCase__ )} files, run `make style`.' ) if __name__ == "__main__": __A =argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A =parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
19
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer a__ : int = logging.get_logger(__name__) a__ : List[str] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a__ : List[Any] = { 'vocab_file': { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt' ), } } a__ : Optional[Any] = { 'junnyu/roformer_chinese_small': 1_5_3_6, 'junnyu/roformer_chinese_base': 1_5_3_6, 'junnyu/roformer_chinese_char_small': 5_1_2, 'junnyu/roformer_chinese_char_base': 5_1_2, 'junnyu/roformer_small_discriminator': 1_2_8, 'junnyu/roformer_small_generator': 1_2_8, } a__ : str = { 'junnyu/roformer_chinese_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_base': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_base': {'do_lower_case': True}, 'junnyu/roformer_small_discriminator': {'do_lower_case': True}, 'junnyu/roformer_small_generator': {'do_lower_case': True}, } class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase = RoFormerTokenizer def __init__( self , a=None , a=None , a=True , a="[UNK]" , a="[SEP]" , a="[PAD]" , a="[CLS]" , a="[MASK]" , a=True , a=None , **a , ): super().__init__( a , tokenizer_file=a , do_lower_case=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , tokenize_chinese_chars=a , strip_accents=a , **a , ) UpperCamelCase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , a ) != do_lower_case or pre_tok_state.get("strip_accents" , a ) != strip_accents ): UpperCamelCase__ = getattr(a , pre_tok_state.pop("type" ) ) UpperCamelCase__ = do_lower_case UpperCamelCase__ = strip_accents UpperCamelCase__ = pre_tok_class(**a ) UpperCamelCase__ = do_lower_case def __getstate__( self ): UpperCamelCase__ = self.__dict__.copy() UpperCamelCase__ = BertPreTokenizer() return state def __setstate__( self , a ): UpperCamelCase__ = d UpperCamelCase__ = self.__dict__["_tokenizer"].get_vocab() UpperCamelCase__ = PreTokenizer.custom(JiebaPreTokenizer(a ) ) def __a ( self , a , a=None ): UpperCamelCase__ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __a ( self , a , a = None ): UpperCamelCase__ = [self.sep_token_id] UpperCamelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __a ( self , a , a = None ): UpperCamelCase__ = self._tokenizer.model.save(a , name=a ) return tuple(a ) def __a ( self , a , a=None , a=None , a=False , **a , ): UpperCamelCase__ = BertPreTokenizer() return super().save_pretrained(a , a , a , a , **a )
80
0
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 __snake_case ( lowerCAmelCase , unittest.TestCase ): _a : str= RoCBertTokenizer _a : str= None _a : str= False _a : Union[str, Any]= True _a : List[str]= filter_non_english def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' super().setUp() lowercase : Any = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] lowercase : Optional[int] = {} lowercase : List[str] = {} for i, value in enumerate(snake_case ): lowercase : List[str] = i lowercase : Optional[int] = i lowercase : Optional[int] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["""vocab_file"""] ) lowercase : List[Any] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["""word_shape_file"""] ) lowercase : List[str] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["""word_pronunciation_file"""] ) with open(self.vocab_file ,"""w""" ,encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.word_shape_file ,"""w""" ,encoding="""utf-8""" ) as word_shape_writer: json.dump(snake_case ,snake_case ,ensure_ascii=snake_case ) with open(self.word_pronunciation_file ,"""w""" ,encoding="""utf-8""" ) as word_pronunciation_writer: json.dump(snake_case ,snake_case ,ensure_ascii=snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Dict = self.tokenizer_class(self.vocab_file ,self.word_shape_file ,self.word_pronunciation_file ) lowercase : Tuple = tokenizer.tokenize("""你好[SEP]你是谁""" ) self.assertListEqual(snake_case ,["""你""", """好""", """[SEP]""", """你""", """是""", """谁"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case ) ,[5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(snake_case ) ,[5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(snake_case ) ,[5, 6, 2, 5, 7, 8] ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : int = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) ,["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Optional[int] = RoCBertBasicTokenizer(do_lower_case=snake_case ) 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 ): '''simple docstring''' lowercase : List[str] = RoCBertBasicTokenizer(do_lower_case=snake_case ,strip_accents=snake_case ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) ,["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) ,["""h\u00E9llo"""] ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Dict = RoCBertBasicTokenizer(do_lower_case=snake_case ,strip_accents=snake_case ) 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 ): '''simple docstring''' lowercase : List[str] = RoCBertBasicTokenizer(do_lower_case=snake_case ) 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 ): '''simple docstring''' lowercase : Dict = RoCBertBasicTokenizer(do_lower_case=snake_case ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) ,["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Dict = RoCBertBasicTokenizer(do_lower_case=snake_case ,strip_accents=snake_case ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) ,["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Optional[int] = RoCBertBasicTokenizer(do_lower_case=snake_case ,strip_accents=snake_case ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) ,["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : str = RoCBertBasicTokenizer(do_lower_case=snake_case ,never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) ,["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : int = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] lowercase : str = {} for i, token in enumerate(snake_case ): lowercase : Optional[Any] = i lowercase : str = RoCBertWordpieceTokenizer(vocab=snake_case ,unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) ,[] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) ,["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) ,["""[UNK]""", """runn""", """##ing"""] ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : int = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(snake_case ) for t in ["""Test""", """\xad""", """test"""]] ,[["""[UNK]"""], [], ["""[UNK]"""]] ) if self.test_rust_tokenizer: lowercase : Union[str, Any] = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(snake_case ) for t in ["""Test""", """\xad""", """test"""]] ,[["""[UNK]"""], [], ["""[UNK]"""]] ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): lowercase : List[Any] = self.rust_tokenizer_class.from_pretrained(snake_case ,**snake_case ) lowercase : Optional[Any] = f"A, naïve {tokenizer_r.mask_token} AllenNLP sentence." lowercase : str = tokenizer_r.encode_plus( snake_case ,return_attention_mask=snake_case ,return_token_type_ids=snake_case ,return_offsets_mapping=snake_case ,add_special_tokens=snake_case ,) lowercase : int = tokenizer_r.do_lower_case if hasattr(snake_case ,"""do_lower_case""" ) else False lowercase : List[str] = ( [ ((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 ): '''simple docstring''' lowercase : List[str] = ["""的""", """人""", """有"""] lowercase : List[str] = """""".join(snake_case ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): lowercase : int = True lowercase : Any = self.tokenizer_class.from_pretrained(snake_case ,**snake_case ) lowercase : str = self.rust_tokenizer_class.from_pretrained(snake_case ,**snake_case ) lowercase : Dict = tokenizer_p.encode(snake_case ,add_special_tokens=snake_case ) lowercase : Optional[int] = tokenizer_r.encode(snake_case ,add_special_tokens=snake_case ) lowercase : Optional[Any] = tokenizer_r.convert_ids_to_tokens(snake_case ) lowercase : str = tokenizer_p.convert_ids_to_tokens(snake_case ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(snake_case ,snake_case ) self.assertListEqual(snake_case ,snake_case ) lowercase : List[str] = False lowercase : Any = self.rust_tokenizer_class.from_pretrained(snake_case ,**snake_case ) lowercase : List[Any] = self.tokenizer_class.from_pretrained(snake_case ,**snake_case ) lowercase : Union[str, Any] = tokenizer_r.encode(snake_case ,add_special_tokens=snake_case ) lowercase : Optional[int] = tokenizer_p.encode(snake_case ,add_special_tokens=snake_case ) lowercase : str = tokenizer_r.convert_ids_to_tokens(snake_case ) lowercase : Optional[Any] = tokenizer_p.convert_ids_to_tokens(snake_case ) # it is expected that only the first Chinese character is not preceded by "##". lowercase : List[str] = [ f"##{token}" if idx != 0 else token for idx, token in enumerate(snake_case ) ] self.assertListEqual(snake_case ,snake_case ) self.assertListEqual(snake_case ,snake_case ) @slow def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[Any] = self.tokenizer_class(self.vocab_file ,self.word_shape_file ,self.word_pronunciation_file ) lowercase : List[Any] = tokenizer.encode("""你好""" ,add_special_tokens=snake_case ) lowercase : Any = tokenizer.encode("""你是谁""" ,add_special_tokens=snake_case ) lowercase : int = tokenizer.build_inputs_with_special_tokens(snake_case ) lowercase : List[Any] = tokenizer.build_inputs_with_special_tokens(snake_case ,snake_case ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : int = self.get_tokenizers(do_lower_case=snake_case ) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): lowercase : Optional[Any] = """你好,你是谁""" lowercase : int = tokenizer.tokenize(snake_case ) lowercase : Tuple = tokenizer.convert_tokens_to_ids(snake_case ) lowercase : Dict = tokenizer.convert_tokens_to_shape_ids(snake_case ) lowercase : str = tokenizer.convert_tokens_to_pronunciation_ids(snake_case ) lowercase : int = tokenizer.prepare_for_model( snake_case ,snake_case ,snake_case ,add_special_tokens=snake_case ) lowercase : Union[str, Any] = tokenizer.encode_plus(snake_case ,add_special_tokens=snake_case ) self.assertEqual(snake_case ,snake_case )
20
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : Optional[int] = {'vocab_file': 'vocab.txt'} a__ : Optional[Any] = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } a__ : Optional[int] = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def _UpperCamelCase ( __A ) -> str: '''simple docstring''' with open(__A , "r" ) as f: UpperCamelCase__ = f.read().splitlines() return [l.strip() for l in lines] class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self , a , a="<unk>" , a="<cls>" , a="<pad>" , a="<mask>" , a="<eos>" , **a , ): super().__init__(**a ) UpperCamelCase__ = load_vocab_file(a ) UpperCamelCase__ = dict(enumerate(self.all_tokens ) ) UpperCamelCase__ = {tok: ind for ind, tok in enumerate(self.all_tokens )} UpperCamelCase__ = unk_token UpperCamelCase__ = cls_token UpperCamelCase__ = pad_token UpperCamelCase__ = mask_token UpperCamelCase__ = eos_token UpperCamelCase__ = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a , **a ): return text.split() def __a ( self , a=False ): return len(self._id_to_token ) def __a ( self ): return {token: i for i, token in enumerate(self.all_tokens )} def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a , a = None ): UpperCamelCase__ = [self.cls_token_id] UpperCamelCase__ = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError("Cannot tokenize multiple sequences when EOS token is not set!" ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __a ( self , a , a = None , a = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] UpperCamelCase__ = [1] + ([0] * len(a )) + [1] if token_ids_a is not None: mask += [0] * len(a ) + [1] return mask def __a ( self , a , a ): UpperCamelCase__ = os.path.join(a , (filename_prefix + "-" if filename_prefix else "") + "vocab.txt" ) with open(a , "w" ) as f: f.write("\n".join(self.all_tokens ) ) return (vocab_file,) @property def __a ( self ): return self.get_vocab_size(with_added_tokens=a ) def __a ( self , a , a = False ): return super()._add_tokens(a , special_tokens=a )
80
0
from ....configuration_utils import PretrainedConfig from ....utils import logging SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : List[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 _lowerCamelCase( _a ): lowercase_ : List[str] = """trajectory_transformer""" lowercase_ : Optional[Any] = ["""past_key_values"""] lowercase_ : Any = { """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self, lowerCamelCase=1_00, lowerCamelCase=5, lowerCamelCase=1, lowerCamelCase=1, lowerCamelCase=2_49, lowerCamelCase=6, lowerCamelCase=17, lowerCamelCase=25, lowerCamelCase=4, lowerCamelCase=4, lowerCamelCase=1_28, lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=0.0_0_0_6, lowerCamelCase=5_12, lowerCamelCase=0.0_2, lowerCamelCase=1E-12, lowerCamelCase=1, lowerCamelCase=True, lowerCamelCase=1, lowerCamelCase=5_02_56, lowerCamelCase=5_02_56, **lowerCamelCase, ) -> Tuple: """simple docstring""" _lowercase : int = vocab_size _lowercase : Dict = action_weight _lowercase : Any = reward_weight _lowercase : List[Any] = value_weight _lowercase : List[str] = max_position_embeddings _lowercase : Any = block_size _lowercase : Tuple = action_dim _lowercase : List[str] = observation_dim _lowercase : Union[str, Any] = transition_dim _lowercase : Optional[Any] = learning_rate _lowercase : Tuple = n_layer _lowercase : str = n_head _lowercase : Union[str, Any] = n_embd _lowercase : Dict = embd_pdrop _lowercase : Optional[int] = attn_pdrop _lowercase : Union[str, Any] = resid_pdrop _lowercase : Any = initializer_range _lowercase : List[str] = layer_norm_eps _lowercase : List[Any] = kaiming_initializer_range _lowercase : Any = use_cache super().__init__(pad_token_id=lowerCamelCase, bos_token_id=lowerCamelCase, eos_token_id=lowerCamelCase, **lowerCamelCase)
21
'''simple docstring''' from math import factorial, pi def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_sin() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(__A ) ) def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_cos() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(__A ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(1_0)) print(maclaurin_sin(-1_0)) print(maclaurin_sin(1_0, 1_5)) print(maclaurin_sin(-1_0, 1_5)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(1_0, 1_5)) print(maclaurin_cos(-1_0, 1_5))
80
0
'''simple docstring''' from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer __SCREAMING_SNAKE_CASE :Any = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE :str = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} __SCREAMING_SNAKE_CASE :List[str] = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } __SCREAMING_SNAKE_CASE :Optional[Any] = {'''allegro/herbert-base-cased''': 514} __SCREAMING_SNAKE_CASE :Optional[int] = {} class A_ ( lowerCAmelCase_ ): _lowerCamelCase : Tuple = VOCAB_FILES_NAMES _lowerCamelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase : int = PRETRAINED_INIT_CONFIGURATION _lowerCamelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase : Tuple = HerbertTokenizer def __init__( self : Dict , snake_case_ : Union[str, Any]=None , snake_case_ : Any=None , snake_case_ : Dict=None , snake_case_ : List[Any]="<s>" , snake_case_ : Tuple="<unk>" , snake_case_ : Dict="<pad>" , snake_case_ : List[str]="<mask>" , snake_case_ : int="</s>" , **snake_case_ : str , ): super().__init__( snake_case_ , snake_case_ , tokenizer_file=snake_case_ , cls_token=snake_case_ , unk_token=snake_case_ , pad_token=snake_case_ , mask_token=snake_case_ , sep_token=snake_case_ , **snake_case_ , ) def lowercase ( self : str , snake_case_ : List[int] , snake_case_ : Optional[List[int]] = None ): _UpperCAmelCase = [self.cls_token_id] _UpperCAmelCase = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowercase ( self : Union[str, Any] , snake_case_ : List[int] , snake_case_ : Optional[List[int]] = None , snake_case_ : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case_ , token_ids_a=snake_case_ , already_has_special_tokens=snake_case_ ) if token_ids_a is None: return [1] + ([0] * len(snake_case_ )) + [1] return [1] + ([0] * len(snake_case_ )) + [1] + ([0] * len(snake_case_ )) + [1] def lowercase ( self : Any , snake_case_ : List[int] , snake_case_ : Optional[List[int]] = None ): _UpperCAmelCase = [self.sep_token_id] _UpperCAmelCase = [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 lowercase ( self : List[Any] , snake_case_ : str , snake_case_ : Optional[str] = None ): _UpperCAmelCase = self._tokenizer.model.save(snake_case_ , name=snake_case_ ) return tuple(snake_case_ )
22
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class lowercase_ ( a__ ): def __init__( self , a , a , a = None , a = None , a = False , **a , ): super().__init__(features=a , cache_dir=a , keep_in_memory=a , **a ) UpperCamelCase__ = Sql( cache_dir=a , features=a , sql=a , con=a , **a , ) def __a ( self ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None self.builder.download_and_prepare( download_config=a , download_mode=a , verification_mode=a , base_path=a , ) # Build dataset for splits UpperCamelCase__ = self.builder.as_dataset( split="train" , verification_mode=a , in_memory=self.keep_in_memory ) return dataset class lowercase_ : def __init__( self , a , a , a , a = None , a = None , **a , ): if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) UpperCamelCase__ = dataset UpperCamelCase__ = name UpperCamelCase__ = con UpperCamelCase__ = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE UpperCamelCase__ = num_proc UpperCamelCase__ = to_sql_kwargs def __a ( self ): UpperCamelCase__ = self.to_sql_kwargs.pop("sql" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("con" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("index" , a ) UpperCamelCase__ = self._write(index=a , **self.to_sql_kwargs ) return written def __a ( self , a ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = args UpperCamelCase__ = {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs UpperCamelCase__ = query_table( table=self.dataset.data , key=slice(a , offset + self.batch_size ) , indices=self.dataset._indices , ) UpperCamelCase__ = batch.to_pandas() UpperCamelCase__ = df.to_sql(self.name , self.con , index=a , **a ) return num_rows or len(a ) def __a ( self , a , **a ): UpperCamelCase__ = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: UpperCamelCase__ , UpperCamelCase__ = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , a , a )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += num_rows return written
80
0
'''simple docstring''' from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def snake_case_ ( _lowerCAmelCase : int ) -> int: UpperCAmelCase : Union[str, Any] = prime_factors(_lowerCAmelCase ) if is_square_free(_lowerCAmelCase ): return -1 if len(_lowerCAmelCase ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
23
'''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. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu a__ : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def _UpperCamelCase ( __A , __A=None , __A=None , __A=None ) -> int: '''simple docstring''' UpperCamelCase__ = True while ask_again: UpperCamelCase__ = input(__A ) try: if default is not None and len(__A ) == 0: return default return convert_value(__A ) if convert_value is not None else result except Exception: if error_message is not None: print(__A ) def _UpperCamelCase ( __A , __A=[] , __A=None , __A=0 ) -> Any: '''simple docstring''' UpperCamelCase__ = BulletMenu(__A , __A ) UpperCamelCase__ = menu.run(default_choice=__A ) return convert_value(__A ) if convert_value is not None else result def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value] ) def _UpperCamelCase ( __A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = int(__A ) return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def _UpperCamelCase ( __A ) -> str: '''simple docstring''' UpperCamelCase__ = int(__A ) return PrecisionType(["no", "fp16", "bf16", "fp8"][value] ) def _UpperCamelCase ( __A ) -> Any: '''simple docstring''' UpperCamelCase__ = int(__A ) return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' return {"yes": True, "no": False}[value.lower()] class lowercase_ ( argparse.RawDescriptionHelpFormatter ): def __a ( self , a , a , a , a ): UpperCamelCase__ = super()._format_usage(a , a , a , a ) UpperCamelCase__ = usage.replace("<command> [<args>] " , "" ) return usage
80
0
from __future__ import annotations def lowerCamelCase__ ( snake_case_ : list[int] , snake_case_ : int ) -> list[list[int]]: __snake_case = [] __snake_case = [] __snake_case = 0 __snake_case = sum(snake_case_ ) create_state_space_tree(snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) return result def lowerCamelCase__ ( snake_case_ : list[int] , snake_case_ : int , snake_case_ : int , snake_case_ : list[int] , snake_case_ : list[list[int]] , snake_case_ : int , ) -> None: if sum(snake_case_ ) > max_sum or (remaining_nums_sum + sum(snake_case_ )) < max_sum: return if sum(snake_case_ ) == max_sum: result.append(snake_case_ ) return for index in range(snake_case_ , len(snake_case_ ) ): create_state_space_tree( snake_case_ , snake_case_ , index + 1 , [*path, nums[index]] , snake_case_ , remaining_nums_sum - nums[index] , ) snake_case_ = [3, 34, 4, 12, 5, 2] snake_case_ = 9 snake_case_ = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
24
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: if resistor <= 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative or zero value!''' raise ValueError(__A ) first_sum += 1 / float(__A ) index += 1 return 1 / first_sum def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: sum_r += resistor if resistor < 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative value!''' raise ValueError(__A ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
80
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase__ : List[str] = {'configuration_xglm': ['XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XGLMConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[int] = ['XGLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : str = ['XGLMTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Union[str, Any] = [ 'XGLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'XGLMForCausalLM', 'XGLMModel', 'XGLMPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[Any] = [ 'FlaxXGLMForCausalLM', 'FlaxXGLMModel', 'FlaxXGLMPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : int = [ 'TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXGLMForCausalLM', 'TFXGLMModel', 'TFXGLMPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys UpperCAmelCase__ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure)
25
'''simple docstring''' import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class lowercase_ ( enum.Enum ): __UpperCAmelCase = 0 __UpperCAmelCase = 1 __UpperCAmelCase = 2 @add_end_docstrings(a__ ) class lowercase_ ( a__ ): __UpperCAmelCase = '\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n ' def __init__( self , *a , **a ): super().__init__(*a , **a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. UpperCamelCase__ = None if self.model.config.prefix is not None: UpperCamelCase__ = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. UpperCamelCase__ = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._sanitize_parameters(prefix=a , **self._forward_params ) UpperCamelCase__ = {**self._preprocess_params, **preprocess_params} UpperCamelCase__ = {**self._forward_params, **forward_params} def __a ( self , a=None , a=None , a=None , a=None , a=None , a=None , a=None , a=None , **a , ): UpperCamelCase__ = {} if prefix is not None: UpperCamelCase__ = prefix if prefix: UpperCamelCase__ = self.tokenizer( a , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = prefix_inputs["input_ids"].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' " [None, 'hole']" ) UpperCamelCase__ = handle_long_generation preprocess_params.update(a ) UpperCamelCase__ = generate_kwargs UpperCamelCase__ = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("`return_text` is mutually exclusive with `return_full_text`" ) if return_tensors is not None: raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`" ) UpperCamelCase__ = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("`return_text` is mutually exclusive with `return_tensors`" ) UpperCamelCase__ = ReturnType.TENSORS if return_type is not None: UpperCamelCase__ = return_type if clean_up_tokenization_spaces is not None: UpperCamelCase__ = clean_up_tokenization_spaces if stop_sequence is not None: UpperCamelCase__ = self.tokenizer.encode(a , add_special_tokens=a ) if len(a ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) UpperCamelCase__ = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __a ( self , *a , **a ): # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"add_space_before_punct_symbol": True} ) return super()._parse_and_tokenize(*a , **a ) def __call__( self , a , **a ): return super().__call__(a , **a ) def __a ( self , a , a="" , a=None , **a ): UpperCamelCase__ = self.tokenizer( prefix + prompt_text , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = prompt_text if handle_long_generation == "hole": UpperCamelCase__ = inputs["input_ids"].shape[-1] if "max_new_tokens" in generate_kwargs: UpperCamelCase__ = generate_kwargs["max_new_tokens"] else: UpperCamelCase__ = generate_kwargs.get("max_length" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("We cannot infer how many new tokens are expected" ) if cur_len + new_tokens > self.tokenizer.model_max_length: UpperCamelCase__ = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( "We cannot use `hole` to handle this generation the number of desired tokens exceeds the" " models max length" ) UpperCamelCase__ = inputs["input_ids"][:, -keep_length:] if "attention_mask" in inputs: UpperCamelCase__ = inputs["attention_mask"][:, -keep_length:] return inputs def __a ( self , a , **a ): UpperCamelCase__ = model_inputs["input_ids"] UpperCamelCase__ = model_inputs.get("attention_mask" , a ) # Allow empty prompts if input_ids.shape[1] == 0: UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = 1 else: UpperCamelCase__ = input_ids.shape[0] UpperCamelCase__ = model_inputs.pop("prompt_text" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. UpperCamelCase__ = generate_kwargs.pop("prefix_length" , 0 ) if prefix_length > 0: UpperCamelCase__ = "max_new_tokens" in generate_kwargs or ( "generation_config" in generate_kwargs and generate_kwargs["generation_config"].max_new_tokens is not None ) if not has_max_new_tokens: UpperCamelCase__ = generate_kwargs.get("max_length" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length UpperCamelCase__ = "min_new_tokens" in generate_kwargs or ( "generation_config" in generate_kwargs and generate_kwargs["generation_config"].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL UpperCamelCase__ = self.model.generate(input_ids=a , attention_mask=a , **a ) UpperCamelCase__ = generated_sequence.shape[0] if self.framework == "pt": UpperCamelCase__ = generated_sequence.reshape(a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": UpperCamelCase__ = tf.reshape(a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def __a ( self , a , a=ReturnType.FULL_TEXT , a=True ): UpperCamelCase__ = model_outputs["generated_sequence"][0] UpperCamelCase__ = model_outputs["input_ids"] UpperCamelCase__ = model_outputs["prompt_text"] UpperCamelCase__ = generated_sequence.numpy().tolist() UpperCamelCase__ = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: UpperCamelCase__ = {"generated_token_ids": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text UpperCamelCase__ = self.tokenizer.decode( a , skip_special_tokens=a , clean_up_tokenization_spaces=a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: UpperCamelCase__ = 0 else: UpperCamelCase__ = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=a , clean_up_tokenization_spaces=a , ) ) if return_type == ReturnType.FULL_TEXT: UpperCamelCase__ = prompt_text + text[prompt_length:] else: UpperCamelCase__ = text[prompt_length:] UpperCamelCase__ = {"generated_text": all_text} records.append(a ) return records
80
0
import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class lowercase ( UpperCamelCase__ ): def __init__( self , _a , _a , _a = None , _a = None , _a = False , **_a , ) -> int: super().__init__(features=_a , cache_dir=_a , keep_in_memory=_a , **_a ) _A : Optional[int] = Sql( cache_dir=_a , features=_a , sql=_a , con=_a , **_a , ) def a__ ( self ) -> Optional[Any]: _A : Tuple = None _A : int = None _A : Tuple = None _A : Union[str, Any] = None self.builder.download_and_prepare( download_config=_a , download_mode=_a , verification_mode=_a , base_path=_a , ) # Build dataset for splits _A : int = self.builder.as_dataset( split="""train""" , verification_mode=_a , in_memory=self.keep_in_memory ) return dataset class lowercase : def __init__( self , _a , _a , _a , _a = None , _a = None , **_a , ) -> Union[str, Any]: if num_proc is not None and num_proc <= 0: raise ValueError(F'''num_proc {num_proc} must be an integer > 0.''' ) _A : Dict = dataset _A : int = name _A : Union[str, Any] = con _A : str = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE _A : str = num_proc _A : Optional[Any] = to_sql_kwargs def a__ ( self ) -> int: _A : Any = self.to_sql_kwargs.pop("""sql""" , _a ) _A : List[str] = self.to_sql_kwargs.pop("""con""" , _a ) _A : int = self.to_sql_kwargs.pop("""index""" , _a ) _A : List[str] = self._write(index=_a , **self.to_sql_kwargs ) return written def a__ ( self , _a ) -> Optional[int]: _A , _A , _A : List[str] = args _A : int = {**to_sql_kwargs, """if_exists""": """append"""} if offset > 0 else to_sql_kwargs _A : str = query_table( table=self.dataset.data , key=slice(_a , offset + self.batch_size ) , indices=self.dataset._indices , ) _A : Tuple = batch.to_pandas() _A : Union[str, Any] = df.to_sql(self.name , self.con , index=_a , **_a ) return num_rows or len(_a ) def a__ ( self , _a , **_a ) -> int: _A : Any = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: _A , _A : Tuple = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , _a , _a )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += num_rows return written
26
'''simple docstring''' from ....utils import logging a__ : Optional[Any] = logging.get_logger(__name__) class lowercase_ ( a__ ): def __init__( self , a , a=None , a=20_48 ): UpperCamelCase__ = config.__dict__ UpperCamelCase__ = modal_hidden_size if num_labels: UpperCamelCase__ = num_labels
80
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowercase : Dict = { 'configuration_luke': ['LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LukeConfig'], 'tokenization_luke': ['LukeTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Optional[int] = [ 'LUKE_PRETRAINED_MODEL_ARCHIVE_LIST', 'LukeForEntityClassification', 'LukeForEntityPairClassification', 'LukeForEntitySpanClassification', 'LukeForMultipleChoice', 'LukeForQuestionAnswering', 'LukeForSequenceClassification', 'LukeForTokenClassification', 'LukeForMaskedLM', 'LukeModel', 'LukePreTrainedModel', ] if TYPE_CHECKING: from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig from .tokenization_luke import LukeTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_luke import ( LUKE_PRETRAINED_MODEL_ARCHIVE_LIST, LukeForEntityClassification, LukeForEntityPairClassification, LukeForEntitySpanClassification, LukeForMaskedLM, LukeForMultipleChoice, LukeForQuestionAnswering, LukeForSequenceClassification, LukeForTokenClassification, LukeModel, LukePreTrainedModel, ) else: import sys __lowercase : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
27
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent a__ : Tuple = {'UserAgent': UserAgent().random} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' UpperCamelCase__ = script.contents[0] UpperCamelCase__ = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class lowercase_ : def __init__( self , a ): UpperCamelCase__ = f'''https://www.instagram.com/{username}/''' UpperCamelCase__ = self.get_json() def __a ( self ): UpperCamelCase__ = requests.get(self.url , headers=a ).text UpperCamelCase__ = BeautifulSoup(a , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self ): return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self ): return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def __a ( self ): return self.user_data["username"] @property def __a ( self ): return self.user_data["full_name"] @property def __a ( self ): return self.user_data["biography"] @property def __a ( self ): return self.user_data["business_email"] @property def __a ( self ): return self.user_data["external_url"] @property def __a ( self ): return self.user_data["edge_followed_by"]["count"] @property def __a ( self ): return self.user_data["edge_follow"]["count"] @property def __a ( self ): return self.user_data["edge_owner_to_timeline_media"]["count"] @property def __a ( self ): return self.user_data["profile_pic_url_hd"] @property def __a ( self ): return self.user_data["is_verified"] @property def __a ( self ): return self.user_data["is_private"] def _UpperCamelCase ( __A = "github" ) -> None: '''simple docstring''' import os if os.environ.get("CI" ): return # test failing on GitHub Actions UpperCamelCase__ = InstagramUser(__A ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __A ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() a__ : Any = InstagramUser('github') print(instagram_user) print(F"""{instagram_user.number_of_posts = }""") print(F"""{instagram_user.number_of_followers = }""") print(F"""{instagram_user.number_of_followings = }""") print(F"""{instagram_user.email = }""") print(F"""{instagram_user.website = }""") print(F"""{instagram_user.profile_picture_url = }""") print(F"""{instagram_user.is_verified = }""") print(F"""{instagram_user.is_private = }""")
80
0
'''simple docstring''' import torch from torch import nn class SCREAMING_SNAKE_CASE ( nn.Module ): """simple docstring""" def __init__( self : List[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Any=1 , UpperCamelCase__ : int=False ): """simple docstring""" super().__init__() UpperCamelCase = n_token UpperCamelCase = d_embed UpperCamelCase = d_proj UpperCamelCase = cutoffs + [n_token] UpperCamelCase = [0] + self.cutoffs UpperCamelCase = div_val UpperCamelCase = self.cutoffs[0] UpperCamelCase = len(self.cutoffs ) - 1 UpperCamelCase = self.shortlist_size + self.n_clusters if self.n_clusters > 0: UpperCamelCase = nn.Parameter(torch.zeros(self.n_clusters , self.d_embed ) ) UpperCamelCase = nn.Parameter(torch.zeros(self.n_clusters ) ) UpperCamelCase = nn.ModuleList() UpperCamelCase = nn.ParameterList() if div_val == 1: for i in range(len(self.cutoffs ) ): if d_proj != d_embed: self.out_projs.append(nn.Parameter(torch.FloatTensor(UpperCamelCase__ , UpperCamelCase__ ) ) ) else: self.out_projs.append(UpperCamelCase__ ) self.out_layers.append(nn.Linear(UpperCamelCase__ , UpperCamelCase__ ) ) else: for i in range(len(self.cutoffs ) ): UpperCamelCase , UpperCamelCase = self.cutoff_ends[i], self.cutoff_ends[i + 1] UpperCamelCase = d_embed // (div_val**i) self.out_projs.append(nn.Parameter(torch.FloatTensor(UpperCamelCase__ , UpperCamelCase__ ) ) ) self.out_layers.append(nn.Linear(UpperCamelCase__ , r_idx - l_idx ) ) UpperCamelCase = keep_order def A ( self : str , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] ): """simple docstring""" if proj is None: UpperCamelCase = nn.functional.linear(UpperCamelCase__ , UpperCamelCase__ , bias=UpperCamelCase__ ) else: # if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1: UpperCamelCase = nn.functional.linear(UpperCamelCase__ , proj.t().contiguous() ) UpperCamelCase = nn.functional.linear(UpperCamelCase__ , UpperCamelCase__ , bias=UpperCamelCase__ ) # else: # logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t())) # if bias is not None: # logit = logit + bias return logit def A ( self : int , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : str=False ): """simple docstring""" if labels is not None: # Shift so that tokens < n predict n UpperCamelCase = hidden[..., :-1, :].contiguous() UpperCamelCase = labels[..., 1:].contiguous() UpperCamelCase = hidden.view(-1 , hidden.size(-1 ) ) UpperCamelCase = labels.view(-1 ) if hidden.size(0 ) != labels.size(0 ): raise RuntimeError('Input and labels should have the same size in the batch dimension.' ) else: UpperCamelCase = hidden.view(-1 , hidden.size(-1 ) ) if self.n_clusters == 0: UpperCamelCase = self._compute_logit(UpperCamelCase__ , self.out_layers[0].weight , self.out_layers[0].bias , self.out_projs[0] ) if labels is not None: UpperCamelCase = labels != -1_0_0 UpperCamelCase = torch.zeros_like(UpperCamelCase__ , dtype=hidden.dtype , device=hidden.device ) UpperCamelCase = ( -nn.functional.log_softmax(UpperCamelCase__ , dim=-1 )[mask].gather(1 , labels[mask].unsqueeze(1 ) ).squeeze(1 ) ) else: UpperCamelCase = nn.functional.log_softmax(UpperCamelCase__ , dim=-1 ) else: # construct weights and biases UpperCamelCase , UpperCamelCase = [], [] for i in range(len(self.cutoffs ) ): if self.div_val == 1: UpperCamelCase , UpperCamelCase = self.cutoff_ends[i], self.cutoff_ends[i + 1] UpperCamelCase = self.out_layers[0].weight[l_idx:r_idx] UpperCamelCase = self.out_layers[0].bias[l_idx:r_idx] else: UpperCamelCase = self.out_layers[i].weight UpperCamelCase = self.out_layers[i].bias if i == 0: UpperCamelCase = torch.cat([weight_i, self.cluster_weight] , dim=0 ) UpperCamelCase = torch.cat([bias_i, self.cluster_bias] , dim=0 ) weights.append(UpperCamelCase__ ) biases.append(UpperCamelCase__ ) UpperCamelCase , UpperCamelCase , UpperCamelCase = weights[0], biases[0], self.out_projs[0] UpperCamelCase = self._compute_logit(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) UpperCamelCase = nn.functional.log_softmax(UpperCamelCase__ , dim=1 ) if labels is None: UpperCamelCase = hidden.new_empty((head_logit.size(0 ), self.n_token) ) else: UpperCamelCase = torch.zeros_like(UpperCamelCase__ , dtype=hidden.dtype , device=hidden.device ) UpperCamelCase = 0 UpperCamelCase = [0] + self.cutoffs for i in range(len(UpperCamelCase__ ) - 1 ): UpperCamelCase , UpperCamelCase = cutoff_values[i], cutoff_values[i + 1] if labels is not None: UpperCamelCase = (labels >= l_idx) & (labels < r_idx) UpperCamelCase = mask_i.nonzero().squeeze() if indices_i.numel() == 0: continue UpperCamelCase = labels.index_select(0 , UpperCamelCase__ ) - l_idx UpperCamelCase = head_logprob.index_select(0 , UpperCamelCase__ ) UpperCamelCase = hidden.index_select(0 , UpperCamelCase__ ) else: UpperCamelCase = hidden if i == 0: if labels is not None: UpperCamelCase = head_logprob_i.gather(1 , target_i[:, None] ).squeeze(1 ) else: UpperCamelCase = head_logprob[:, : self.cutoffs[0]] else: UpperCamelCase , UpperCamelCase , UpperCamelCase = weights[i], biases[i], self.out_projs[i] UpperCamelCase = self._compute_logit(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) UpperCamelCase = nn.functional.log_softmax(UpperCamelCase__ , dim=1 ) UpperCamelCase = self.cutoffs[0] + i - 1 # No probability for the head cluster if labels is not None: UpperCamelCase = head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather( 1 , target_i[:, None] ).squeeze(1 ) else: UpperCamelCase = head_logprob[:, cluster_prob_idx, None] + tail_logprob_i UpperCamelCase = logprob_i if labels is not None: if (hasattr(self , 'keep_order' ) and self.keep_order) or keep_order: out.index_copy_(0 , UpperCamelCase__ , -logprob_i ) else: out[offset : offset + logprob_i.size(0 )].copy_(-logprob_i ) offset += logprob_i.size(0 ) return out def A ( self : List[Any] , UpperCamelCase__ : str ): """simple docstring""" if self.n_clusters == 0: UpperCamelCase = self._compute_logit(UpperCamelCase__ , self.out_layers[0].weight , self.out_layers[0].bias , self.out_projs[0] ) return nn.functional.log_softmax(UpperCamelCase__ , dim=-1 ) else: # construct weights and biases UpperCamelCase , UpperCamelCase = [], [] for i in range(len(self.cutoffs ) ): if self.div_val == 1: UpperCamelCase , UpperCamelCase = self.cutoff_ends[i], self.cutoff_ends[i + 1] UpperCamelCase = self.out_layers[0].weight[l_idx:r_idx] UpperCamelCase = self.out_layers[0].bias[l_idx:r_idx] else: UpperCamelCase = self.out_layers[i].weight UpperCamelCase = self.out_layers[i].bias if i == 0: UpperCamelCase = torch.cat([weight_i, self.cluster_weight] , dim=0 ) UpperCamelCase = torch.cat([bias_i, self.cluster_bias] , dim=0 ) weights.append(UpperCamelCase__ ) biases.append(UpperCamelCase__ ) UpperCamelCase , UpperCamelCase , UpperCamelCase = weights[0], biases[0], self.out_projs[0] UpperCamelCase = self._compute_logit(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) UpperCamelCase = hidden.new_empty((head_logit.size(0 ), self.n_token) ) UpperCamelCase = nn.functional.log_softmax(UpperCamelCase__ , dim=1 ) UpperCamelCase = [0] + self.cutoffs for i in range(len(UpperCamelCase__ ) - 1 ): UpperCamelCase , UpperCamelCase = cutoff_values[i], cutoff_values[i + 1] if i == 0: UpperCamelCase = head_logprob[:, : self.cutoffs[0]] else: UpperCamelCase , UpperCamelCase , UpperCamelCase = weights[i], biases[i], self.out_projs[i] UpperCamelCase = self._compute_logit(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) UpperCamelCase = nn.functional.log_softmax(UpperCamelCase__ , dim=1 ) UpperCamelCase = head_logprob[:, -i] + tail_logprob_i UpperCamelCase = logprob_i return out
28
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A , __A , __A ) -> dict[str, float]: '''simple docstring''' if (voltage, current, resistance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if resistance < 0: raise ValueError("Resistance cannot be negative" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
80
0
import math import sys def lowercase__ ( __snake_case : str ): '''simple docstring''' UpperCAmelCase_ : List[str] = '' try: with open(__snake_case , 'rb' ) as binary_file: UpperCAmelCase_ : str = binary_file.read() for dat in data: UpperCAmelCase_ : List[str] = F"{dat:08b}" result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def lowercase__ ( __snake_case : str ): '''simple docstring''' UpperCAmelCase_ : int = {'0': '0', '1': '1'} UpperCAmelCase_ , UpperCAmelCase_ : int = '', '' UpperCAmelCase_ : Optional[Any] = len(__snake_case ) for i in range(len(__snake_case ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue UpperCAmelCase_ : str = lexicon[curr_string] result += last_match_id UpperCAmelCase_ : Tuple = last_match_id + '0' if math.loga(__snake_case ).is_integer(): UpperCAmelCase_ : List[Any] = {} for curr_key in list(__snake_case ): UpperCAmelCase_ : Optional[int] = lexicon.pop(__snake_case ) UpperCAmelCase_ : Optional[Any] = new_lex UpperCAmelCase_ : Tuple = last_match_id + '1' index += 1 UpperCAmelCase_ : Tuple = '' return result def lowercase__ ( __snake_case : str , __snake_case : str ): '''simple docstring''' UpperCAmelCase_ : Tuple = 8 try: with open(__snake_case , 'wb' ) as opened_file: UpperCAmelCase_ : Dict = [ to_write[i : i + byte_length] for i in range(0 , len(__snake_case ) , __snake_case ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('10000000' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(__snake_case , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def lowercase__ ( __snake_case : str ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = 0 for letter in data_bits: if letter == "1": break counter += 1 UpperCAmelCase_ : List[str] = data_bits[counter:] UpperCAmelCase_ : Union[str, Any] = data_bits[counter + 1 :] return data_bits def lowercase__ ( __snake_case : str , __snake_case : str ): '''simple docstring''' UpperCAmelCase_ : List[str] = read_file_binary(__snake_case ) UpperCAmelCase_ : List[str] = remove_prefix(__snake_case ) UpperCAmelCase_ : Union[str, Any] = decompress_data(__snake_case ) write_file_binary(__snake_case , __snake_case ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
29
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Union[str, Any] = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys a__ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
80
0
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { 'huggingface/time-series-transformer-tourism-monthly': ( 'https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json' ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class lowercase__( UpperCAmelCase ): """simple docstring""" a :Optional[Any] = 'time_series_transformer' a :int = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : str = "student_t" , SCREAMING_SNAKE_CASE_ : str = "nll" , SCREAMING_SNAKE_CASE_ : int = 1 , SCREAMING_SNAKE_CASE_ : List[int] = [1, 2, 3, 4, 5, 6, 7] , SCREAMING_SNAKE_CASE_ : Optional[Union[str, bool]] = "mean" , SCREAMING_SNAKE_CASE_ : int = 0 , SCREAMING_SNAKE_CASE_ : int = 0 , SCREAMING_SNAKE_CASE_ : int = 0 , SCREAMING_SNAKE_CASE_ : int = 0 , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE_ : int = 3_2 , SCREAMING_SNAKE_CASE_ : int = 3_2 , SCREAMING_SNAKE_CASE_ : int = 2 , SCREAMING_SNAKE_CASE_ : int = 2 , SCREAMING_SNAKE_CASE_ : int = 2 , SCREAMING_SNAKE_CASE_ : int = 2 , SCREAMING_SNAKE_CASE_ : bool = True , SCREAMING_SNAKE_CASE_ : str = "gelu" , SCREAMING_SNAKE_CASE_ : int = 6_4 , SCREAMING_SNAKE_CASE_ : float = 0.1 , SCREAMING_SNAKE_CASE_ : float = 0.1 , SCREAMING_SNAKE_CASE_ : float = 0.1 , SCREAMING_SNAKE_CASE_ : float = 0.1 , SCREAMING_SNAKE_CASE_ : float = 0.1 , SCREAMING_SNAKE_CASE_ : int = 1_0_0 , SCREAMING_SNAKE_CASE_ : float = 0.02 , SCREAMING_SNAKE_CASE_ : Dict=True , **SCREAMING_SNAKE_CASE_ : Optional[int] , ) -> Optional[Any]: # time series specific configuration lowercase_ = prediction_length lowercase_ = context_length or prediction_length lowercase_ = distribution_output lowercase_ = loss lowercase_ = input_size lowercase_ = num_time_features lowercase_ = lags_sequence lowercase_ = scaling lowercase_ = num_dynamic_real_features lowercase_ = num_static_real_features lowercase_ = num_static_categorical_features if cardinality and num_static_categorical_features > 0: if len(SCREAMING_SNAKE_CASE_ ) != num_static_categorical_features: raise ValueError( '''The cardinality should be a list of the same length as `num_static_categorical_features`''' ) lowercase_ = cardinality else: lowercase_ = [0] if embedding_dimension and num_static_categorical_features > 0: if len(SCREAMING_SNAKE_CASE_ ) != num_static_categorical_features: raise ValueError( '''The embedding dimension should be a list of the same length as `num_static_categorical_features`''' ) lowercase_ = embedding_dimension else: lowercase_ = [min(5_0 , (cat + 1) // 2 ) for cat in self.cardinality] lowercase_ = num_parallel_samples # Transformer architecture configuration lowercase_ = input_size * len(SCREAMING_SNAKE_CASE_ ) + self._number_of_features lowercase_ = d_model lowercase_ = encoder_attention_heads lowercase_ = decoder_attention_heads lowercase_ = encoder_ffn_dim lowercase_ = decoder_ffn_dim lowercase_ = encoder_layers lowercase_ = decoder_layers lowercase_ = dropout lowercase_ = attention_dropout lowercase_ = activation_dropout lowercase_ = encoder_layerdrop lowercase_ = decoder_layerdrop lowercase_ = activation_function lowercase_ = init_std lowercase_ = use_cache super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @property def _lowercase ( self : str ) -> int: return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
30
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if len(__A ) != 2 or len(a[0] ) != 2 or len(__A ) != 2 or len(b[0] ) != 2: raise Exception("Matrices are not 2x2" ) UpperCamelCase__ = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _UpperCamelCase ( __A , __A ) -> str: '''simple docstring''' return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A ) -> tuple[list, list, list, list]: '''simple docstring''' if len(__A ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception("Odd matrices are not supported!" ) UpperCamelCase__ = len(__A ) UpperCamelCase__ = matrix_length // 2 UpperCamelCase__ = [[a[i][j] for j in range(__A , __A )] for i in range(__A )] UpperCamelCase__ = [ [a[i][j] for j in range(__A , __A )] for i in range(__A , __A ) ] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A )] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A , __A )] return top_left, top_right, bot_left, bot_right def _UpperCamelCase ( __A ) -> tuple[int, int]: '''simple docstring''' return len(__A ), len(matrix[0] ) def _UpperCamelCase ( __A ) -> None: '''simple docstring''' print("\n".join(str(__A ) for line in matrix ) ) def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A ) == (2, 2): return default_matrix_multiplication(__A , __A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = matrix_addition(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_subtraction(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) # construct the new matrix from our 4 quadrants UpperCamelCase__ = [] for i in range(len(__A ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(__A ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A )[1] != matrix_dimensions(__A )[0]: UpperCamelCase__ = ( "Unable to multiply these matrices, please check the dimensions.\n" F'''Matrix A: {matrixa}\n''' F'''Matrix B: {matrixa}''' ) raise Exception(__A ) UpperCamelCase__ = matrix_dimensions(__A ) UpperCamelCase__ = matrix_dimensions(__A ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] UpperCamelCase__ = max(*__A , *__A ) UpperCamelCase__ = int(math.pow(2 , math.ceil(math.loga(__A ) ) ) ) UpperCamelCase__ = matrixa UpperCamelCase__ = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) UpperCamelCase__ = actual_strassen(__A , __A ) # Removing the additional zeros for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a__ : int = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a__ : str = [[0, 2, 1, 1], [1_6, 2, 3, 3], [2, 2, 7, 7], [1_3, 1_1, 2_2, 4]] print(strassen(matrixa, matrixa))
80
0
'''simple docstring''' from __future__ import annotations def UpperCamelCase_ ( _UpperCAmelCase : Dict , _UpperCAmelCase : Dict , _UpperCAmelCase : str , _UpperCAmelCase : Optional[int] ) -> Any: # noqa: E741 """simple docstring""" while r - l > 1: _UpperCAmelCase : List[Any] = (l + r) // 2 if v[m] >= key: _UpperCAmelCase : Tuple = m else: _UpperCAmelCase : List[Any] = m # noqa: E741 return r def UpperCamelCase_ ( _UpperCAmelCase : list[int] ) -> int: """simple docstring""" if len(_UpperCAmelCase ) == 0: return 0 _UpperCAmelCase : Any = [0] * len(_UpperCAmelCase ) _UpperCAmelCase : str = 1 _UpperCAmelCase : List[str] = v[0] for i in range(1 , len(_UpperCAmelCase ) ): if v[i] < tail[0]: _UpperCAmelCase : Tuple = v[i] elif v[i] > tail[length - 1]: _UpperCAmelCase : Tuple = v[i] length += 1 else: _UpperCAmelCase : str = v[i] return length if __name__ == "__main__": import doctest doctest.testmod()
31
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging a__ : List[str] = logging.get_logger(__name__) if is_vision_available(): import PIL class lowercase_ ( a__ ): __UpperCAmelCase = ['pixel_values'] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = None , a = True , a = 1 / 2_55 , a = True , a = None , a = None , a = True , **a , ): super().__init__(**a ) UpperCamelCase__ = size if size is not None else {"shortest_edge": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a ) UpperCamelCase__ = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a , param_name="crop_size" ) UpperCamelCase__ = do_resize UpperCamelCase__ = size UpperCamelCase__ = resample UpperCamelCase__ = do_center_crop UpperCamelCase__ = crop_size UpperCamelCase__ = do_rescale UpperCamelCase__ = rescale_factor UpperCamelCase__ = do_normalize UpperCamelCase__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN UpperCamelCase__ = image_std if image_std is not None else OPENAI_CLIP_STD UpperCamelCase__ = do_convert_rgb def __a ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ): UpperCamelCase__ = get_size_dict(a , default_to_square=a ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) UpperCamelCase__ = get_resize_output_image_size(a , size=size["shortest_edge"] , default_to_square=a ) return resize(a , size=a , resample=a , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): UpperCamelCase__ = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(a , size=(size["height"], size["width"]) , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): return rescale(a , scale=a , data_format=a , **a ) def __a ( self , a , a , a , a = None , **a , ): return normalize(a , mean=a , std=a , data_format=a , **a ) def __a ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ): UpperCamelCase__ = do_resize if do_resize is not None else self.do_resize UpperCamelCase__ = size if size is not None else self.size UpperCamelCase__ = get_size_dict(a , param_name="size" , default_to_square=a ) UpperCamelCase__ = resample if resample is not None else self.resample UpperCamelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase__ = crop_size if crop_size is not None else self.crop_size UpperCamelCase__ = get_size_dict(a , param_name="crop_size" , default_to_square=a ) UpperCamelCase__ = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase__ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase__ = image_mean if image_mean is not None else self.image_mean UpperCamelCase__ = image_std if image_std is not None else self.image_std UpperCamelCase__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase__ = make_list_of_images(a ) if not valid_images(a ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase__ = [convert_to_rgb(a ) for image in images] # All transformations expect numpy arrays. UpperCamelCase__ = [to_numpy_array(a ) for image in images] if do_resize: UpperCamelCase__ = [self.resize(image=a , size=a , resample=a ) for image in images] if do_center_crop: UpperCamelCase__ = [self.center_crop(image=a , size=a ) for image in images] if do_rescale: UpperCamelCase__ = [self.rescale(image=a , scale=a ) for image in images] if do_normalize: UpperCamelCase__ = [self.normalize(image=a , mean=a , std=a ) for image in images] UpperCamelCase__ = [to_channel_dimension_format(a , a ) for image in images] UpperCamelCase__ = {"pixel_values": images} return BatchFeature(data=a , tensor_type=a )
80
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy, skip_mps, slow from diffusers.utils.testing_utils import require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin UpperCAmelCase_ : Optional[Any] = False @skip_mps class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): snake_case__ : str = StableDiffusionAttendAndExcitePipeline snake_case__ : Tuple = False snake_case__ : Dict = TEXT_TO_IMAGE_PARAMS snake_case__ : str = TEXT_TO_IMAGE_BATCH_PARAMS.union({'''token_indices'''} ) snake_case__ : int = TEXT_TO_IMAGE_IMAGE_PARAMS snake_case__ : List[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def SCREAMING_SNAKE_CASE ( cls : str ) -> Optional[Any]: super().setUpClass() torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE__ ) @classmethod def SCREAMING_SNAKE_CASE ( cls : Optional[int] ) -> List[str]: super().tearDownClass() torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : int ) -> Union[str, Any]: torch.manual_seed(0 ) a_ : List[str] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=1 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=3_2 , attention_head_dim=(2, 4) , use_linear_projection=SCREAMING_SNAKE_CASE__ , ) a_ : str = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) a_ : Union[str, Any] = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) a_ : Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=5_1_2 , ) a_ : Optional[int] = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) a_ : List[str] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) a_ : Dict = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Any=0 ) -> Any: if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): a_ : Any = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: a_ : List[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) a_ : List[str] = { 'prompt': 'a cat and a frog', 'token_indices': [2, 5], 'generator': generator, 'num_inference_steps': 1, 'guidance_scale': 6.0, 'output_type': 'numpy', 'max_iter_to_alter': 2, 'thresholds': {0: 0.7}, } return inputs def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: a_ : List[str] = 'cpu' a_ : Optional[Any] = self.get_dummy_components() a_ : Any = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : str = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) a_ : str = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : List[Any] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 6_4, 6_4, 3) ) a_ : Any = np.array( [0.63905364, 0.62897307, 0.48599017, 0.5133624, 0.5550048, 0.45769516, 0.50326973, 0.5023139, 0.45384496] ) a_ : Union[str, Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1E-3 ) def SCREAMING_SNAKE_CASE ( self : int ) -> int: super().test_cpu_offload_forward_pass(expected_max_diff=5E-4 ) def SCREAMING_SNAKE_CASE ( self : str ) -> int: # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: self._test_inference_batch_single_identical(batch_size=2 , expected_max_diff=7E-4 ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4 ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: super().test_save_load_local(expected_max_difference=5E-4 ) def SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: super().test_save_load_optional_components(expected_max_difference=4E-4 ) @require_torch_gpu @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @classmethod def SCREAMING_SNAKE_CASE ( cls : Dict ) -> Union[str, Any]: super().setUpClass() torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE__ ) @classmethod def SCREAMING_SNAKE_CASE ( cls : List[str] ) -> Tuple: super().tearDownClass() torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: a_ : str = torch.manual_seed(5_1 ) a_ : Tuple = StableDiffusionAttendAndExcitePipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , safety_checker=SCREAMING_SNAKE_CASE__ , torch_dtype=torch.floataa ) pipe.to('cuda' ) a_ : Any = 'a painting of an elephant with glasses' a_ : str = [5, 7] a_ : Dict = pipe( prompt=SCREAMING_SNAKE_CASE__ , token_indices=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=5 , max_iter_to_alter=5 , output_type='numpy' , ).images[0] a_ : int = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy' ) assert np.abs((expected_image - image).max() ) < 5E-1
32
'''simple docstring''' import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase_ ( a__ , unittest.TestCase ): __UpperCAmelCase = CLIPTokenizer __UpperCAmelCase = CLIPTokenizerFast __UpperCAmelCase = True __UpperCAmelCase = {} __UpperCAmelCase = False def __a ( self ): super().setUp() # fmt: off UpperCamelCase__ = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on UpperCamelCase__ = dict(zip(a , range(len(a ) ) ) ) UpperCamelCase__ = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] UpperCamelCase__ = {"unk_token": "<unk>"} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(a ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(a ) ) def __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def __a ( self , a ): UpperCamelCase__ = "lower newer" UpperCamelCase__ = "lower newer" return input_text, output_text def __a ( self ): UpperCamelCase__ = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = "lower newer" UpperCamelCase__ = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] UpperCamelCase__ = tokenizer.tokenize(a ) self.assertListEqual(a , a ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def __a ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = self.tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways UpperCamelCase__ = "xa\u0303y" + " " + "x\xe3y" UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type UpperCamelCase__ = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type UpperCamelCase__ = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def __a ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = "hello" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = f'''{text_of_1_token} {text_of_1_token}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) UpperCamelCase__ = f''' {text}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def __a ( self ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def __a ( self ): super().test_tokenization_python_rust_equals() def __a ( self ): # CLIP always lower cases letters pass
80
0
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class _UpperCAmelCase ( unittest.TestCase ): def A ( self : List[str] , A : Union[str, Any] ) -> int: for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''] , model_result['''ss'''] ): lowercase_ : Tuple = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(A ) def A ( self : int ) -> Optional[Any]: lowercase_ : Optional[Any] = '''sshleifer/tiny-gpt2''' lowercase_ : int = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A , inference=A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A , ) lowercase_ : List[str] = PyTorchBenchmark(A ) lowercase_ : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def A ( self : int ) -> Optional[Any]: lowercase_ : List[Any] = '''sgugger/tiny-distilbert-classification''' lowercase_ : Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A , inference=A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A , only_pretrain_model=A , ) lowercase_ : Tuple = PyTorchBenchmark(A ) lowercase_ : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def A ( self : List[Any] ) -> str: lowercase_ : str = '''sshleifer/tiny-gpt2''' lowercase_ : Any = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A , inference=A , torchscript=A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A , ) lowercase_ : List[Any] = PyTorchBenchmark(A ) lowercase_ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def A ( self : List[Any] ) -> str: lowercase_ : int = '''sshleifer/tiny-gpt2''' lowercase_ : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A , inference=A , fpaa=A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A , ) lowercase_ : Any = PyTorchBenchmark(A ) lowercase_ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def A ( self : Union[str, Any] ) -> Optional[int]: lowercase_ : Union[str, Any] = '''sshleifer/tiny-gpt2''' lowercase_ : Optional[int] = AutoConfig.from_pretrained(A ) # set architectures equal to `None` lowercase_ : str = None lowercase_ : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A , inference=A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A , ) lowercase_ : Any = PyTorchBenchmark(A , configs=[config] ) lowercase_ : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def A ( self : Optional[Any] ) -> List[Any]: lowercase_ : Optional[Any] = '''sshleifer/tiny-gpt2''' lowercase_ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A , inference=A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A , ) lowercase_ : List[str] = PyTorchBenchmark(A ) lowercase_ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Can\'t do half precision''' ) def A ( self : Optional[Any] ) -> Dict: lowercase_ : Optional[Any] = '''sshleifer/tiny-gpt2''' lowercase_ : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A , inference=A , sequence_lengths=[8] , batch_sizes=[1] , fpaa=A , multi_process=A , ) lowercase_ : int = PyTorchBenchmark(A ) lowercase_ : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def A ( self : int ) -> Optional[Any]: lowercase_ : List[Any] = '''sshleifer/tiny-gpt2''' lowercase_ : Any = AutoConfig.from_pretrained(A ) lowercase_ : Any = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A , inference=A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A , ) lowercase_ : Optional[Any] = PyTorchBenchmark(A , configs=[config] ) lowercase_ : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def A ( self : Any ) -> List[Any]: lowercase_ : Union[str, Any] = '''sshleifer/tinier_bart''' lowercase_ : Optional[Any] = AutoConfig.from_pretrained(A ) lowercase_ : int = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A , inference=A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A , ) lowercase_ : Any = PyTorchBenchmark(A , configs=[config] ) lowercase_ : int = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def A ( self : List[str] ) -> Optional[int]: lowercase_ : str = '''sshleifer/tiny-gpt2''' lowercase_ : Union[str, Any] = AutoConfig.from_pretrained(A ) lowercase_ : List[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A , inference=A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A , ) lowercase_ : List[str] = PyTorchBenchmark(A , configs=[config] ) lowercase_ : str = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def A ( self : Optional[Any] ) -> int: lowercase_ : Optional[Any] = '''sshleifer/tinier_bart''' lowercase_ : Optional[Any] = AutoConfig.from_pretrained(A ) lowercase_ : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A , inference=A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=A , ) lowercase_ : str = PyTorchBenchmark(A , configs=[config] ) lowercase_ : str = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def A ( self : Union[str, Any] ) -> Optional[int]: lowercase_ : List[Any] = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Any = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A , inference=A , save_to_csv=A , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(A , '''inf_time.csv''' ) , train_memory_csv_file=os.path.join(A , '''train_mem.csv''' ) , inference_memory_csv_file=os.path.join(A , '''inf_mem.csv''' ) , train_time_csv_file=os.path.join(A , '''train_time.csv''' ) , env_info_csv_file=os.path.join(A , '''env.csv''' ) , multi_process=A , ) lowercase_ : str = PyTorchBenchmark(A ) benchmark.run() self.assertTrue(Path(os.path.join(A , '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(A , '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(A , '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(A , '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(A , '''env.csv''' ) ).exists() ) def A ( self : str ) -> Tuple: lowercase_ : str = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(A : List[Any] ): self.assertTrue(hasattr(A , '''sequential''' ) ) self.assertTrue(hasattr(A , '''cumulative''' ) ) self.assertTrue(hasattr(A , '''current''' ) ) self.assertTrue(hasattr(A , '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Any = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=A , inference=A , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(A , '''log.txt''' ) , log_print=A , trace_memory_line_by_line=A , multi_process=A , ) lowercase_ : Optional[int] = PyTorchBenchmark(A ) lowercase_ : Dict = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(A , '''log.txt''' ) ).exists() )
33
'''simple docstring''' import argparse import collections import json import os import re import string import sys import numpy as np a__ : Optional[int] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a__ : int = None def _UpperCamelCase ( ) -> Dict: '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0." ) parser.add_argument("data_file" , metavar="data.json" , help="Input data JSON file." ) parser.add_argument("pred_file" , metavar="pred.json" , help="Model predictions." ) parser.add_argument( "--out-file" , "-o" , metavar="eval.json" , help="Write accuracy metrics to file (default is stdout)." ) parser.add_argument( "--na-prob-file" , "-n" , metavar="na_prob.json" , help="Model estimates of probability of no answer." ) parser.add_argument( "--na-prob-thresh" , "-t" , type=__A , default=1.0 , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)." , ) parser.add_argument( "--out-image-dir" , "-p" , metavar="out_images" , default=__A , help="Save precision-recall curves to directory." ) parser.add_argument("--verbose" , "-v" , action="store_true" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = bool(qa["answers"]["text"] ) return qid_to_has_ans def _UpperCamelCase ( __A ) -> Optional[Any]: '''simple docstring''' def remove_articles(__A ): return ARTICLES_REGEX.sub(" " , __A ) def white_space_fix(__A ): return " ".join(text.split() ) def remove_punc(__A ): UpperCamelCase__ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__A ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__A ) ) ) ) def _UpperCamelCase ( __A ) -> int: '''simple docstring''' if not s: return [] return normalize_answer(__A ).split() def _UpperCamelCase ( __A , __A ) -> List[Any]: '''simple docstring''' return int(normalize_answer(__A ) == normalize_answer(__A ) ) def _UpperCamelCase ( __A , __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = collections.Counter(__A ) & collections.Counter(__A ) UpperCamelCase__ = sum(common.values() ) if len(__A ) == 0 or len(__A ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = (2 * precision * recall) / (precision + recall) return fa def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = qa["id"] UpperCamelCase__ = [t for t in qa["answers"]["text"] if normalize_answer(__A )] if not gold_answers: # For unanswerable questions, only correct answer is empty string UpperCamelCase__ = [""] if qid not in preds: print(F'''Missing prediction for {qid}''' ) continue UpperCamelCase__ = preds[qid] # Take max over all gold answers UpperCamelCase__ = max(compute_exact(__A , __A ) for a in gold_answers ) UpperCamelCase__ = max(compute_fa(__A , __A ) for a in gold_answers ) return exact_scores, fa_scores def _UpperCamelCase ( __A , __A , __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} for qid, s in scores.items(): UpperCamelCase__ = na_probs[qid] > na_prob_thresh if pred_na: UpperCamelCase__ = float(not qid_to_has_ans[qid] ) else: UpperCamelCase__ = s return new_scores def _UpperCamelCase ( __A , __A , __A=None ) -> List[Any]: '''simple docstring''' if not qid_list: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores.values() ) / total), ("f1", 100.0 * sum(fa_scores.values() ) / total), ("total", total), ] ) else: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("f1", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("total", total), ] ) def _UpperCamelCase ( __A , __A , __A ) -> Optional[int]: '''simple docstring''' for k in new_eval: UpperCamelCase__ = new_eval[k] def _UpperCamelCase ( __A , __A , __A , __A ) -> Optional[int]: '''simple docstring''' plt.step(__A , __A , color="b" , alpha=0.2 , where="post" ) plt.fill_between(__A , __A , step="post" , alpha=0.2 , color="b" ) plt.xlabel("Recall" ) plt.ylabel("Precision" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__A ) plt.savefig(__A ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A , __A=None , __A=None ) -> Any: '''simple docstring''' UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) UpperCamelCase__ = 0.0 UpperCamelCase__ = 1.0 UpperCamelCase__ = 0.0 UpperCamelCase__ = [1.0] UpperCamelCase__ = [0.0] UpperCamelCase__ = 0.0 for i, qid in enumerate(__A ): if qid_to_has_ans[qid]: true_pos += scores[qid] UpperCamelCase__ = true_pos / float(i + 1 ) UpperCamelCase__ = true_pos / float(__A ) if i == len(__A ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__A ) recalls.append(__A ) if out_image: plot_pr_curve(__A , __A , __A , __A ) return {"ap": 100.0 * avg_prec} def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if out_image_dir and not os.path.exists(__A ): os.makedirs(__A ) UpperCamelCase__ = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_exact.png" ) , title="Precision-Recall curve for Exact Match score" , ) UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_f1.png" ) , title="Precision-Recall curve for F1 score" , ) UpperCamelCase__ = {k: float(__A ) for k, v in qid_to_has_ans.items()} UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_oracle.png" ) , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)" , ) merge_eval(__A , __A , "pr_exact" ) merge_eval(__A , __A , "pr_f1" ) merge_eval(__A , __A , "pr_oracle" ) def _UpperCamelCase ( __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if not qid_list: return UpperCamelCase__ = [na_probs[k] for k in qid_list] UpperCamelCase__ = np.ones_like(__A ) / float(len(__A ) ) plt.hist(__A , weights=__A , bins=20 , range=(0.0, 1.0) ) plt.xlabel("Model probability of no-answer" ) plt.ylabel("Proportion of dataset" ) plt.title(F'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__A , F'''na_prob_hist_{name}.png''' ) ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A ) -> Tuple: '''simple docstring''' UpperCamelCase__ = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) UpperCamelCase__ = num_no_ans UpperCamelCase__ = cur_score UpperCamelCase__ = 0.0 UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) for i, qid in enumerate(__A ): if qid not in scores: continue if qid_to_has_ans[qid]: UpperCamelCase__ = scores[qid] else: if preds[qid]: UpperCamelCase__ = -1 else: UpperCamelCase__ = 0 cur_score += diff if cur_score > best_score: UpperCamelCase__ = cur_score UpperCamelCase__ = na_probs[qid] return 100.0 * best_score / len(__A ), best_thresh def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> Dict: '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ = best_exact UpperCamelCase__ = exact_thresh UpperCamelCase__ = best_fa UpperCamelCase__ = fa_thresh def _UpperCamelCase ( ) -> Any: '''simple docstring''' with open(OPTS.data_file ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = dataset_json["data"] with open(OPTS.pred_file ) as f: UpperCamelCase__ = json.load(__A ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: UpperCamelCase__ = json.load(__A ) else: UpperCamelCase__ = {k: 0.0 for k in preds} UpperCamelCase__ = make_qid_to_has_ans(__A ) # maps qid to True/False UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if v] UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if not v] UpperCamelCase__ , UpperCamelCase__ = get_raw_scores(__A , __A ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = make_eval_dict(__A , __A ) if has_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "HasAns" ) if no_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "NoAns" ) if OPTS.na_prob_file: find_all_best_thresh(__A , __A , __A , __A , __A , __A ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__A , __A , __A , __A , __A , OPTS.out_image_dir ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "hasAns" ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "noAns" ) if OPTS.out_file: with open(OPTS.out_file , "w" ) as f: json.dump(__A , __A ) else: print(json.dumps(__A , indent=2 ) ) if __name__ == "__main__": a__ : Optional[int] = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
80
0
'''simple docstring''' from typing import List, Optional, TypeVar from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .info import DatasetInfo from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets from .splits import NamedSplit from .utils import logging from .utils.py_utils import Literal A =logging.get_logger(__name__) A =TypeVar('DatasetType', Dataset, IterableDataset) def snake_case_ (_a : List[DatasetType] , _a : Optional[List[float]] = None , _a : Optional[int] = None , _a : Optional[DatasetInfo] = None , _a : Optional[NamedSplit] = None , _a : Literal["first_exhausted", "all_exhausted"] = "first_exhausted" , ): from .arrow_dataset import Dataset from .iterable_dataset import IterableDataset if not datasets: raise ValueError('''Unable to interleave an empty list of datasets.''' ) for i, dataset in enumerate(_a ): if not isinstance(_a , (Dataset, IterableDataset) ): if isinstance(_a , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} " '''is an empty dataset dictionary.''' ) raise ValueError( F"Dataset at position {i} has at least one split: {list(_a )}\n" F"Please pick one to interleave with the other datasets, for example: dataset['{next(iter(_a ) )}']" ) raise ValueError( F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(_a ).__name__}." ) if i == 0: UpperCAmelCase , UpperCAmelCase = ( (Dataset, IterableDataset) if isinstance(_a , _a ) else (IterableDataset, Dataset) ) elif not isinstance(_a , _a ): raise ValueError( F"Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects." ) if stopping_strategy not in ["first_exhausted", "all_exhausted"]: raise ValueError(F"{stopping_strategy} is not supported. Please enter a valid stopping_strategy." ) if dataset_type is Dataset: return _interleave_map_style_datasets( _a , _a , _a , info=_a , split=_a , stopping_strategy=_a ) else: return _interleave_iterable_datasets( _a , _a , _a , info=_a , split=_a , stopping_strategy=_a ) def snake_case_ (_a : List[DatasetType] , _a : Optional[DatasetInfo] = None , _a : Optional[NamedSplit] = None , _a : int = 0 , ): if not dsets: raise ValueError('''Unable to concatenate an empty list of datasets.''' ) for i, dataset in enumerate(_a ): if not isinstance(_a , (Dataset, IterableDataset) ): if isinstance(_a , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} " '''is an empty dataset dictionary.''' ) raise ValueError( F"Dataset at position {i} has at least one split: {list(_a )}\n" F"Please pick one to interleave with the other datasets, for example: dataset['{next(iter(_a ) )}']" ) raise ValueError( F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(_a ).__name__}." ) if i == 0: UpperCAmelCase , UpperCAmelCase = ( (Dataset, IterableDataset) if isinstance(_a , _a ) else (IterableDataset, Dataset) ) elif not isinstance(_a , _a ): raise ValueError( F"Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects." ) if dataset_type is Dataset: return _concatenate_map_style_datasets(_a , info=_a , split=_a , axis=_a ) else: return _concatenate_iterable_datasets(_a , info=_a , split=_a , axis=_a )
34
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType a__ : Optional[List[str]] = None a__ : Dict = '<' if sys.byteorder == 'little' else '>' # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image a__ : Any = [ np.dtype('|b1'), np.dtype('|u1'), np.dtype('<u2'), np.dtype('>u2'), np.dtype('<i2'), np.dtype('>i2'), np.dtype('<u4'), np.dtype('>u4'), np.dtype('<i4'), np.dtype('>i4'), np.dtype('<f4'), np.dtype('>f4'), np.dtype('<f8'), np.dtype('>f8'), ] @dataclass class lowercase_ : __UpperCAmelCase = True __UpperCAmelCase = None # Automatically constructed __UpperCAmelCase = "PIL.Image.Image" __UpperCAmelCase = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) __UpperCAmelCase = field(default='Image' , init=a__ , repr=a__ ) def __call__( self ): return self.pa_type def __a ( self , a ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if isinstance(a , a ): UpperCamelCase__ = np.array(a ) if isinstance(a , a ): return {"path": value, "bytes": None} elif isinstance(a , a ): return {"path": None, "bytes": value} elif isinstance(a , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(a ) elif isinstance(a , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(a ) elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def __a ( self , a , a=None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Image(decode=True) instead." ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support decoding images, please install 'Pillow'." ) if token_per_repo_id is None: UpperCamelCase__ = {} UpperCamelCase__ , UpperCamelCase__ = value["path"], value["bytes"] if bytes_ is None: if path is None: raise ValueError(f'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) else: if is_local_path(a ): UpperCamelCase__ = PIL.Image.open(a ) else: UpperCamelCase__ = path.split("::" )[-1] try: UpperCamelCase__ = string_to_dict(a , config.HUB_DATASETS_URL )["repo_id"] UpperCamelCase__ = token_per_repo_id.get(a ) except ValueError: UpperCamelCase__ = None with xopen(a , "rb" , use_auth_token=a ) as f: UpperCamelCase__ = BytesIO(f.read() ) UpperCamelCase__ = PIL.Image.open(bytes_ ) else: UpperCamelCase__ = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __a ( self ): from .features import Value return ( self if self.decode else { "bytes": Value("binary" ), "path": Value("string" ), } ) def __a ( self , a ): if pa.types.is_string(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCamelCase__ = storage.field("bytes" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCamelCase__ = storage.field("path" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): UpperCamelCase__ = pa.array( [encode_np_array(np.array(a ) )["bytes"] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays( [bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def __a ( self , a ): @no_op_if_value_is_null def path_to_bytes(a ): with xopen(a , "rb" ) as f: UpperCamelCase__ = f.read() return bytes_ UpperCamelCase__ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCamelCase__ = pa.array( [os.path.basename(a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def _UpperCamelCase ( ) -> List[str]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() UpperCamelCase__ = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def _UpperCamelCase ( __A ) -> bytes: '''simple docstring''' UpperCamelCase__ = BytesIO() if image.format in list_image_compression_formats(): UpperCamelCase__ = image.format else: UpperCamelCase__ = "PNG" if image.mode in ["1", "L", "LA", "RGB", "RGBA"] else "TIFF" image.save(__A , format=__A ) return buffer.getvalue() def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if hasattr(__A , "filename" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) UpperCamelCase__ = array.dtype UpperCamelCase__ = dtype.byteorder if dtype.byteorder != "=" else _NATIVE_BYTEORDER UpperCamelCase__ = dtype.kind UpperCamelCase__ = dtype.itemsize UpperCamelCase__ = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: UpperCamelCase__ = np.dtype("|u1" ) if dtype_kind not in ["u", "i"]: raise TypeError( F'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.''' ) if dtype is not dest_dtype: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: UpperCamelCase__ = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: UpperCamelCase__ = dtype_byteorder + dtype_kind + str(__A ) UpperCamelCase__ = np.dtype(__A ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}''' ) UpperCamelCase__ = PIL.Image.fromarray(array.astype(__A ) ) return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> List[dict]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if objs: UpperCamelCase__ , UpperCamelCase__ = first_non_null_value(__A ) if isinstance(__A , __A ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__A , np.ndarray ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] elif isinstance(__A , PIL.Image.Image ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] else: return objs else: return objs
80
0
'''simple docstring''' from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = CustomTokenizer pass
35
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> int: '''simple docstring''' if depth < 0: raise ValueError("Depth cannot be less than 0" ) if not scores: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) ) def _UpperCamelCase ( ) -> None: '''simple docstring''' UpperCamelCase__ = [90, 23, 6, 33, 21, 65, 123, 34423] UpperCamelCase__ = math.log(len(__A ) , 2 ) print(F'''Optimal value : {minimax(0 , 0 , __A , __A , __A )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
80
0
import argparse import json import subprocess def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Any = [] _lowerCAmelCase : Optional[int] = ( F"curl -H \"Accept: application/vnd.github+json\" -H \"Authorization: Bearer {token}\"" " https://api.github.com/repos/huggingface/transformers/actions/runners" ) _lowerCAmelCase : Any = subprocess.run(_lowerCamelCase , shell=_lowerCamelCase , stdout=subprocess.PIPE ) _lowerCAmelCase : Tuple = output.stdout.decode("utf-8" ) _lowerCAmelCase : Dict = json.loads(_lowerCamelCase ) _lowerCAmelCase : Optional[Any] = status["runners"] for runner in runners: if runner["name"] in target_runners: if runner["status"] == "offline": offline_runners.append(_lowerCamelCase ) # save the result so we can report them on Slack with open("offline_runners.txt" , "w" ) as fp: fp.write(json.dumps(_lowerCamelCase ) ) if len(_lowerCamelCase ) > 0: _lowerCAmelCase : Tuple = "\n".join([x["name"] for x in offline_runners] ) raise ValueError(F"The following runners are offline:\n{failed}" ) if __name__ == "__main__": def A ( _lowerCamelCase ): '''simple docstring''' return values.split("," ) _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( "--target_runners", default=None, type=list_str, required=True, help="Comma-separated list of runners to check status.", ) parser.add_argument( "--token", default=None, type=str, required=True, help="A token that has actions:read permission." ) _snake_case = parser.parse_args() get_runner_status(args.target_runners, args.token)
36
'''simple docstring''' def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def _UpperCamelCase ( __A = 100 ) -> int: '''simple docstring''' UpperCamelCase__ = 1 UpperCamelCase__ = 2 for i in range(2 , max_n + 1 ): UpperCamelCase__ = pre_numerator UpperCamelCase__ = 2 * i // 3 if i % 3 == 0 else 1 UpperCamelCase__ = cur_numerator UpperCamelCase__ = e_cont * pre_numerator + temp return sum_digits(__A ) if __name__ == "__main__": print(F"""{solution() = }""")
80
0
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" if "cls_token" in name: lowerCAmelCase__ : Dict = name.replace("""cls_token""" , """vit.embeddings.cls_token""" ) if "mask_token" in name: lowerCAmelCase__ : Any = name.replace("""mask_token""" , """decoder.mask_token""" ) if "decoder_pos_embed" in name: lowerCAmelCase__ : str = name.replace("""decoder_pos_embed""" , """decoder.decoder_pos_embed""" ) if "pos_embed" in name and "decoder" not in name: lowerCAmelCase__ : List[str] = name.replace("""pos_embed""" , """vit.embeddings.position_embeddings""" ) if "patch_embed.proj" in name: lowerCAmelCase__ : List[Any] = name.replace("""patch_embed.proj""" , """vit.embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: lowerCAmelCase__ : Optional[Any] = name.replace("""patch_embed.norm""" , """vit.embeddings.norm""" ) if "decoder_blocks" in name: lowerCAmelCase__ : Optional[int] = name.replace("""decoder_blocks""" , """decoder.decoder_layers""" ) if "blocks" in name: lowerCAmelCase__ : Optional[int] = name.replace("""blocks""" , """vit.encoder.layer""" ) if "attn.proj" in name: lowerCAmelCase__ : Optional[Any] = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: lowerCAmelCase__ : Optional[int] = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: lowerCAmelCase__ : Dict = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: lowerCAmelCase__ : Dict = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: lowerCAmelCase__ : Union[str, Any] = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: lowerCAmelCase__ : List[Any] = name.replace("""mlp.fc2""" , """output.dense""" ) if "decoder_embed" in name: lowerCAmelCase__ : Tuple = name.replace("""decoder_embed""" , """decoder.decoder_embed""" ) if "decoder_norm" in name: lowerCAmelCase__ : int = name.replace("""decoder_norm""" , """decoder.decoder_norm""" ) if "decoder_pred" in name: lowerCAmelCase__ : int = name.replace("""decoder_pred""" , """decoder.decoder_pred""" ) if "norm.weight" in name and "decoder" not in name: lowerCAmelCase__ : Tuple = name.replace("""norm.weight""" , """vit.layernorm.weight""" ) if "norm.bias" in name and "decoder" not in name: lowerCAmelCase__ : Dict = name.replace("""norm.bias""" , """vit.layernorm.bias""" ) return name def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase ): """simple docstring""" for key in orig_state_dict.copy().keys(): lowerCAmelCase__ : Any = orig_state_dict.pop(UpperCamelCase ) if "qkv" in key: lowerCAmelCase__ : str = key.split(""".""" ) lowerCAmelCase__ : Optional[int] = int(key_split[1] ) if "decoder_blocks" in key: lowerCAmelCase__ : str = config.decoder_hidden_size lowerCAmelCase__ : Any = """decoder.decoder_layers.""" if "weight" in key: lowerCAmelCase__ : int = val[:dim, :] lowerCAmelCase__ : Union[str, Any] = val[dim : dim * 2, :] lowerCAmelCase__ : Optional[int] = val[-dim:, :] elif "bias" in key: lowerCAmelCase__ : Dict = val[:dim] lowerCAmelCase__ : Any = val[dim : dim * 2] lowerCAmelCase__ : int = val[-dim:] else: lowerCAmelCase__ : Tuple = config.hidden_size lowerCAmelCase__ : Any = """vit.encoder.layer.""" if "weight" in key: lowerCAmelCase__ : List[Any] = val[:dim, :] lowerCAmelCase__ : int = val[dim : dim * 2, :] lowerCAmelCase__ : Optional[Any] = val[-dim:, :] elif "bias" in key: lowerCAmelCase__ : int = val[:dim] lowerCAmelCase__ : Optional[Any] = val[dim : dim * 2] lowerCAmelCase__ : Any = val[-dim:] else: lowerCAmelCase__ : List[str] = val return orig_state_dict def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : List[str] = ViTMAEConfig() if "large" in checkpoint_url: lowerCAmelCase__ : Optional[int] = 1024 lowerCAmelCase__ : int = 4096 lowerCAmelCase__ : Any = 24 lowerCAmelCase__ : Any = 16 elif "huge" in checkpoint_url: lowerCAmelCase__ : List[Any] = 14 lowerCAmelCase__ : str = 1280 lowerCAmelCase__ : Dict = 5120 lowerCAmelCase__ : Any = 32 lowerCAmelCase__ : Union[str, Any] = 16 lowerCAmelCase__ : Tuple = ViTMAEForPreTraining(UpperCamelCase ) lowerCAmelCase__ : Tuple = torch.hub.load_state_dict_from_url(UpperCamelCase , map_location="""cpu""" )["""model"""] lowerCAmelCase__ : str = ViTMAEImageProcessor(size=config.image_size ) lowerCAmelCase__ : str = convert_state_dict(UpperCamelCase , UpperCamelCase ) model.load_state_dict(UpperCamelCase ) model.eval() lowerCAmelCase__ : List[str] = """https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg""" lowerCAmelCase__ : Tuple = Image.open(requests.get(UpperCamelCase , stream=UpperCamelCase ).raw ) lowerCAmelCase__ : int = ViTMAEImageProcessor(size=config.image_size ) lowerCAmelCase__ : Optional[Any] = image_processor(images=UpperCamelCase , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) lowerCAmelCase__ : str = model(**UpperCamelCase ) lowerCAmelCase__ : List[Any] = outputs.logits if "large" in checkpoint_url: lowerCAmelCase__ : List[str] = torch.tensor( [[-0.7309, -0.7128, -1.0169], [-1.0161, -0.9058, -1.1878], [-1.0478, -0.9411, -1.1911]] ) elif "huge" in checkpoint_url: lowerCAmelCase__ : Union[str, Any] = torch.tensor( [[-1.1599, -0.9199, -1.2221], [-1.1952, -0.9269, -1.2307], [-1.2143, -0.9337, -1.2262]] ) else: lowerCAmelCase__ : int = torch.tensor( [[-0.9192, -0.8481, -1.1259], [-1.1349, -1.0034, -1.2599], [-1.1757, -1.0429, -1.2726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , UpperCamelCase , atol=1e-4 ) print(f"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(UpperCamelCase ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(UpperCamelCase ) if __name__ == "__main__": _lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth''', type=str, help='''URL of the checkpoint 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 = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
37
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' with open(__A ) as metadata_file: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = LukeConfig(use_entity_aware_attention=__A , **metadata["model_config"] ) # Load in the weights from the checkpoint_path UpperCamelCase__ = torch.load(__A , map_location="cpu" )["module"] # Load the entity vocab file UpperCamelCase__ = load_original_entity_vocab(__A ) # add an entry for [MASK2] UpperCamelCase__ = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase__ = XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase__ = AddedToken("<ent>" , lstrip=__A , rstrip=__A ) UpperCamelCase__ = AddedToken("<ent2>" , lstrip=__A , rstrip=__A ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'''Saving tokenizer to {pytorch_dump_folder_path}''' ) tokenizer.save_pretrained(__A ) with open(os.path.join(__A , "tokenizer_config.json" ) , "r" ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = "MLukeTokenizer" with open(os.path.join(__A , "tokenizer_config.json" ) , "w" ) as f: json.dump(__A , __A ) with open(os.path.join(__A , MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(__A , __A ) UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) # Initialize the embeddings of the special tokens UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["@"] )[0] UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["#"] )[0] UpperCamelCase__ = state_dict["embeddings.word_embeddings.weight"] UpperCamelCase__ = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase__ = state_dict[bias_name] UpperCamelCase__ = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: UpperCamelCase__ = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase__ = state_dict["entity_embeddings.entity_embeddings.weight"] UpperCamelCase__ = entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase__ = state_dict["entity_predictions.bias"] UpperCamelCase__ = entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase__ = LukeForMaskedLM(config=__A ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) UpperCamelCase__ = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): UpperCamelCase__ = state_dict[key] else: UpperCamelCase__ = state_dict[key] UpperCamelCase__ , UpperCamelCase__ = model.load_state_dict(__A , strict=__A ) if set(__A ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(__A ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A , task="entity_classification" ) UpperCamelCase__ = "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." UpperCamelCase__ = (0, 9) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 33, 768) ) UpperCamelCase__ = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}''' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 1, 768) ) UpperCamelCase__ = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is''' F''' {expected_shape}''' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) UpperCamelCase__ = "Tokyo is the capital of <mask>." UpperCamelCase__ = (24, 30) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) UpperCamelCase__ = encoding["input_ids"][0].tolist() UpperCamelCase__ = input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) UpperCamelCase__ = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(__A ) UpperCamelCase__ = outputs.entity_logits[0][0].argmax().item() UpperCamelCase__ = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(__A ) ) model.save_pretrained(__A ) def _UpperCamelCase ( __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = ["[MASK]", "[PAD]", "[UNK]"] UpperCamelCase__ = [json.loads(__A ) for line in open(__A )] UpperCamelCase__ = {} for entry in data: UpperCamelCase__ = entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase__ = entity_id break UpperCamelCase__ = F'''{language}:{entity_name}''' UpperCamelCase__ = entity_id return new_mapping if __name__ == "__main__": a__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) a__ : Any = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
80
0
import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase_ : List[Any] = logging.get_logger(__name__) UpperCAmelCase_ : Any = {'''vocab_file''': '''vocab.json'''} UpperCAmelCase_ : Union[str, Any] = { '''vocab_file''': { '''mgp-str''': '''https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json''', } } UpperCAmelCase_ : Dict = {'''mgp-str''': 27} class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Optional[Any] = VOCAB_FILES_NAMES snake_case__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP snake_case__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[str] , __lowerCamelCase : str , __lowerCamelCase : int="[GO]" , __lowerCamelCase : Union[str, Any]="[GO]" , __lowerCamelCase : Tuple="[s]" , __lowerCamelCase : Any="[GO]" , **__lowerCamelCase : Optional[int] ): super().__init__( unk_token=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , pad_token=__lowerCamelCase , **__lowerCamelCase , ) with open(__lowerCamelCase , encoding="""utf-8""" ) as vocab_handle: UpperCamelCase :Tuple = json.load(__lowerCamelCase ) UpperCamelCase :int = {v: k for k, v in self.vocab.items()} @property def _A ( self : Optional[Any] ): return len(self.vocab ) def _A ( self : int ): return dict(self.vocab , **self.added_tokens_encoder ) def _A ( self : Union[str, Any] , __lowerCamelCase : Tuple ): UpperCamelCase :List[Any] = [] for s in text: char_tokens.extend(__lowerCamelCase ) return char_tokens def _A ( self : int , __lowerCamelCase : List[Any] ): return self.vocab.get(__lowerCamelCase , self.vocab.get(self.unk_token ) ) def _A ( self : str , __lowerCamelCase : List[Any] ): return self.decoder.get(__lowerCamelCase ) def _A ( self : Tuple , __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ): if not os.path.isdir(__lowerCamelCase ): logger.error("""Vocabulary path ({}) should be a directory""".format(__lowerCamelCase ) ) return UpperCamelCase :List[str] = os.path.join( __lowerCamelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) with open(__lowerCamelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=__lowerCamelCase , ensure_ascii=__lowerCamelCase ) + """\n""" ) return (vocab_file,)
38
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Any = logging.get_logger(__name__) a__ : str = { 'SCUT-DLVCLab/lilt-roberta-en-base': ( 'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json' ), } class lowercase_ ( a__ ): __UpperCAmelCase = 'lilt' def __init__( self , a=3_05_22 , a=7_68 , a=12 , a=12 , a=30_72 , a="gelu" , a=0.1 , a=0.1 , a=5_12 , a=2 , a=0.02 , a=1e-12 , a=0 , a="absolute" , a=None , a=4 , a=10_24 , **a , ): super().__init__(pad_token_id=a , **a ) UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = position_embedding_type UpperCamelCase__ = classifier_dropout UpperCamelCase__ = channel_shrink_ratio UpperCamelCase__ = max_ad_position_embeddings
80
0
import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class __lowerCamelCase ( snake_case__): """simple docstring""" UpperCamelCase__ = ["image_processor", "tokenizer"] UpperCamelCase__ = "BlipImageProcessor" UpperCamelCase__ = "AutoTokenizer" def __init__( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ): """simple docstring""" super().__init__(UpperCAmelCase , UpperCAmelCase ) # add QFormer tokenizer _UpperCAmelCase = qformer_tokenizer def __call__( self , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = True , UpperCAmelCase = False , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = 0 , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = False , UpperCAmelCase = False , UpperCAmelCase = False , UpperCAmelCase = False , UpperCAmelCase = False , UpperCAmelCase = True , UpperCAmelCase = None , **UpperCAmelCase , ): """simple docstring""" if images is None and text is None: raise ValueError('You have to specify at least images or text.' ) _UpperCAmelCase = BatchFeature() if text is not None: _UpperCAmelCase = self.tokenizer( text=UpperCAmelCase , add_special_tokens=UpperCAmelCase , padding=UpperCAmelCase , truncation=UpperCAmelCase , max_length=UpperCAmelCase , stride=UpperCAmelCase , pad_to_multiple_of=UpperCAmelCase , return_attention_mask=UpperCAmelCase , return_overflowing_tokens=UpperCAmelCase , return_special_tokens_mask=UpperCAmelCase , return_offsets_mapping=UpperCAmelCase , return_token_type_ids=UpperCAmelCase , return_length=UpperCAmelCase , verbose=UpperCAmelCase , return_tensors=UpperCAmelCase , **UpperCAmelCase , ) encoding.update(UpperCAmelCase ) _UpperCAmelCase = self.qformer_tokenizer( text=UpperCAmelCase , add_special_tokens=UpperCAmelCase , padding=UpperCAmelCase , truncation=UpperCAmelCase , max_length=UpperCAmelCase , stride=UpperCAmelCase , pad_to_multiple_of=UpperCAmelCase , return_attention_mask=UpperCAmelCase , return_overflowing_tokens=UpperCAmelCase , return_special_tokens_mask=UpperCAmelCase , return_offsets_mapping=UpperCAmelCase , return_token_type_ids=UpperCAmelCase , return_length=UpperCAmelCase , verbose=UpperCAmelCase , return_tensors=UpperCAmelCase , **UpperCAmelCase , ) _UpperCAmelCase = qformer_text_encoding.pop('input_ids' ) _UpperCAmelCase = qformer_text_encoding.pop('attention_mask' ) if images is not None: _UpperCAmelCase = self.image_processor(UpperCAmelCase , return_tensors=UpperCAmelCase ) encoding.update(UpperCAmelCase ) return encoding def UpperCamelCase ( self , *UpperCAmelCase , **UpperCAmelCase ): """simple docstring""" return self.tokenizer.batch_decode(*UpperCAmelCase , **UpperCAmelCase ) def UpperCamelCase ( self , *UpperCAmelCase , **UpperCAmelCase ): """simple docstring""" return self.tokenizer.decode(*UpperCAmelCase , **UpperCAmelCase ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = self.tokenizer.model_input_names _UpperCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def UpperCamelCase ( self , UpperCAmelCase , **UpperCAmelCase ): """simple docstring""" if os.path.isfile(UpperCAmelCase ): raise ValueError(F"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(UpperCAmelCase , exist_ok=UpperCAmelCase ) _UpperCAmelCase = os.path.join(UpperCAmelCase , 'qformer_tokenizer' ) self.qformer_tokenizer.save_pretrained(UpperCAmelCase ) return super().save_pretrained(UpperCAmelCase , **UpperCAmelCase ) @classmethod def UpperCamelCase ( cls , UpperCAmelCase , **UpperCAmelCase ): """simple docstring""" _UpperCAmelCase = AutoTokenizer.from_pretrained(UpperCAmelCase , subfolder='qformer_tokenizer' ) _UpperCAmelCase = cls._get_arguments_from_pretrained(UpperCAmelCase , **UpperCAmelCase ) args.append(UpperCAmelCase ) return cls(*UpperCAmelCase )
39
'''simple docstring''' a__ : Union[str, Any] = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution a__ : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 a__ : Optional[Any] = True a__ : Optional[Any] = False def _UpperCamelCase ( __A ) -> bool: '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__A ) ) UpperCamelCase__ = number_chain while number < 10000000: UpperCamelCase__ = number_chain number *= 10 return number_chain def _UpperCamelCase ( __A = 10000000 ) -> int: '''simple docstring''' for i in range(1 , __A ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__A ) if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution() = }""")
80
0
"""simple docstring""" import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowercase ( A_ )-> List[Any]: '''simple docstring''' monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" , set() ) @pytest.fixture def lowercase ( A_ )-> Tuple: '''simple docstring''' class _A : """simple docstring""" def __init__( self : str , __UpperCAmelCase : int): a : List[Any] = metric_id class _A : """simple docstring""" UpperCAmelCase : Union[str, Any] = [MetricMock(_a ) for metric_id in ["""accuracy""", """mse""", """precision""", """codeparrot/apps_metric"""]] def __snake_case ( self : List[str]): return self._metrics monkeypatch.setattr("datasets.inspect.huggingface_hub" , HfhMock() ) @pytest.mark.parametrize( "func, args" , [(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] ) def lowercase ( A_ , A_ , A_ , A_ , A_ )-> Any: '''simple docstring''' if "tmp_path" in args: a : Union[str, Any] = tuple(arg if arg != "tmp_path" else tmp_path for arg in args ) with pytest.warns(A_ , match="https://huggingface.co/docs/evaluate" ): func(*A_ )
40
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def _UpperCamelCase ( __A , __A , __A=1024 , __A=1024 , __A=False , **__A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = AutoTokenizer.from_pretrained(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="train" , **__A ) UpperCamelCase__ = tok.pad_token_id def get_lens(__A ): UpperCamelCase__ = tqdm( DataLoader(__A , batch_size=512 , num_workers=8 , shuffle=__A , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) UpperCamelCase__ = [] for batch in dl: UpperCamelCase__ = batch["input_ids"].ne(__A ).sum(1 ).tolist() UpperCamelCase__ = batch["labels"].ne(__A ).sum(1 ).tolist() if consider_target: for src, tgt in zip(__A , __A ): max_lens.append(max(__A , __A ) ) else: max_lens.extend(__A ) return max_lens UpperCamelCase__ = get_lens(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="val" , **__A ) UpperCamelCase__ = get_lens(__A ) pickle_save(__A , train_ds.len_file ) pickle_save(__A , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
80
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _A : Dict ={ '''configuration_clip''': [ '''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPConfig''', '''CLIPOnnxConfig''', '''CLIPTextConfig''', '''CLIPVisionConfig''', ], '''processing_clip''': ['''CLIPProcessor'''], '''tokenization_clip''': ['''CLIPTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Dict =['''CLIPTokenizerFast'''] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Optional[int] =['''CLIPFeatureExtractor'''] _A : List[Any] =['''CLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : List[str] =[ '''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPModel''', '''CLIPPreTrainedModel''', '''CLIPTextModel''', '''CLIPTextModelWithProjection''', '''CLIPVisionModel''', '''CLIPVisionModelWithProjection''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Union[str, Any] =[ '''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCLIPModel''', '''TFCLIPPreTrainedModel''', '''TFCLIPTextModel''', '''TFCLIPVisionModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Dict =[ '''FlaxCLIPModel''', '''FlaxCLIPPreTrainedModel''', '''FlaxCLIPTextModel''', '''FlaxCLIPTextPreTrainedModel''', '''FlaxCLIPVisionModel''', '''FlaxCLIPVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys _A : Optional[Any] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
41
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer a__ : int = logging.get_logger(__name__) a__ : List[str] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a__ : List[Any] = { 'vocab_file': { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt' ), } } a__ : Optional[Any] = { 'junnyu/roformer_chinese_small': 1_5_3_6, 'junnyu/roformer_chinese_base': 1_5_3_6, 'junnyu/roformer_chinese_char_small': 5_1_2, 'junnyu/roformer_chinese_char_base': 5_1_2, 'junnyu/roformer_small_discriminator': 1_2_8, 'junnyu/roformer_small_generator': 1_2_8, } a__ : str = { 'junnyu/roformer_chinese_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_base': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_base': {'do_lower_case': True}, 'junnyu/roformer_small_discriminator': {'do_lower_case': True}, 'junnyu/roformer_small_generator': {'do_lower_case': True}, } class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase = RoFormerTokenizer def __init__( self , a=None , a=None , a=True , a="[UNK]" , a="[SEP]" , a="[PAD]" , a="[CLS]" , a="[MASK]" , a=True , a=None , **a , ): super().__init__( a , tokenizer_file=a , do_lower_case=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , tokenize_chinese_chars=a , strip_accents=a , **a , ) UpperCamelCase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , a ) != do_lower_case or pre_tok_state.get("strip_accents" , a ) != strip_accents ): UpperCamelCase__ = getattr(a , pre_tok_state.pop("type" ) ) UpperCamelCase__ = do_lower_case UpperCamelCase__ = strip_accents UpperCamelCase__ = pre_tok_class(**a ) UpperCamelCase__ = do_lower_case def __getstate__( self ): UpperCamelCase__ = self.__dict__.copy() UpperCamelCase__ = BertPreTokenizer() return state def __setstate__( self , a ): UpperCamelCase__ = d UpperCamelCase__ = self.__dict__["_tokenizer"].get_vocab() UpperCamelCase__ = PreTokenizer.custom(JiebaPreTokenizer(a ) ) def __a ( self , a , a=None ): UpperCamelCase__ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __a ( self , a , a = None ): UpperCamelCase__ = [self.sep_token_id] UpperCamelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __a ( self , a , a = None ): UpperCamelCase__ = self._tokenizer.model.save(a , name=a ) return tuple(a ) def __a ( self , a , a=None , a=None , a=False , **a , ): UpperCamelCase__ = BertPreTokenizer() return super().save_pretrained(a , a , a , a , **a )
80
0
'''simple docstring''' import math class __UpperCAmelCase : def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = 0.0 _snake_case = 0.0 for i in range(len(lowerCAmelCase_ ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" for i in range(len(lowerCAmelCase_ ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def SCREAMING_SNAKE_CASE__ ( ) -> None: # Training Examples ( m, n ) _snake_case = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) _snake_case = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training _snake_case = SelfOrganizingMap() _snake_case = 3 _snake_case = 0.5 for _ in range(__A ): for j in range(len(__A ) ): # training sample _snake_case = training_samples[j] # Compute the winning vector _snake_case = self_organizing_map.get_winner(__A , __A ) # Update the winning vector _snake_case = self_organizing_map.update(__A , __A , __A , __A ) # classify test sample _snake_case = [0, 0, 0, 1] _snake_case = self_organizing_map.get_winner(__A , __A ) # results print(F'Clusters that the test sample belongs to : {winner}' ) print(F'Weights that have been trained : {weights}' ) # running the main() function if __name__ == "__main__": main()
42
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : Optional[int] = {'vocab_file': 'vocab.txt'} a__ : Optional[Any] = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } a__ : Optional[int] = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def _UpperCamelCase ( __A ) -> str: '''simple docstring''' with open(__A , "r" ) as f: UpperCamelCase__ = f.read().splitlines() return [l.strip() for l in lines] class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self , a , a="<unk>" , a="<cls>" , a="<pad>" , a="<mask>" , a="<eos>" , **a , ): super().__init__(**a ) UpperCamelCase__ = load_vocab_file(a ) UpperCamelCase__ = dict(enumerate(self.all_tokens ) ) UpperCamelCase__ = {tok: ind for ind, tok in enumerate(self.all_tokens )} UpperCamelCase__ = unk_token UpperCamelCase__ = cls_token UpperCamelCase__ = pad_token UpperCamelCase__ = mask_token UpperCamelCase__ = eos_token UpperCamelCase__ = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a , **a ): return text.split() def __a ( self , a=False ): return len(self._id_to_token ) def __a ( self ): return {token: i for i, token in enumerate(self.all_tokens )} def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a , a = None ): UpperCamelCase__ = [self.cls_token_id] UpperCamelCase__ = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError("Cannot tokenize multiple sequences when EOS token is not set!" ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __a ( self , a , a = None , a = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] UpperCamelCase__ = [1] + ([0] * len(a )) + [1] if token_ids_a is not None: mask += [0] * len(a ) + [1] return mask def __a ( self , a , a ): UpperCamelCase__ = os.path.join(a , (filename_prefix + "-" if filename_prefix else "") + "vocab.txt" ) with open(a , "w" ) as f: f.write("\n".join(self.all_tokens ) ) return (vocab_file,) @property def __a ( self ): return self.get_vocab_size(with_added_tokens=a ) def __a ( self , a , a = False ): return super()._add_tokens(a , special_tokens=a )
80
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCamelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' a__ : Tuple = StableDiffusionInstructPixaPixPipeline a__ : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width""", """cross_attention_kwargs"""} a__ : Any = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS a__ : Any = IMAGE_TO_IMAGE_IMAGE_PARAMS a__ : Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def UpperCamelCase__ ( self) -> Optional[int]: torch.manual_seed(0) __UpperCamelCase :Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) __UpperCamelCase :Dict = PNDMScheduler(skip_prk_steps=__lowercase) torch.manual_seed(0) __UpperCamelCase :Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0) __UpperCamelCase :Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) __UpperCamelCase :List[Any] = CLIPTextModel(__lowercase) __UpperCamelCase :str = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''') __UpperCamelCase :List[str] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def UpperCamelCase__ ( self , __lowercase , __lowercase=0) -> Union[str, Any]: __UpperCamelCase :Optional[Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(__lowercase)).to(__lowercase) __UpperCamelCase :Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1)[0] __UpperCamelCase :Tuple = Image.fromarray(np.uinta(__lowercase)).convert('''RGB''') if str(__lowercase).startswith('''mps'''): __UpperCamelCase :List[Any] = torch.manual_seed(__lowercase) else: __UpperCamelCase :Any = torch.Generator(device=__lowercase).manual_seed(__lowercase) __UpperCamelCase :Dict = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''image_guidance_scale''': 1, '''output_type''': '''numpy''', } return inputs def UpperCamelCase__ ( self) -> Dict: __UpperCamelCase :List[str] = '''cpu''' # ensure determinism for the device-dependent torch.Generator __UpperCamelCase :Dict = self.get_dummy_components() __UpperCamelCase :List[Any] = StableDiffusionInstructPixaPixPipeline(**__lowercase) __UpperCamelCase :List[str] = sd_pipe.to(__lowercase) sd_pipe.set_progress_bar_config(disable=__lowercase) __UpperCamelCase :List[str] = self.get_dummy_inputs(__lowercase) __UpperCamelCase :int = sd_pipe(**__lowercase).images __UpperCamelCase :int = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __UpperCamelCase :List[Any] = np.array([0.75_26, 0.37_50, 0.45_47, 0.61_17, 0.58_66, 0.50_16, 0.43_27, 0.56_42, 0.48_15]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-3 def UpperCamelCase__ ( self) -> Optional[Any]: __UpperCamelCase :int = '''cpu''' # ensure determinism for the device-dependent torch.Generator __UpperCamelCase :Dict = self.get_dummy_components() __UpperCamelCase :int = StableDiffusionInstructPixaPixPipeline(**__lowercase) __UpperCamelCase :List[Any] = sd_pipe.to(__lowercase) sd_pipe.set_progress_bar_config(disable=__lowercase) __UpperCamelCase :Any = self.get_dummy_inputs(__lowercase) __UpperCamelCase :int = '''french fries''' __UpperCamelCase :Tuple = sd_pipe(**__lowercase , negative_prompt=__lowercase) __UpperCamelCase :Dict = output.images __UpperCamelCase :Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __UpperCamelCase :List[Any] = np.array([0.75_11, 0.36_42, 0.45_53, 0.62_36, 0.57_97, 0.50_13, 0.43_43, 0.56_11, 0.48_31]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-3 def UpperCamelCase__ ( self) -> Tuple: __UpperCamelCase :int = '''cpu''' # ensure determinism for the device-dependent torch.Generator __UpperCamelCase :str = self.get_dummy_components() __UpperCamelCase :str = StableDiffusionInstructPixaPixPipeline(**__lowercase) __UpperCamelCase :List[Any] = sd_pipe.to(__lowercase) sd_pipe.set_progress_bar_config(disable=__lowercase) __UpperCamelCase :List[Any] = self.get_dummy_inputs(__lowercase) __UpperCamelCase :Tuple = [inputs['''prompt''']] * 2 __UpperCamelCase :Dict = np.array(inputs['''image''']).astype(np.floataa) / 2_55.0 __UpperCamelCase :Tuple = torch.from_numpy(__lowercase).unsqueeze(0).to(__lowercase) __UpperCamelCase :int = image / 2 + 0.5 __UpperCamelCase :List[str] = image.permute(0 , 3 , 1 , 2) __UpperCamelCase :Dict = image.repeat(2 , 1 , 1 , 1) __UpperCamelCase :Tuple = sd_pipe(**__lowercase).images __UpperCamelCase :Optional[int] = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) __UpperCamelCase :List[str] = np.array([0.58_12, 0.57_48, 0.52_22, 0.59_08, 0.56_95, 0.71_74, 0.68_04, 0.55_23, 0.55_79]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-3 def UpperCamelCase__ ( self) -> List[str]: __UpperCamelCase :List[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator __UpperCamelCase :Union[str, Any] = self.get_dummy_components() __UpperCamelCase :Union[str, Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='''scaled_linear''') __UpperCamelCase :Any = StableDiffusionInstructPixaPixPipeline(**__lowercase) __UpperCamelCase :Union[str, Any] = sd_pipe.to(__lowercase) sd_pipe.set_progress_bar_config(disable=__lowercase) __UpperCamelCase :Optional[Any] = self.get_dummy_inputs(__lowercase) __UpperCamelCase :int = sd_pipe(**__lowercase).images __UpperCamelCase :List[Any] = image[0, -3:, -3:, -1] __UpperCamelCase :str = [round(__lowercase , 4) for x in image_slice.flatten().tolist()] print(''','''.join([str(__lowercase) for x in slice])) assert image.shape == (1, 32, 32, 3) __UpperCamelCase :str = np.array([0.74_17, 0.38_42, 0.47_32, 0.57_76, 0.58_91, 0.51_39, 0.40_52, 0.56_73, 0.49_86]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-3 def UpperCamelCase__ ( self) -> Union[str, Any]: super().test_inference_batch_single_identical(expected_max_diff=3E-3) def UpperCamelCase__ ( self) -> List[str]: __UpperCamelCase :int = self.get_dummy_components() __UpperCamelCase :Any = StableDiffusionInstructPixaPixPipeline(**__lowercase) __UpperCamelCase :Union[str, Any] = VaeImageProcessor(do_resize=__lowercase , do_normalize=__lowercase) __UpperCamelCase :Dict = pipe.to(__lowercase) pipe.set_progress_bar_config(disable=__lowercase) __UpperCamelCase :Any = pipe(**self.get_dummy_inputs_by_type(__lowercase , input_image_type='''pt'''))[0] __UpperCamelCase :int = components['''vae'''] __UpperCamelCase :Dict = self.get_dummy_inputs_by_type(__lowercase , input_image_type='''pt''') for image_param in self.image_latents_params: if image_param in inputs.keys(): __UpperCamelCase :str = vae.encode(inputs[image_param]).latent_dist.mode() __UpperCamelCase :Tuple = pipe(**__lowercase)[0] __UpperCamelCase :Optional[Any] = np.abs(out - out_latents_inputs).max() self.assertLess(__lowercase , 1E-4 , '''passing latents as image input generate different result from passing image''') @slow @require_torch_gpu class lowerCamelCase_ ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ ( self) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self , __lowercase=0) -> List[Any]: __UpperCamelCase :Optional[int] = torch.manual_seed(__lowercase) __UpperCamelCase :Optional[Any] = load_image( '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg''') __UpperCamelCase :Any = { '''prompt''': '''turn him into a cyborg''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''image_guidance_scale''': 1.0, '''output_type''': '''numpy''', } return inputs def UpperCamelCase__ ( self) -> Tuple: __UpperCamelCase :Any = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=__lowercase) pipe.to(__lowercase) pipe.set_progress_bar_config(disable=__lowercase) pipe.enable_attention_slicing() __UpperCamelCase :Union[str, Any] = self.get_inputs() __UpperCamelCase :Dict = pipe(**__lowercase).images __UpperCamelCase :Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) __UpperCamelCase :Any = np.array([0.59_02, 0.60_15, 0.60_27, 0.59_83, 0.60_92, 0.60_61, 0.57_65, 0.57_85, 0.55_55]) assert np.abs(expected_slice - image_slice).max() < 1E-3 def UpperCamelCase__ ( self) -> Any: __UpperCamelCase :int = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=__lowercase) __UpperCamelCase :Dict = LMSDiscreteScheduler.from_config(pipe.scheduler.config) pipe.to(__lowercase) pipe.set_progress_bar_config(disable=__lowercase) pipe.enable_attention_slicing() __UpperCamelCase :Any = self.get_inputs() __UpperCamelCase :Union[str, Any] = pipe(**__lowercase).images __UpperCamelCase :int = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) __UpperCamelCase :List[str] = np.array([0.65_78, 0.68_17, 0.69_72, 0.67_61, 0.68_56, 0.69_16, 0.64_28, 0.65_16, 0.63_01]) assert np.abs(expected_slice - image_slice).max() < 1E-3 def UpperCamelCase__ ( self) -> str: __UpperCamelCase :Dict = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=__lowercase) __UpperCamelCase :List[Any] = DDIMScheduler.from_config(pipe.scheduler.config) pipe.to(__lowercase) pipe.set_progress_bar_config(disable=__lowercase) pipe.enable_attention_slicing() __UpperCamelCase :Any = self.get_inputs() __UpperCamelCase :Dict = pipe(**__lowercase).images __UpperCamelCase :List[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) __UpperCamelCase :List[str] = np.array([0.38_28, 0.38_34, 0.38_18, 0.37_92, 0.38_65, 0.37_52, 0.37_92, 0.38_47, 0.37_53]) assert np.abs(expected_slice - image_slice).max() < 1E-3 def UpperCamelCase__ ( self) -> Optional[int]: __UpperCamelCase :Dict = 0 def callback_fn(__lowercase , __lowercase , __lowercase) -> None: __UpperCamelCase :Any = True nonlocal number_of_steps number_of_steps += 1 if step == 1: __UpperCamelCase :str = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) __UpperCamelCase :Optional[int] = latents[0, -3:, -3:, -1] __UpperCamelCase :Tuple = np.array([-0.24_63, -0.46_44, -0.97_56, 1.51_76, 1.44_14, 0.78_66, 0.98_97, 0.85_21, 0.79_83]) assert np.abs(latents_slice.flatten() - expected_slice).max() < 5E-2 elif step == 2: __UpperCamelCase :Optional[Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) __UpperCamelCase :str = latents[0, -3:, -3:, -1] __UpperCamelCase :int = np.array([-0.26_44, -0.46_26, -0.96_53, 1.51_76, 1.45_51, 0.76_86, 0.98_05, 0.84_52, 0.81_15]) assert np.abs(latents_slice.flatten() - expected_slice).max() < 5E-2 __UpperCamelCase :Tuple = False __UpperCamelCase :Optional[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=__lowercase , torch_dtype=torch.floataa) __UpperCamelCase :List[str] = pipe.to(__lowercase) pipe.set_progress_bar_config(disable=__lowercase) pipe.enable_attention_slicing() __UpperCamelCase :Dict = self.get_inputs() pipe(**__lowercase , callback=__lowercase , callback_steps=1) assert callback_fn.has_been_called assert number_of_steps == 3 def UpperCamelCase__ ( self) -> str: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __UpperCamelCase :Dict = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=__lowercase , torch_dtype=torch.floataa) __UpperCamelCase :Tuple = pipe.to(__lowercase) pipe.set_progress_bar_config(disable=__lowercase) pipe.enable_attention_slicing(1) pipe.enable_sequential_cpu_offload() __UpperCamelCase :Any = self.get_inputs() __UpperCamelCase :Tuple = pipe(**__lowercase) __UpperCamelCase :Union[str, Any] = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def UpperCamelCase__ ( self) -> str: __UpperCamelCase :Any = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 __UpperCamelCase :str = inputs['''image'''].resize((504, 504)) __UpperCamelCase :str = '''timbrooks/instruct-pix2pix''' __UpperCamelCase :str = StableDiffusionInstructPixaPixPipeline.from_pretrained( __lowercase , safety_checker=__lowercase , ) pipe.to(__lowercase) pipe.set_progress_bar_config(disable=__lowercase) pipe.enable_attention_slicing() __UpperCamelCase :int = pipe(**__lowercase) __UpperCamelCase :Tuple = output.images[0] __UpperCamelCase :Dict = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) __UpperCamelCase :List[str] = np.array([0.27_26, 0.25_29, 0.26_64, 0.26_55, 0.26_41, 0.26_42, 0.25_91, 0.26_49, 0.25_90]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5E-3
43
'''simple docstring''' from math import factorial, pi def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_sin() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(__A ) ) def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_cos() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(__A ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(1_0)) print(maclaurin_sin(-1_0)) print(maclaurin_sin(1_0, 1_5)) print(maclaurin_sin(-1_0, 1_5)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(1_0, 1_5)) print(maclaurin_cos(-1_0, 1_5))
80
0
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html _a : int = 'platform' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class __A : _UpperCamelCase : Dict = PegasusConfig _UpperCamelCase : List[Any] = {} _UpperCamelCase : Any = "gelu" def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=False , a__=99 , a__=32 , a__=5 , a__=4 , a__=37 , a__=0.1 , a__=0.1 , a__=20 , a__=2 , a__=1 , a__=0 , ): _lowerCAmelCase : List[str] = parent _lowerCAmelCase : Optional[int] = batch_size _lowerCAmelCase : str = seq_length _lowerCAmelCase : Dict = is_training _lowerCAmelCase : int = use_labels _lowerCAmelCase : Optional[Any] = vocab_size _lowerCAmelCase : Optional[Any] = hidden_size _lowerCAmelCase : int = num_hidden_layers _lowerCAmelCase : Optional[int] = num_attention_heads _lowerCAmelCase : str = intermediate_size _lowerCAmelCase : List[str] = hidden_dropout_prob _lowerCAmelCase : int = attention_probs_dropout_prob _lowerCAmelCase : Union[str, Any] = max_position_embeddings _lowerCAmelCase : List[str] = eos_token_id _lowerCAmelCase : List[str] = pad_token_id _lowerCAmelCase : Tuple = bos_token_id def __A ( self ): _lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) _lowerCAmelCase : List[Any] = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) _lowerCAmelCase : Dict = np.concatenate([input_ids, eos_tensor] , axis=1 ) _lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCAmelCase : List[Any] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _lowerCAmelCase : List[Any] = prepare_pegasus_inputs_dict(a__ , a__ , a__ ) return config, inputs_dict def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : str = 20 _lowerCAmelCase : Tuple = model_class_name(a__ ) _lowerCAmelCase : Optional[Any] = model.encode(inputs_dict["""input_ids"""] ) _lowerCAmelCase , _lowerCAmelCase : Optional[int] = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) _lowerCAmelCase : Tuple = model.init_cache(decoder_input_ids.shape[0] , a__ , a__ ) _lowerCAmelCase : Union[str, Any] = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) _lowerCAmelCase : Any = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _lowerCAmelCase : Tuple = model.decode( decoder_input_ids[:, :-1] , a__ , decoder_attention_mask=a__ , past_key_values=a__ , decoder_position_ids=a__ , ) _lowerCAmelCase : str = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) _lowerCAmelCase : List[Any] = model.decode( decoder_input_ids[:, -1:] , a__ , decoder_attention_mask=a__ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=a__ , ) _lowerCAmelCase : Optional[int] = model.decode(a__ , a__ ) _lowerCAmelCase : Optional[int] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F"Max diff is {diff}" ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : Optional[Any] = 20 _lowerCAmelCase : Optional[Any] = model_class_name(a__ ) _lowerCAmelCase : Tuple = model.encode(inputs_dict["""input_ids"""] ) _lowerCAmelCase , _lowerCAmelCase : List[Any] = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) _lowerCAmelCase : Tuple = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) _lowerCAmelCase : List[Any] = model.init_cache(decoder_input_ids.shape[0] , a__ , a__ ) _lowerCAmelCase : Tuple = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _lowerCAmelCase : int = model.decode( decoder_input_ids[:, :-1] , a__ , decoder_attention_mask=a__ , past_key_values=a__ , decoder_position_ids=a__ , ) _lowerCAmelCase : Dict = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) _lowerCAmelCase : int = model.decode( decoder_input_ids[:, -1:] , a__ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=a__ , decoder_position_ids=a__ , ) _lowerCAmelCase : Any = model.decode(a__ , a__ , decoder_attention_mask=a__ ) _lowerCAmelCase : Any = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F"Max diff is {diff}" ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Tuple ,_lowerCamelCase : List[str] ,_lowerCamelCase : Union[str, Any] ,_lowerCamelCase : Union[str, Any]=None ,_lowerCamelCase : Dict=None ,) -> Union[str, Any]: if attention_mask is None: _lowerCAmelCase : int = np.not_equal(_lowerCamelCase ,config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: _lowerCAmelCase : Union[str, Any] = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape ,dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ).astype(np.inta ), ] ,axis=-1 ,) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : int = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) _UpperCamelCase : Tuple = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () _UpperCamelCase : str = True _UpperCamelCase : str = False _UpperCamelCase : List[Any] = False _UpperCamelCase : str = False def __A ( self ): _lowerCAmelCase : Dict = FlaxPegasusModelTester(self ) _lowerCAmelCase : List[str] = ConfigTester(self , config_class=a__ ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(a__ , a__ , a__ ) def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(a__ , a__ , a__ ) def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _lowerCAmelCase : List[str] = self._prepare_for_class(a__ , a__ ) _lowerCAmelCase : List[Any] = model_class(a__ ) @jax.jit def encode_jitted(a__ , a__=None , **a__ ): return model.encode(input_ids=a__ , attention_mask=a__ ) with self.subTest("""JIT Enabled""" ): _lowerCAmelCase : List[str] = encode_jitted(**a__ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): _lowerCAmelCase : Optional[Any] = encode_jitted(**a__ ).to_tuple() self.assertEqual(len(a__ ) , len(a__ ) ) for jitted_output, output in zip(a__ , a__ ): self.assertEqual(jitted_output.shape , output.shape ) def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _lowerCAmelCase : str = model_class(a__ ) _lowerCAmelCase : Optional[int] = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) _lowerCAmelCase : Optional[Any] = { """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(a__ , a__ , a__ ): return model.decode( decoder_input_ids=a__ , decoder_attention_mask=a__ , encoder_outputs=a__ , ) with self.subTest("""JIT Enabled""" ): _lowerCAmelCase : Optional[int] = decode_jitted(**a__ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): _lowerCAmelCase : Tuple = decode_jitted(**a__ ).to_tuple() self.assertEqual(len(a__ ) , len(a__ ) ) for jitted_output, output in zip(a__ , a__ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def __A ( self ): for model_class_name in self.all_model_classes: _lowerCAmelCase : Any = model_class_name.from_pretrained("""google/pegasus-large""" , from_pt=a__ ) _lowerCAmelCase : List[str] = np.ones((1, 1) ) _lowerCAmelCase : Optional[Any] = model(a__ ) self.assertIsNotNone(a__ ) @slow def __A ( self ): _lowerCAmelCase : int = FlaxPegasusForConditionalGeneration.from_pretrained("""google/pegasus-xsum""" ) _lowerCAmelCase : int = PegasusTokenizer.from_pretrained("""google/pegasus-xsum""" ) _lowerCAmelCase : List[str] = [ """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""", """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" """, ] _lowerCAmelCase : List[Any] = [ """California's largest electricity provider has turned off power to hundreds of thousands of customers.""", """Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.""", ] _lowerCAmelCase : Optional[int] = tokenizer(a__ , return_tensors="""np""" , truncation=a__ , max_length=512 , padding=a__ ) _lowerCAmelCase : Optional[Any] = model.generate(**a__ , num_beams=2 ).sequences _lowerCAmelCase : List[Any] = tokenizer.batch_decode(a__ , skip_special_tokens=a__ ) assert tgt_text == decoded
44
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class lowercase_ ( a__ ): def __init__( self , a , a , a = None , a = None , a = False , **a , ): super().__init__(features=a , cache_dir=a , keep_in_memory=a , **a ) UpperCamelCase__ = Sql( cache_dir=a , features=a , sql=a , con=a , **a , ) def __a ( self ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None self.builder.download_and_prepare( download_config=a , download_mode=a , verification_mode=a , base_path=a , ) # Build dataset for splits UpperCamelCase__ = self.builder.as_dataset( split="train" , verification_mode=a , in_memory=self.keep_in_memory ) return dataset class lowercase_ : def __init__( self , a , a , a , a = None , a = None , **a , ): if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) UpperCamelCase__ = dataset UpperCamelCase__ = name UpperCamelCase__ = con UpperCamelCase__ = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE UpperCamelCase__ = num_proc UpperCamelCase__ = to_sql_kwargs def __a ( self ): UpperCamelCase__ = self.to_sql_kwargs.pop("sql" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("con" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("index" , a ) UpperCamelCase__ = self._write(index=a , **self.to_sql_kwargs ) return written def __a ( self , a ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = args UpperCamelCase__ = {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs UpperCamelCase__ = query_table( table=self.dataset.data , key=slice(a , offset + self.batch_size ) , indices=self.dataset._indices , ) UpperCamelCase__ = batch.to_pandas() UpperCamelCase__ = df.to_sql(self.name , self.con , index=a , **a ) return num_rows or len(a ) def __a ( self , a , **a ): UpperCamelCase__ = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: UpperCamelCase__ , UpperCamelCase__ = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , a , a )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += num_rows return written
80
0
"""simple docstring""" import importlib import math import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Tuple, Union import flax import jax.numpy as jnp from ..utils import BaseOutput lowercase_ = "scheduler_config.json" class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = 1 __UpperCAmelCase : Dict = 2 __UpperCAmelCase : int = 3 __UpperCAmelCase : Tuple = 4 __UpperCAmelCase : Union[str, Any] = 5 @dataclass class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : jnp.ndarray class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : int = SCHEDULER_CONFIG_NAME __UpperCAmelCase : str = ['dtype'] __UpperCAmelCase : List[str] = [] __UpperCAmelCase : Any = True @classmethod def __UpperCAmelCase ( cls , _a = None , _a = None , _a=False , **_a , ): __a , __a = cls.load_config( pretrained_model_name_or_path=_a , subfolder=_a , return_unused_kwargs=_a , **_a , ) __a , __a = cls.from_config(_a , return_unused_kwargs=_a , **_a ) if hasattr(_a , '''create_state''' ) and getattr(_a , '''has_state''' , _a ): __a = scheduler.create_state() if return_unused_kwargs: return scheduler, state, unused_kwargs return scheduler, state def __UpperCAmelCase ( self , _a , _a = False , **_a ): self.save_config(save_directory=_a , push_to_hub=_a , **_a ) @property def __UpperCAmelCase ( self ): return self._get_compatibles() @classmethod def __UpperCAmelCase ( cls ): __a = list(set([cls.__name__] + cls._compatibles ) ) __a = importlib.import_module(__name__.split('''.''' )[0] ) __a = [ getattr(_a , _a ) for c in compatible_classes_str if hasattr(_a , _a ) ] return compatible_classes def lowercase ( lowerCAmelCase__ : jnp.ndarray , lowerCAmelCase__ : Tuple[int] ) -> jnp.ndarray: assert len(lowerCAmelCase__ ) >= x.ndim return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(lowerCAmelCase__ ) - x.ndim) ) , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : str=0.9_99 , lowerCAmelCase__ : List[str]=jnp.floataa ) -> jnp.ndarray: def alpha_bar(lowerCAmelCase__ : str ): return math.cos((time_step + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 __a = [] for i in range(lowerCAmelCase__ ): __a = i / num_diffusion_timesteps __a = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(lowerCAmelCase__ ) / alpha_bar(lowerCAmelCase__ ) , lowerCAmelCase__ ) ) return jnp.array(lowerCAmelCase__ , dtype=lowerCAmelCase__ ) @flax.struct.dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : jnp.ndarray __UpperCAmelCase : jnp.ndarray __UpperCAmelCase : jnp.ndarray @classmethod def __UpperCAmelCase ( cls , _a ): __a = scheduler.config if config.trained_betas is not None: __a = jnp.asarray(config.trained_betas , dtype=scheduler.dtype ) elif config.beta_schedule == "linear": __a = jnp.linspace(config.beta_start , config.beta_end , config.num_train_timesteps , dtype=scheduler.dtype ) elif config.beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __a = ( jnp.linspace( config.beta_start**0.5 , config.beta_end**0.5 , config.num_train_timesteps , dtype=scheduler.dtype ) ** 2 ) elif config.beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __a = betas_for_alpha_bar(config.num_train_timesteps , dtype=scheduler.dtype ) else: raise NotImplementedError( f'''beta_schedule {config.beta_schedule} is not implemented for scheduler {scheduler.__class__.__name__}''' ) __a = 1.0 - betas __a = jnp.cumprod(_a , axis=0 ) return cls( alphas=_a , betas=_a , alphas_cumprod=_a , ) def lowercase ( lowerCAmelCase__ : CommonSchedulerState , lowerCAmelCase__ : jnp.ndarray , lowerCAmelCase__ : jnp.ndarray , lowerCAmelCase__ : jnp.ndarray ) -> Optional[int]: __a = state.alphas_cumprod __a = alphas_cumprod[timesteps] ** 0.5 __a = sqrt_alpha_prod.flatten() __a = broadcast_to_shape_from_left(lowerCAmelCase__ , original_samples.shape ) __a = (1 - alphas_cumprod[timesteps]) ** 0.5 __a = sqrt_one_minus_alpha_prod.flatten() __a = broadcast_to_shape_from_left(lowerCAmelCase__ , original_samples.shape ) return sqrt_alpha_prod, sqrt_one_minus_alpha_prod def lowercase ( lowerCAmelCase__ : CommonSchedulerState , lowerCAmelCase__ : jnp.ndarray , lowerCAmelCase__ : jnp.ndarray , lowerCAmelCase__ : jnp.ndarray ) -> Dict: __a , __a = get_sqrt_alpha_prod(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __a = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples def lowercase ( lowerCAmelCase__ : CommonSchedulerState , lowerCAmelCase__ : jnp.ndarray , lowerCAmelCase__ : jnp.ndarray , lowerCAmelCase__ : jnp.ndarray ) -> List[Any]: __a , __a = get_sqrt_alpha_prod(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __a = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample return velocity
45
'''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. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu a__ : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def _UpperCamelCase ( __A , __A=None , __A=None , __A=None ) -> int: '''simple docstring''' UpperCamelCase__ = True while ask_again: UpperCamelCase__ = input(__A ) try: if default is not None and len(__A ) == 0: return default return convert_value(__A ) if convert_value is not None else result except Exception: if error_message is not None: print(__A ) def _UpperCamelCase ( __A , __A=[] , __A=None , __A=0 ) -> Any: '''simple docstring''' UpperCamelCase__ = BulletMenu(__A , __A ) UpperCamelCase__ = menu.run(default_choice=__A ) return convert_value(__A ) if convert_value is not None else result def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value] ) def _UpperCamelCase ( __A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = int(__A ) return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def _UpperCamelCase ( __A ) -> str: '''simple docstring''' UpperCamelCase__ = int(__A ) return PrecisionType(["no", "fp16", "bf16", "fp8"][value] ) def _UpperCamelCase ( __A ) -> Any: '''simple docstring''' UpperCamelCase__ = int(__A ) return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' return {"yes": True, "no": False}[value.lower()] class lowercase_ ( argparse.RawDescriptionHelpFormatter ): def __a ( self , a , a , a , a ): UpperCamelCase__ = super()._format_usage(a , a , a , a ) UpperCamelCase__ = usage.replace("<command> [<args>] " , "" ) return usage
80
0
"""simple docstring""" import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser( description=( "Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned" " Distillation" ) ) parser.add_argument("--model_type", default="roberta", choices=["roberta", "gpt2"]) parser.add_argument("--model_name", default="roberta-large", type=str) parser.add_argument("--dump_checkpoint", default="serialization_dir/tf_roberta_048131723.pth", type=str) parser.add_argument("--vocab_transform", action="store_true") SCREAMING_SNAKE_CASE__ = parser.parse_args() if args.model_type == "roberta": SCREAMING_SNAKE_CASE__ = RobertaForMaskedLM.from_pretrained(args.model_name) SCREAMING_SNAKE_CASE__ = "roberta" elif args.model_type == "gpt2": SCREAMING_SNAKE_CASE__ = GPTaLMHeadModel.from_pretrained(args.model_name) SCREAMING_SNAKE_CASE__ = "transformer" SCREAMING_SNAKE_CASE__ = model.state_dict() SCREAMING_SNAKE_CASE__ = {} # Embeddings # if args.model_type == "gpt2": for param_name in ["wte.weight", "wpe.weight"]: SCREAMING_SNAKE_CASE__ = state_dict[f'{prefix}.{param_name}'] else: for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]: SCREAMING_SNAKE_CASE__ = f'{prefix}.embeddings.{w}.weight' SCREAMING_SNAKE_CASE__ = state_dict[param_name] for w in ["weight", "bias"]: SCREAMING_SNAKE_CASE__ = f'{prefix}.embeddings.LayerNorm.{w}' SCREAMING_SNAKE_CASE__ = state_dict[param_name] # Transformer Blocks # SCREAMING_SNAKE_CASE__ = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: if args.model_type == "gpt2": for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]: for w in ["weight", "bias"]: SCREAMING_SNAKE_CASE__ = state_dict[ f'{prefix}.h.{teacher_idx}.{layer}.{w}' ] SCREAMING_SNAKE_CASE__ = state_dict[f'{prefix}.h.{teacher_idx}.attn.bias'] else: for layer in [ "attention.self.query", "attention.self.key", "attention.self.value", "attention.output.dense", "attention.output.LayerNorm", "intermediate.dense", "output.dense", "output.LayerNorm", ]: for w in ["weight", "bias"]: SCREAMING_SNAKE_CASE__ = state_dict[ f'{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}' ] std_idx += 1 # Language Modeling Head ###s if args.model_type == "roberta": for layer in ["lm_head.decoder.weight", "lm_head.bias"]: SCREAMING_SNAKE_CASE__ = state_dict[f'{layer}'] if args.vocab_transform: for w in ["weight", "bias"]: SCREAMING_SNAKE_CASE__ = state_dict[f'lm_head.dense.{w}'] SCREAMING_SNAKE_CASE__ = state_dict[f'lm_head.layer_norm.{w}'] elif args.model_type == "gpt2": for w in ["weight", "bias"]: SCREAMING_SNAKE_CASE__ = state_dict[f'{prefix}.ln_f.{w}'] SCREAMING_SNAKE_CASE__ = state_dict["lm_head.weight"] print(f'N layers selected for distillation: {std_idx}') print(f'Number of params transferred for distillation: {len(compressed_sd.keys())}') print(f'Save transferred checkpoint to {args.dump_checkpoint}.') torch.save(compressed_sd, args.dump_checkpoint)
46
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: if resistor <= 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative or zero value!''' raise ValueError(__A ) first_sum += 1 / float(__A ) index += 1 return 1 / first_sum def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: sum_r += resistor if resistor < 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative value!''' raise ValueError(__A ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
80
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase : List[Any] = logging.get_logger(__name__) def _lowerCAmelCase ( _UpperCamelCase : str ) -> YolosConfig: """simple docstring""" _SCREAMING_SNAKE_CASE =YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: _SCREAMING_SNAKE_CASE =1_92 _SCREAMING_SNAKE_CASE =7_68 _SCREAMING_SNAKE_CASE =12 _SCREAMING_SNAKE_CASE =3 _SCREAMING_SNAKE_CASE =[8_00, 13_33] _SCREAMING_SNAKE_CASE =False elif yolos_name == "yolos_s_dWr": _SCREAMING_SNAKE_CASE =3_30 _SCREAMING_SNAKE_CASE =14 _SCREAMING_SNAKE_CASE =6 _SCREAMING_SNAKE_CASE =13_20 elif "yolos_s" in yolos_name: _SCREAMING_SNAKE_CASE =3_84 _SCREAMING_SNAKE_CASE =15_36 _SCREAMING_SNAKE_CASE =12 _SCREAMING_SNAKE_CASE =6 elif "yolos_b" in yolos_name: _SCREAMING_SNAKE_CASE =[8_00, 13_44] _SCREAMING_SNAKE_CASE =91 _SCREAMING_SNAKE_CASE ='huggingface/label-files' _SCREAMING_SNAKE_CASE ='coco-detection-id2label.json' _SCREAMING_SNAKE_CASE =json.load(open(hf_hub_download(_UpperCamelCase , _UpperCamelCase , repo_type='dataset' ) , 'r' ) ) _SCREAMING_SNAKE_CASE ={int(_UpperCamelCase ): v for k, v in idalabel.items()} _SCREAMING_SNAKE_CASE =idalabel _SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} return config def _lowerCAmelCase ( _UpperCamelCase : dict , _UpperCamelCase : YolosConfig , _UpperCamelCase : bool = False ) -> Union[str, Any]: """simple docstring""" for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _SCREAMING_SNAKE_CASE =state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) _SCREAMING_SNAKE_CASE =state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict _SCREAMING_SNAKE_CASE =in_proj_weight[: config.hidden_size, :] _SCREAMING_SNAKE_CASE =in_proj_bias[: config.hidden_size] _SCREAMING_SNAKE_CASE =in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _SCREAMING_SNAKE_CASE =in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _SCREAMING_SNAKE_CASE =in_proj_weight[-config.hidden_size :, :] _SCREAMING_SNAKE_CASE =in_proj_bias[-config.hidden_size :] def _lowerCAmelCase ( _UpperCamelCase : str ) -> str: """simple docstring""" if "backbone" in name: _SCREAMING_SNAKE_CASE =name.replace('backbone' , 'vit' ) if "cls_token" in name: _SCREAMING_SNAKE_CASE =name.replace('cls_token' , 'embeddings.cls_token' ) if "det_token" in name: _SCREAMING_SNAKE_CASE =name.replace('det_token' , 'embeddings.detection_tokens' ) if "mid_pos_embed" in name: _SCREAMING_SNAKE_CASE =name.replace('mid_pos_embed' , 'encoder.mid_position_embeddings' ) if "pos_embed" in name: _SCREAMING_SNAKE_CASE =name.replace('pos_embed' , 'embeddings.position_embeddings' ) if "patch_embed.proj" in name: _SCREAMING_SNAKE_CASE =name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "blocks" in name: _SCREAMING_SNAKE_CASE =name.replace('blocks' , 'encoder.layer' ) if "attn.proj" in name: _SCREAMING_SNAKE_CASE =name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: _SCREAMING_SNAKE_CASE =name.replace('attn' , 'attention.self' ) if "norm1" in name: _SCREAMING_SNAKE_CASE =name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: _SCREAMING_SNAKE_CASE =name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: _SCREAMING_SNAKE_CASE =name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: _SCREAMING_SNAKE_CASE =name.replace('mlp.fc2' , 'output.dense' ) if "class_embed" in name: _SCREAMING_SNAKE_CASE =name.replace('class_embed' , 'class_labels_classifier' ) if "bbox_embed" in name: _SCREAMING_SNAKE_CASE =name.replace('bbox_embed' , 'bbox_predictor' ) if "vit.norm" in name: _SCREAMING_SNAKE_CASE =name.replace('vit.norm' , 'vit.layernorm' ) return name def _lowerCAmelCase ( _UpperCamelCase : dict , _UpperCamelCase : YolosForObjectDetection ) -> dict: """simple docstring""" for key in orig_state_dict.copy().keys(): _SCREAMING_SNAKE_CASE =orig_state_dict.pop(_UpperCamelCase ) if "qkv" in key: _SCREAMING_SNAKE_CASE =key.split('.' ) _SCREAMING_SNAKE_CASE =int(key_split[2] ) _SCREAMING_SNAKE_CASE =model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: _SCREAMING_SNAKE_CASE =val[:dim, :] _SCREAMING_SNAKE_CASE =val[ dim : dim * 2, : ] _SCREAMING_SNAKE_CASE =val[-dim:, :] else: _SCREAMING_SNAKE_CASE =val[:dim] _SCREAMING_SNAKE_CASE =val[dim : dim * 2] _SCREAMING_SNAKE_CASE =val[-dim:] else: _SCREAMING_SNAKE_CASE =val return orig_state_dict def _lowerCAmelCase ( ) -> torch.Tensor: """simple docstring""" _SCREAMING_SNAKE_CASE ='http://images.cocodataset.org/val2017/000000039769.jpg' _SCREAMING_SNAKE_CASE =Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : str , _UpperCamelCase : str , _UpperCamelCase : bool = False ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =get_yolos_config(_UpperCamelCase ) # load original state_dict _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location='cpu' )['model'] # load 🤗 model _SCREAMING_SNAKE_CASE =YolosForObjectDetection(_UpperCamelCase ) model.eval() _SCREAMING_SNAKE_CASE =convert_state_dict(_UpperCamelCase , _UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) # Check outputs on an image, prepared by YolosImageProcessor _SCREAMING_SNAKE_CASE =8_00 if yolos_name != 'yolos_ti' else 5_12 _SCREAMING_SNAKE_CASE =YolosImageProcessor(format='coco_detection' , size=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =image_processor(images=prepare_img() , return_tensors='pt' ) _SCREAMING_SNAKE_CASE =model(**_UpperCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =outputs.logits, outputs.pred_boxes _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =None, None if yolos_name == "yolos_ti": _SCREAMING_SNAKE_CASE =torch.tensor( [[-39.50_22, -11.98_20, -17.68_88], [-29.95_74, -9.97_69, -17.76_91], [-42.32_81, -20.72_00, -30.62_94]] ) _SCREAMING_SNAKE_CASE =torch.tensor( [[0.40_21, 0.08_36, 0.79_79], [0.01_84, 0.26_09, 0.03_64], [0.17_81, 0.20_04, 0.20_95]] ) elif yolos_name == "yolos_s_200_pre": _SCREAMING_SNAKE_CASE =torch.tensor( [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]] ) _SCREAMING_SNAKE_CASE =torch.tensor( [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]] ) elif yolos_name == "yolos_s_300_pre": _SCREAMING_SNAKE_CASE =torch.tensor( [[-36.22_20, -14.43_85, -23.54_57], [-35.69_70, -14.75_83, -21.39_35], [-31.59_39, -13.60_42, -16.80_49]] ) _SCREAMING_SNAKE_CASE =torch.tensor( [[0.76_14, 0.23_16, 0.47_28], [0.71_68, 0.44_95, 0.38_55], [0.49_96, 0.14_66, 0.99_96]] ) elif yolos_name == "yolos_s_dWr": _SCREAMING_SNAKE_CASE =torch.tensor( [[-42.86_68, -24.10_49, -41.16_90], [-34.74_56, -14.12_74, -24.91_94], [-33.78_98, -12.19_46, -25.64_95]] ) _SCREAMING_SNAKE_CASE =torch.tensor( [[0.55_87, 0.27_73, 0.06_05], [0.50_04, 0.30_14, 0.99_94], [0.49_99, 0.15_48, 0.99_94]] ) elif yolos_name == "yolos_base": _SCREAMING_SNAKE_CASE =torch.tensor( [[-40.60_64, -24.30_84, -32.64_47], [-55.19_90, -30.77_19, -35.58_77], [-51.43_11, -33.35_07, -35.64_62]] ) _SCREAMING_SNAKE_CASE =torch.tensor( [[0.55_55, 0.27_94, 0.06_55], [0.90_49, 0.26_64, 0.18_94], [0.91_83, 0.19_84, 0.16_35]] ) else: raise ValueError(f"Unknown yolos_name: {yolos_name}" ) assert torch.allclose(logits[0, :3, :3] , _UpperCamelCase , atol=1E-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , _UpperCamelCase , atol=1E-4 ) Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) print(f"Saving model {yolos_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_UpperCamelCase ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(_UpperCamelCase ) if push_to_hub: _SCREAMING_SNAKE_CASE ={ 'yolos_ti': 'yolos-tiny', 'yolos_s_200_pre': 'yolos-small', 'yolos_s_300_pre': 'yolos-small-300', 'yolos_s_dWr': 'yolos-small-dwr', 'yolos_base': 'yolos-base', } print('Pushing to the hub...' ) _SCREAMING_SNAKE_CASE =model_mapping[yolos_name] image_processor.push_to_hub(_UpperCamelCase , organization='hustvl' ) model.push_to_hub(_UpperCamelCase , organization='hustvl' ) if __name__ == "__main__": lowerCamelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--yolos_name", default="yolos_s_200_pre", type=str, help=( "Name of the YOLOS model you'd like to convert. Should be one of 'yolos_ti', 'yolos_s_200_pre'," " 'yolos_s_300_pre', 'yolos_s_dWr', 'yolos_base'." ), ) parser.add_argument( "--checkpoint_path", default=None, type=str, help="Path to the original state dict (.pth file)." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) lowerCamelCase : int = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
47
'''simple docstring''' import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class lowercase_ ( enum.Enum ): __UpperCAmelCase = 0 __UpperCAmelCase = 1 __UpperCAmelCase = 2 @add_end_docstrings(a__ ) class lowercase_ ( a__ ): __UpperCAmelCase = '\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n ' def __init__( self , *a , **a ): super().__init__(*a , **a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. UpperCamelCase__ = None if self.model.config.prefix is not None: UpperCamelCase__ = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. UpperCamelCase__ = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._sanitize_parameters(prefix=a , **self._forward_params ) UpperCamelCase__ = {**self._preprocess_params, **preprocess_params} UpperCamelCase__ = {**self._forward_params, **forward_params} def __a ( self , a=None , a=None , a=None , a=None , a=None , a=None , a=None , a=None , **a , ): UpperCamelCase__ = {} if prefix is not None: UpperCamelCase__ = prefix if prefix: UpperCamelCase__ = self.tokenizer( a , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = prefix_inputs["input_ids"].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' " [None, 'hole']" ) UpperCamelCase__ = handle_long_generation preprocess_params.update(a ) UpperCamelCase__ = generate_kwargs UpperCamelCase__ = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("`return_text` is mutually exclusive with `return_full_text`" ) if return_tensors is not None: raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`" ) UpperCamelCase__ = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("`return_text` is mutually exclusive with `return_tensors`" ) UpperCamelCase__ = ReturnType.TENSORS if return_type is not None: UpperCamelCase__ = return_type if clean_up_tokenization_spaces is not None: UpperCamelCase__ = clean_up_tokenization_spaces if stop_sequence is not None: UpperCamelCase__ = self.tokenizer.encode(a , add_special_tokens=a ) if len(a ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) UpperCamelCase__ = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __a ( self , *a , **a ): # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"add_space_before_punct_symbol": True} ) return super()._parse_and_tokenize(*a , **a ) def __call__( self , a , **a ): return super().__call__(a , **a ) def __a ( self , a , a="" , a=None , **a ): UpperCamelCase__ = self.tokenizer( prefix + prompt_text , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = prompt_text if handle_long_generation == "hole": UpperCamelCase__ = inputs["input_ids"].shape[-1] if "max_new_tokens" in generate_kwargs: UpperCamelCase__ = generate_kwargs["max_new_tokens"] else: UpperCamelCase__ = generate_kwargs.get("max_length" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("We cannot infer how many new tokens are expected" ) if cur_len + new_tokens > self.tokenizer.model_max_length: UpperCamelCase__ = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( "We cannot use `hole` to handle this generation the number of desired tokens exceeds the" " models max length" ) UpperCamelCase__ = inputs["input_ids"][:, -keep_length:] if "attention_mask" in inputs: UpperCamelCase__ = inputs["attention_mask"][:, -keep_length:] return inputs def __a ( self , a , **a ): UpperCamelCase__ = model_inputs["input_ids"] UpperCamelCase__ = model_inputs.get("attention_mask" , a ) # Allow empty prompts if input_ids.shape[1] == 0: UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = 1 else: UpperCamelCase__ = input_ids.shape[0] UpperCamelCase__ = model_inputs.pop("prompt_text" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. UpperCamelCase__ = generate_kwargs.pop("prefix_length" , 0 ) if prefix_length > 0: UpperCamelCase__ = "max_new_tokens" in generate_kwargs or ( "generation_config" in generate_kwargs and generate_kwargs["generation_config"].max_new_tokens is not None ) if not has_max_new_tokens: UpperCamelCase__ = generate_kwargs.get("max_length" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length UpperCamelCase__ = "min_new_tokens" in generate_kwargs or ( "generation_config" in generate_kwargs and generate_kwargs["generation_config"].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL UpperCamelCase__ = self.model.generate(input_ids=a , attention_mask=a , **a ) UpperCamelCase__ = generated_sequence.shape[0] if self.framework == "pt": UpperCamelCase__ = generated_sequence.reshape(a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": UpperCamelCase__ = tf.reshape(a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def __a ( self , a , a=ReturnType.FULL_TEXT , a=True ): UpperCamelCase__ = model_outputs["generated_sequence"][0] UpperCamelCase__ = model_outputs["input_ids"] UpperCamelCase__ = model_outputs["prompt_text"] UpperCamelCase__ = generated_sequence.numpy().tolist() UpperCamelCase__ = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: UpperCamelCase__ = {"generated_token_ids": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text UpperCamelCase__ = self.tokenizer.decode( a , skip_special_tokens=a , clean_up_tokenization_spaces=a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: UpperCamelCase__ = 0 else: UpperCamelCase__ = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=a , clean_up_tokenization_spaces=a , ) ) if return_type == ReturnType.FULL_TEXT: UpperCamelCase__ = prompt_text + text[prompt_length:] else: UpperCamelCase__ = text[prompt_length:] UpperCamelCase__ = {"generated_text": all_text} records.append(a ) return records
80
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase__ (lowerCAmelCase__ ): '''simple docstring''' lowerCamelCase_ : Optional[int] = ["""image_processor""", """tokenizer"""] lowerCamelCase_ : Tuple = """ViTImageProcessor""" lowerCamelCase_ : str = ("""CLIPTokenizer""", """CLIPTokenizerFast""") def __init__( self , UpperCamelCase__=None , UpperCamelCase__=None , **UpperCamelCase__ ) -> int: lowerCamelCase : List[Any] = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , UpperCamelCase__ , ) lowerCamelCase : Any = kwargs.pop("feature_extractor" ) lowerCamelCase : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(UpperCamelCase__ , UpperCamelCase__ ) def __call__( self , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , **UpperCamelCase__ ) -> Union[str, Any]: if text is None and visual_prompt is None and images is None: raise ValueError("You have to specify either text, visual prompt or images." ) if text is not None and visual_prompt is not None: raise ValueError("You have to specify exactly one type of prompt. Either text or visual prompt." ) if text is not None: lowerCamelCase : Any = self.tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) if visual_prompt is not None: lowerCamelCase : List[Any] = self.image_processor(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) if images is not None: lowerCamelCase : Tuple = self.image_processor(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) if visual_prompt is not None and images is not None: lowerCamelCase : Optional[Any] = { "pixel_values": image_features.pixel_values, "conditional_pixel_values": prompt_features.pixel_values, } return encoding elif text is not None and images is not None: lowerCamelCase : int = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: lowerCamelCase : Tuple = { "conditional_pixel_values": prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**UpperCamelCase__ ) , tensor_type=UpperCamelCase__ ) def _lowercase ( self , *UpperCamelCase__ , **UpperCamelCase__ ) -> List[Any]: return self.tokenizer.batch_decode(*UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self , *UpperCamelCase__ , **UpperCamelCase__ ) -> int: return self.tokenizer.decode(*UpperCamelCase__ , **UpperCamelCase__ ) @property def _lowercase ( self ) -> Dict: warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCamelCase__ , ) return self.image_processor_class @property def _lowercase ( self ) -> str: warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , UpperCamelCase__ , ) return self.image_processor
48
'''simple docstring''' from ....utils import logging a__ : Optional[Any] = logging.get_logger(__name__) class lowercase_ ( a__ ): def __init__( self , a , a=None , a=20_48 ): UpperCamelCase__ = config.__dict__ UpperCamelCase__ = modal_hidden_size if num_labels: UpperCamelCase__ = num_labels
80
0
from typing import TYPE_CHECKING from ....utils import _LazyModule __snake_case :Any = {'''tokenization_tapex''': ['''TapexTokenizer''']} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys __snake_case :str = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
49
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent a__ : Tuple = {'UserAgent': UserAgent().random} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' UpperCamelCase__ = script.contents[0] UpperCamelCase__ = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class lowercase_ : def __init__( self , a ): UpperCamelCase__ = f'''https://www.instagram.com/{username}/''' UpperCamelCase__ = self.get_json() def __a ( self ): UpperCamelCase__ = requests.get(self.url , headers=a ).text UpperCamelCase__ = BeautifulSoup(a , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self ): return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self ): return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def __a ( self ): return self.user_data["username"] @property def __a ( self ): return self.user_data["full_name"] @property def __a ( self ): return self.user_data["biography"] @property def __a ( self ): return self.user_data["business_email"] @property def __a ( self ): return self.user_data["external_url"] @property def __a ( self ): return self.user_data["edge_followed_by"]["count"] @property def __a ( self ): return self.user_data["edge_follow"]["count"] @property def __a ( self ): return self.user_data["edge_owner_to_timeline_media"]["count"] @property def __a ( self ): return self.user_data["profile_pic_url_hd"] @property def __a ( self ): return self.user_data["is_verified"] @property def __a ( self ): return self.user_data["is_private"] def _UpperCamelCase ( __A = "github" ) -> None: '''simple docstring''' import os if os.environ.get("CI" ): return # test failing on GitHub Actions UpperCamelCase__ = InstagramUser(__A ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __A ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() a__ : Any = InstagramUser('github') print(instagram_user) print(F"""{instagram_user.number_of_posts = }""") print(F"""{instagram_user.number_of_followers = }""") print(F"""{instagram_user.number_of_followings = }""") print(F"""{instagram_user.email = }""") print(F"""{instagram_user.website = }""") print(F"""{instagram_user.profile_picture_url = }""") print(F"""{instagram_user.is_verified = }""") print(F"""{instagram_user.is_private = }""")
80
0
import os import re import shutil import sys import tempfile import unittest import black _UpperCAmelCase : Optional[int] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated. _UpperCAmelCase : Union[str, Any] = """ def __init__(self, config): super().__init__() self.transform = BertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states """ class lowerCAmelCase ( unittest.TestCase ): def A_ ( self : str ) -> Optional[Any]: lowerCamelCase__ : Any = tempfile.mkdtemp() os.makedirs(os.path.join(self.transformer_dir , 'models/bert/' ) ) lowerCamelCase__ : str = self.transformer_dir shutil.copy( os.path.join(UpperCAmelCase , 'src/transformers/models/bert/modeling_bert.py' ) , os.path.join(self.transformer_dir , 'models/bert/modeling_bert.py' ) , ) def A_ ( self : Optional[int] ) -> Dict: lowerCamelCase__ : Optional[Any] = 'src/transformers' shutil.rmtree(self.transformer_dir ) def A_ ( self : Tuple , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : int , UpperCAmelCase : Dict , UpperCAmelCase : Tuple=None ) -> List[Any]: lowerCamelCase__ : List[str] = comment + F"""\nclass {class_name}(nn.Module):\n""" + class_code if overwrite_result is not None: lowerCamelCase__ : Tuple = comment + F"""\nclass {class_name}(nn.Module):\n""" + overwrite_result lowerCamelCase__ : int = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 ) lowerCamelCase__ : int = black.format_str(UpperCAmelCase , mode=UpperCAmelCase ) lowerCamelCase__ : List[str] = os.path.join(self.transformer_dir , 'new_code.py' ) with open(UpperCAmelCase , 'w' , newline='\n' ) as f: f.write(UpperCAmelCase ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(UpperCAmelCase ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=UpperCAmelCase ) with open(UpperCAmelCase , 'r' ) as f: self.assertTrue(f.read() , UpperCAmelCase ) def A_ ( self : Optional[int] ) -> str: lowerCamelCase__ : Optional[Any] = check_copies.find_code_in_transformers('models.bert.modeling_bert.BertLMPredictionHead' ) self.assertEqual(UpperCAmelCase , UpperCAmelCase ) def A_ ( self : Optional[Any] ) -> Dict: # Base copy consistency self.check_copy_consistency( '# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead' , 'BertLMPredictionHead' , REFERENCE_CODE + '\n' , ) # With no empty line at the end self.check_copy_consistency( '# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead' , 'BertLMPredictionHead' , UpperCAmelCase , ) # Copy consistency with rename self.check_copy_consistency( '# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel' , 'TestModelLMPredictionHead' , re.sub('Bert' , 'TestModel' , UpperCAmelCase ) , ) # Copy consistency with a really long name lowerCamelCase__ : Tuple = 'TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason' self.check_copy_consistency( F"""# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}""" , F"""{long_class_name}LMPredictionHead""" , re.sub('Bert' , UpperCAmelCase , UpperCAmelCase ) , ) # Copy consistency with overwrite self.check_copy_consistency( '# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel' , 'TestModelLMPredictionHead' , UpperCAmelCase , overwrite_result=re.sub('Bert' , 'TestModel' , UpperCAmelCase ) , ) def A_ ( self : Any ) -> Optional[Any]: lowerCamelCase__ : Tuple = check_copies.LOCALIZED_READMES['README_zh-hans.md'] lowerCamelCase__ : Optional[Any] = ( '1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the' ' Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for' ' Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong' ' Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1.' ' **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),' ' released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and' ' lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same' ' method has been applied to compress GPT2 into' ' [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into' ' [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),' ' Multilingual BERT into' ' [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German' ' version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**' ' (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders' ' as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang' ' Luong, Quoc V. Le, Christopher D. Manning.' ) lowerCamelCase__ : Any = ( '1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the' ' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of' ' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian' ' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n' ) lowerCamelCase__ : Optional[int] = ( '1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the' ' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of' ' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian' ' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1.' ' **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文' ' [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and' ' lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same' ' method has been applied to compress GPT2 into' ' [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into' ' [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),' ' Multilingual BERT into' ' [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German' ' version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自' ' Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather' ' than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,' ' Christopher D. Manning 发布。\n' ) lowerCamelCase__ , lowerCamelCase__ : Optional[int] = check_copies.convert_to_localized_md( UpperCAmelCase , UpperCAmelCase , localized_readme['format_model_list'] ) self.assertFalse(UpperCAmelCase ) self.assertEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ , lowerCamelCase__ : Tuple = check_copies.convert_to_localized_md( UpperCAmelCase , UpperCAmelCase , localized_readme['format_model_list'] ) # Check whether the number of models is equal to README.md after conversion. self.assertTrue(UpperCAmelCase ) lowerCamelCase__ : Dict = ( '1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the' ' Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for' ' Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong' ' Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.' ) lowerCamelCase__ : List[Any] = ( '1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and' ' the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of' ' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian' ' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n' ) lowerCamelCase__ : Tuple = ( '1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the' ' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of' ' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian' ' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n' ) lowerCamelCase__ , lowerCamelCase__ : Any = check_copies.convert_to_localized_md( UpperCAmelCase , UpperCAmelCase , localized_readme['format_model_list'] ) # Check if the model link is synchronized. self.assertEqual(UpperCAmelCase , UpperCAmelCase )
50
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A , __A , __A ) -> dict[str, float]: '''simple docstring''' if (voltage, current, resistance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if resistance < 0: raise ValueError("Resistance cannot be negative" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
80
0
from copy import deepcopy class __snake_case : def __init__( self : List[str] , _snake_case : list[int] | None = None , _snake_case : int | None = None): """simple docstring""" if arr is None and size is not None: UpperCAmelCase_ = size UpperCAmelCase_ = [0] * size elif arr is not None: self.init(_snake_case) else: raise ValueError('''Either arr or size must be specified''') def lowerCamelCase ( self : Tuple , _snake_case : list[int]): """simple docstring""" UpperCAmelCase_ = len(_snake_case) UpperCAmelCase_ = deepcopy(_snake_case) for i in range(1 , self.size): UpperCAmelCase_ = self.next_(_snake_case) if j < self.size: self.tree[j] += self.tree[i] def lowerCamelCase ( self : List[Any]): """simple docstring""" UpperCAmelCase_ = self.tree[:] for i in range(self.size - 1 , 0 , -1): UpperCAmelCase_ = self.next_(_snake_case) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def lowerCamelCase ( _snake_case : int): """simple docstring""" return index + (index & (-index)) @staticmethod def lowerCamelCase ( _snake_case : int): """simple docstring""" return index - (index & (-index)) def lowerCamelCase ( self : Tuple , _snake_case : int , _snake_case : int): """simple docstring""" if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value UpperCAmelCase_ = self.next_(_snake_case) def lowerCamelCase ( self : Tuple , _snake_case : int , _snake_case : int): """simple docstring""" self.add(_snake_case , value - self.get(_snake_case)) def lowerCamelCase ( self : str , _snake_case : int): """simple docstring""" if right == 0: return 0 UpperCAmelCase_ = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] UpperCAmelCase_ = self.prev(_snake_case) return result def lowerCamelCase ( self : Dict , _snake_case : int , _snake_case : int): """simple docstring""" return self.prefix(_snake_case) - self.prefix(_snake_case) def lowerCamelCase ( self : Optional[int] , _snake_case : int): """simple docstring""" return self.query(_snake_case , index + 1) def lowerCamelCase ( self : Tuple , _snake_case : int): """simple docstring""" value -= self.tree[0] if value < 0: return -1 UpperCAmelCase_ = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 UpperCAmelCase_ = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
51
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Union[str, Any] = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys a__ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
80
0
import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging __lowerCamelCase : int = logging.get_logger(__name__) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Any: UpperCamelCase : Any = set() UpperCamelCase : Union[str, Any] = [] def parse_line(_lowerCAmelCase ): for line in fp: if isinstance(_lowerCAmelCase , _lowerCAmelCase ): UpperCamelCase : Dict = line.decode("UTF-8" ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(" " ): # process a single warning and move it to `selected_warnings`. if len(_lowerCAmelCase ) > 0: UpperCamelCase : Dict = "\n".join(_lowerCAmelCase ) # Only keep the warnings specified in `targets` if any(F""": {x}: """ in warning for x in targets ): selected_warnings.add(_lowerCAmelCase ) buffer.clear() continue else: UpperCamelCase : List[Any] = line.strip() buffer.append(_lowerCAmelCase ) if from_gh: for filename in os.listdir(_lowerCAmelCase ): UpperCamelCase : Optional[Any] = os.path.join(_lowerCAmelCase , _lowerCAmelCase ) if not os.path.isdir(_lowerCAmelCase ): # read the file if filename != "warnings.txt": continue with open(_lowerCAmelCase ) as fp: parse_line(_lowerCAmelCase ) else: try: with zipfile.ZipFile(_lowerCAmelCase ) as z: for filename in z.namelist(): if not os.path.isdir(_lowerCAmelCase ): # read the file if filename != "warnings.txt": continue with z.open(_lowerCAmelCase ) as fp: parse_line(_lowerCAmelCase ) except Exception: logger.warning( F"""{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.""" ) return selected_warnings def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Dict: UpperCamelCase : List[str] = set() UpperCamelCase : Dict = [os.path.join(_lowerCAmelCase , _lowerCAmelCase ) for p in os.listdir(_lowerCAmelCase ) if (p.endswith(".zip" ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(_lowerCAmelCase , _lowerCAmelCase ) ) return selected_warnings if __name__ == "__main__": def A_ ( _lowerCAmelCase ) -> Tuple: return values.split("," ) __lowerCamelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument("""--workflow_run_id""", type=str, required=True, help="""A GitHub Actions workflow run id.""") parser.add_argument( """--output_dir""", type=str, required=True, help="""Where to store the downloaded artifacts and other result files.""", ) parser.add_argument("""--token""", default=None, type=str, help="""A token that has actions:read permission.""") # optional parameters parser.add_argument( """--targets""", default="""DeprecationWarning,UserWarning,FutureWarning""", type=list_str, help="""Comma-separated list of target warning(s) which we want to extract.""", ) parser.add_argument( """--from_gh""", action="""store_true""", help="""If running from a GitHub action workflow and collecting warnings from its artifacts.""", ) __lowerCamelCase : Optional[Any] = parser.parse_args() __lowerCamelCase : Tuple = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links __lowerCamelCase : Optional[int] = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, """artifacts.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print("""=""" * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts __lowerCamelCase : Any = extract_warnings(args.output_dir, args.targets) __lowerCamelCase : List[Any] = sorted(selected_warnings) with open(os.path.join(args.output_dir, """selected_warnings.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
52
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if len(__A ) != 2 or len(a[0] ) != 2 or len(__A ) != 2 or len(b[0] ) != 2: raise Exception("Matrices are not 2x2" ) UpperCamelCase__ = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _UpperCamelCase ( __A , __A ) -> str: '''simple docstring''' return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A ) -> tuple[list, list, list, list]: '''simple docstring''' if len(__A ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception("Odd matrices are not supported!" ) UpperCamelCase__ = len(__A ) UpperCamelCase__ = matrix_length // 2 UpperCamelCase__ = [[a[i][j] for j in range(__A , __A )] for i in range(__A )] UpperCamelCase__ = [ [a[i][j] for j in range(__A , __A )] for i in range(__A , __A ) ] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A )] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A , __A )] return top_left, top_right, bot_left, bot_right def _UpperCamelCase ( __A ) -> tuple[int, int]: '''simple docstring''' return len(__A ), len(matrix[0] ) def _UpperCamelCase ( __A ) -> None: '''simple docstring''' print("\n".join(str(__A ) for line in matrix ) ) def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A ) == (2, 2): return default_matrix_multiplication(__A , __A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = matrix_addition(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_subtraction(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) # construct the new matrix from our 4 quadrants UpperCamelCase__ = [] for i in range(len(__A ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(__A ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A )[1] != matrix_dimensions(__A )[0]: UpperCamelCase__ = ( "Unable to multiply these matrices, please check the dimensions.\n" F'''Matrix A: {matrixa}\n''' F'''Matrix B: {matrixa}''' ) raise Exception(__A ) UpperCamelCase__ = matrix_dimensions(__A ) UpperCamelCase__ = matrix_dimensions(__A ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] UpperCamelCase__ = max(*__A , *__A ) UpperCamelCase__ = int(math.pow(2 , math.ceil(math.loga(__A ) ) ) ) UpperCamelCase__ = matrixa UpperCamelCase__ = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) UpperCamelCase__ = actual_strassen(__A , __A ) # Removing the additional zeros for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a__ : int = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a__ : str = [[0, 2, 1, 1], [1_6, 2, 3, 3], [2, 2, 7, 7], [1_3, 1_1, 2_2, 4]] print(strassen(matrixa, matrixa))
80
0
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __lowerCamelCase , __lowerCamelCase ): """simple docstring""" @register_to_config def __init__( self : Any , __A : int = 7_6_8 , ): super().__init__() __UpperCamelCase = nn.Parameter(torch.zeros(1 , __A ) ) __UpperCamelCase = nn.Parameter(torch.ones(1 , __A ) ) def _lowerCamelCase ( self : Optional[Any] , __A : Optional[Union[str, torch.device]] = None , __A : Optional[torch.dtype] = None , ): __UpperCamelCase = nn.Parameter(self.mean.to(__A ).to(__A ) ) __UpperCamelCase = nn.Parameter(self.std.to(__A ).to(__A ) ) return self def _lowerCamelCase ( self : Optional[int] , __A : Optional[int] ): __UpperCamelCase = (embeds - self.mean) * 1.0 / self.std return embeds def _lowerCamelCase ( self : Optional[int] , __A : Tuple ): __UpperCamelCase = (embeds * self.std) + self.mean return embeds
53
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging a__ : List[str] = logging.get_logger(__name__) if is_vision_available(): import PIL class lowercase_ ( a__ ): __UpperCAmelCase = ['pixel_values'] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = None , a = True , a = 1 / 2_55 , a = True , a = None , a = None , a = True , **a , ): super().__init__(**a ) UpperCamelCase__ = size if size is not None else {"shortest_edge": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a ) UpperCamelCase__ = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a , param_name="crop_size" ) UpperCamelCase__ = do_resize UpperCamelCase__ = size UpperCamelCase__ = resample UpperCamelCase__ = do_center_crop UpperCamelCase__ = crop_size UpperCamelCase__ = do_rescale UpperCamelCase__ = rescale_factor UpperCamelCase__ = do_normalize UpperCamelCase__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN UpperCamelCase__ = image_std if image_std is not None else OPENAI_CLIP_STD UpperCamelCase__ = do_convert_rgb def __a ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ): UpperCamelCase__ = get_size_dict(a , default_to_square=a ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) UpperCamelCase__ = get_resize_output_image_size(a , size=size["shortest_edge"] , default_to_square=a ) return resize(a , size=a , resample=a , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): UpperCamelCase__ = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(a , size=(size["height"], size["width"]) , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): return rescale(a , scale=a , data_format=a , **a ) def __a ( self , a , a , a , a = None , **a , ): return normalize(a , mean=a , std=a , data_format=a , **a ) def __a ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ): UpperCamelCase__ = do_resize if do_resize is not None else self.do_resize UpperCamelCase__ = size if size is not None else self.size UpperCamelCase__ = get_size_dict(a , param_name="size" , default_to_square=a ) UpperCamelCase__ = resample if resample is not None else self.resample UpperCamelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase__ = crop_size if crop_size is not None else self.crop_size UpperCamelCase__ = get_size_dict(a , param_name="crop_size" , default_to_square=a ) UpperCamelCase__ = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase__ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase__ = image_mean if image_mean is not None else self.image_mean UpperCamelCase__ = image_std if image_std is not None else self.image_std UpperCamelCase__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase__ = make_list_of_images(a ) if not valid_images(a ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase__ = [convert_to_rgb(a ) for image in images] # All transformations expect numpy arrays. UpperCamelCase__ = [to_numpy_array(a ) for image in images] if do_resize: UpperCamelCase__ = [self.resize(image=a , size=a , resample=a ) for image in images] if do_center_crop: UpperCamelCase__ = [self.center_crop(image=a , size=a ) for image in images] if do_rescale: UpperCamelCase__ = [self.rescale(image=a , scale=a ) for image in images] if do_normalize: UpperCamelCase__ = [self.normalize(image=a , mean=a , std=a ) for image in images] UpperCamelCase__ = [to_channel_dimension_format(a , a ) for image in images] UpperCamelCase__ = {"pixel_values": images} return BatchFeature(data=a , tensor_type=a )
80
0
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..utils import cached_file # docstyle-ignore a__ : Union[str, Any] = ''' Human: <<task>> Assistant: ''' a__ : Optional[Any] = '''huggingface-tools/default-prompts''' a__ : int = {'''chat''': '''chat_prompt_template.txt''', '''run''': '''run_prompt_template.txt'''} def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="run" ): '''simple docstring''' if prompt_or_repo_id is None: __SCREAMING_SNAKE_CASE = DEFAULT_PROMPTS_REPO # prompt is considered a repo ID when it does not contain any kind of space if re.search("\\s" , lowerCAmelCase_ ) is not None: return prompt_or_repo_id __SCREAMING_SNAKE_CASE = cached_file( lowerCAmelCase_ , PROMPT_FILES[mode] , repo_type="dataset" , user_agent={"agent": agent_name} ) with open(lowerCAmelCase_ , "r" , encoding="utf-8" ) as f: return f.read()
54
'''simple docstring''' import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase_ ( a__ , unittest.TestCase ): __UpperCAmelCase = CLIPTokenizer __UpperCAmelCase = CLIPTokenizerFast __UpperCAmelCase = True __UpperCAmelCase = {} __UpperCAmelCase = False def __a ( self ): super().setUp() # fmt: off UpperCamelCase__ = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on UpperCamelCase__ = dict(zip(a , range(len(a ) ) ) ) UpperCamelCase__ = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] UpperCamelCase__ = {"unk_token": "<unk>"} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(a ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(a ) ) def __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def __a ( self , a ): UpperCamelCase__ = "lower newer" UpperCamelCase__ = "lower newer" return input_text, output_text def __a ( self ): UpperCamelCase__ = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = "lower newer" UpperCamelCase__ = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] UpperCamelCase__ = tokenizer.tokenize(a ) self.assertListEqual(a , a ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def __a ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = self.tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways UpperCamelCase__ = "xa\u0303y" + " " + "x\xe3y" UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type UpperCamelCase__ = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type UpperCamelCase__ = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def __a ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = "hello" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = f'''{text_of_1_token} {text_of_1_token}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) UpperCamelCase__ = f''' {text}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def __a ( self ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def __a ( self ): super().test_tokenization_python_rust_equals() def __a ( self ): # CLIP always lower cases letters pass
80
0
'''simple docstring''' import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def __snake_case ( UpperCAmelCase_ : Tuple ): if "model" in orig_key: lowerCamelCase_ = orig_key.replace("model." , "" ) if "norm1" in orig_key: lowerCamelCase_ = orig_key.replace("norm1" , "attention.output.LayerNorm" ) if "norm2" in orig_key: lowerCamelCase_ = orig_key.replace("norm2" , "output.LayerNorm" ) if "norm" in orig_key: lowerCamelCase_ = orig_key.replace("norm" , "LayerNorm" ) if "transformer" in orig_key: lowerCamelCase_ = orig_key.split("." )[0].split("_" )[-1] lowerCamelCase_ = orig_key.replace(F'''transformer_{layer_num}''' , F'''encoder.layer.{layer_num}''' ) if "mha.attn" in orig_key: lowerCamelCase_ = orig_key.replace("mha.attn" , "attention.self" ) if "mha" in orig_key: lowerCamelCase_ = orig_key.replace("mha" , "attention" ) if "W_q" in orig_key: lowerCamelCase_ = orig_key.replace("W_q" , "self.query" ) if "W_k" in orig_key: lowerCamelCase_ = orig_key.replace("W_k" , "self.key" ) if "W_v" in orig_key: lowerCamelCase_ = orig_key.replace("W_v" , "self.value" ) if "ff1" in orig_key: lowerCamelCase_ = orig_key.replace("ff1" , "intermediate.dense" ) if "ff2" in orig_key: lowerCamelCase_ = orig_key.replace("ff2" , "output.dense" ) if "ff" in orig_key: lowerCamelCase_ = orig_key.replace("ff" , "output.dense" ) if "mlm_class" in orig_key: lowerCamelCase_ = orig_key.replace("mlm.mlm_class" , "cls.predictions.decoder" ) if "mlm" in orig_key: lowerCamelCase_ = orig_key.replace("mlm" , "cls.predictions.transform" ) if "cls" not in orig_key: lowerCamelCase_ = "yoso." + orig_key return orig_key def __snake_case ( UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict ): for key in orig_state_dict.copy().keys(): lowerCamelCase_ = orig_state_dict.pop(UpperCAmelCase_ ) if ("pooler" in key) or ("sen_class" in key): continue else: lowerCamelCase_ = val lowerCamelCase_ = orig_state_dict["cls.predictions.decoder.bias"] lowerCamelCase_ = torch.arange(UpperCAmelCase_ ).expand((1, -1) ) + 2 return orig_state_dict def __snake_case ( UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any ): lowerCamelCase_ = torch.load(UpperCAmelCase_ , map_location="cpu" )["model_state_dict"] lowerCamelCase_ = YosoConfig.from_json_file(UpperCAmelCase_ ) lowerCamelCase_ = YosoForMaskedLM(UpperCAmelCase_ ) lowerCamelCase_ = convert_checkpoint_helper(config.max_position_embeddings , UpperCAmelCase_ ) print(model.load_state_dict(UpperCAmelCase_ ) ) model.eval() model.save_pretrained(UpperCAmelCase_ ) print(F'''Checkpoint successfuly converted. Model saved at {pytorch_dump_path}''' ) if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( """--pytorch_model_path""", default=None, type=str, required=True, help="""Path to YOSO pytorch checkpoint.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help="""The json file for YOSO model config.""", ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) a_ : Optional[Any] = parser.parse_args() convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
55
'''simple docstring''' import argparse import collections import json import os import re import string import sys import numpy as np a__ : Optional[int] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a__ : int = None def _UpperCamelCase ( ) -> Dict: '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0." ) parser.add_argument("data_file" , metavar="data.json" , help="Input data JSON file." ) parser.add_argument("pred_file" , metavar="pred.json" , help="Model predictions." ) parser.add_argument( "--out-file" , "-o" , metavar="eval.json" , help="Write accuracy metrics to file (default is stdout)." ) parser.add_argument( "--na-prob-file" , "-n" , metavar="na_prob.json" , help="Model estimates of probability of no answer." ) parser.add_argument( "--na-prob-thresh" , "-t" , type=__A , default=1.0 , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)." , ) parser.add_argument( "--out-image-dir" , "-p" , metavar="out_images" , default=__A , help="Save precision-recall curves to directory." ) parser.add_argument("--verbose" , "-v" , action="store_true" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = bool(qa["answers"]["text"] ) return qid_to_has_ans def _UpperCamelCase ( __A ) -> Optional[Any]: '''simple docstring''' def remove_articles(__A ): return ARTICLES_REGEX.sub(" " , __A ) def white_space_fix(__A ): return " ".join(text.split() ) def remove_punc(__A ): UpperCamelCase__ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__A ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__A ) ) ) ) def _UpperCamelCase ( __A ) -> int: '''simple docstring''' if not s: return [] return normalize_answer(__A ).split() def _UpperCamelCase ( __A , __A ) -> List[Any]: '''simple docstring''' return int(normalize_answer(__A ) == normalize_answer(__A ) ) def _UpperCamelCase ( __A , __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = collections.Counter(__A ) & collections.Counter(__A ) UpperCamelCase__ = sum(common.values() ) if len(__A ) == 0 or len(__A ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = (2 * precision * recall) / (precision + recall) return fa def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = qa["id"] UpperCamelCase__ = [t for t in qa["answers"]["text"] if normalize_answer(__A )] if not gold_answers: # For unanswerable questions, only correct answer is empty string UpperCamelCase__ = [""] if qid not in preds: print(F'''Missing prediction for {qid}''' ) continue UpperCamelCase__ = preds[qid] # Take max over all gold answers UpperCamelCase__ = max(compute_exact(__A , __A ) for a in gold_answers ) UpperCamelCase__ = max(compute_fa(__A , __A ) for a in gold_answers ) return exact_scores, fa_scores def _UpperCamelCase ( __A , __A , __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} for qid, s in scores.items(): UpperCamelCase__ = na_probs[qid] > na_prob_thresh if pred_na: UpperCamelCase__ = float(not qid_to_has_ans[qid] ) else: UpperCamelCase__ = s return new_scores def _UpperCamelCase ( __A , __A , __A=None ) -> List[Any]: '''simple docstring''' if not qid_list: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores.values() ) / total), ("f1", 100.0 * sum(fa_scores.values() ) / total), ("total", total), ] ) else: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("f1", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("total", total), ] ) def _UpperCamelCase ( __A , __A , __A ) -> Optional[int]: '''simple docstring''' for k in new_eval: UpperCamelCase__ = new_eval[k] def _UpperCamelCase ( __A , __A , __A , __A ) -> Optional[int]: '''simple docstring''' plt.step(__A , __A , color="b" , alpha=0.2 , where="post" ) plt.fill_between(__A , __A , step="post" , alpha=0.2 , color="b" ) plt.xlabel("Recall" ) plt.ylabel("Precision" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__A ) plt.savefig(__A ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A , __A=None , __A=None ) -> Any: '''simple docstring''' UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) UpperCamelCase__ = 0.0 UpperCamelCase__ = 1.0 UpperCamelCase__ = 0.0 UpperCamelCase__ = [1.0] UpperCamelCase__ = [0.0] UpperCamelCase__ = 0.0 for i, qid in enumerate(__A ): if qid_to_has_ans[qid]: true_pos += scores[qid] UpperCamelCase__ = true_pos / float(i + 1 ) UpperCamelCase__ = true_pos / float(__A ) if i == len(__A ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__A ) recalls.append(__A ) if out_image: plot_pr_curve(__A , __A , __A , __A ) return {"ap": 100.0 * avg_prec} def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if out_image_dir and not os.path.exists(__A ): os.makedirs(__A ) UpperCamelCase__ = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_exact.png" ) , title="Precision-Recall curve for Exact Match score" , ) UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_f1.png" ) , title="Precision-Recall curve for F1 score" , ) UpperCamelCase__ = {k: float(__A ) for k, v in qid_to_has_ans.items()} UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_oracle.png" ) , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)" , ) merge_eval(__A , __A , "pr_exact" ) merge_eval(__A , __A , "pr_f1" ) merge_eval(__A , __A , "pr_oracle" ) def _UpperCamelCase ( __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if not qid_list: return UpperCamelCase__ = [na_probs[k] for k in qid_list] UpperCamelCase__ = np.ones_like(__A ) / float(len(__A ) ) plt.hist(__A , weights=__A , bins=20 , range=(0.0, 1.0) ) plt.xlabel("Model probability of no-answer" ) plt.ylabel("Proportion of dataset" ) plt.title(F'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__A , F'''na_prob_hist_{name}.png''' ) ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A ) -> Tuple: '''simple docstring''' UpperCamelCase__ = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) UpperCamelCase__ = num_no_ans UpperCamelCase__ = cur_score UpperCamelCase__ = 0.0 UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) for i, qid in enumerate(__A ): if qid not in scores: continue if qid_to_has_ans[qid]: UpperCamelCase__ = scores[qid] else: if preds[qid]: UpperCamelCase__ = -1 else: UpperCamelCase__ = 0 cur_score += diff if cur_score > best_score: UpperCamelCase__ = cur_score UpperCamelCase__ = na_probs[qid] return 100.0 * best_score / len(__A ), best_thresh def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> Dict: '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ = best_exact UpperCamelCase__ = exact_thresh UpperCamelCase__ = best_fa UpperCamelCase__ = fa_thresh def _UpperCamelCase ( ) -> Any: '''simple docstring''' with open(OPTS.data_file ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = dataset_json["data"] with open(OPTS.pred_file ) as f: UpperCamelCase__ = json.load(__A ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: UpperCamelCase__ = json.load(__A ) else: UpperCamelCase__ = {k: 0.0 for k in preds} UpperCamelCase__ = make_qid_to_has_ans(__A ) # maps qid to True/False UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if v] UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if not v] UpperCamelCase__ , UpperCamelCase__ = get_raw_scores(__A , __A ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = make_eval_dict(__A , __A ) if has_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "HasAns" ) if no_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "NoAns" ) if OPTS.na_prob_file: find_all_best_thresh(__A , __A , __A , __A , __A , __A ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__A , __A , __A , __A , __A , OPTS.out_image_dir ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "hasAns" ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "noAns" ) if OPTS.out_file: with open(OPTS.out_file , "w" ) as f: json.dump(__A , __A ) else: print(json.dumps(__A , indent=2 ) ) if __name__ == "__main__": a__ : Optional[int] = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
80
0
'''simple docstring''' from maths.prime_check import is_prime def __magic_name__ ( __UpperCAmelCase ) -> int: '''simple docstring''' if not isinstance(__UpperCAmelCase, __UpperCAmelCase ): snake_case_ = F"Input value of [number={number}] must be an integer" raise TypeError(__UpperCAmelCase ) if is_prime(__UpperCAmelCase ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
56
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType a__ : Optional[List[str]] = None a__ : Dict = '<' if sys.byteorder == 'little' else '>' # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image a__ : Any = [ np.dtype('|b1'), np.dtype('|u1'), np.dtype('<u2'), np.dtype('>u2'), np.dtype('<i2'), np.dtype('>i2'), np.dtype('<u4'), np.dtype('>u4'), np.dtype('<i4'), np.dtype('>i4'), np.dtype('<f4'), np.dtype('>f4'), np.dtype('<f8'), np.dtype('>f8'), ] @dataclass class lowercase_ : __UpperCAmelCase = True __UpperCAmelCase = None # Automatically constructed __UpperCAmelCase = "PIL.Image.Image" __UpperCAmelCase = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) __UpperCAmelCase = field(default='Image' , init=a__ , repr=a__ ) def __call__( self ): return self.pa_type def __a ( self , a ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if isinstance(a , a ): UpperCamelCase__ = np.array(a ) if isinstance(a , a ): return {"path": value, "bytes": None} elif isinstance(a , a ): return {"path": None, "bytes": value} elif isinstance(a , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(a ) elif isinstance(a , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(a ) elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def __a ( self , a , a=None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Image(decode=True) instead." ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support decoding images, please install 'Pillow'." ) if token_per_repo_id is None: UpperCamelCase__ = {} UpperCamelCase__ , UpperCamelCase__ = value["path"], value["bytes"] if bytes_ is None: if path is None: raise ValueError(f'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) else: if is_local_path(a ): UpperCamelCase__ = PIL.Image.open(a ) else: UpperCamelCase__ = path.split("::" )[-1] try: UpperCamelCase__ = string_to_dict(a , config.HUB_DATASETS_URL )["repo_id"] UpperCamelCase__ = token_per_repo_id.get(a ) except ValueError: UpperCamelCase__ = None with xopen(a , "rb" , use_auth_token=a ) as f: UpperCamelCase__ = BytesIO(f.read() ) UpperCamelCase__ = PIL.Image.open(bytes_ ) else: UpperCamelCase__ = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __a ( self ): from .features import Value return ( self if self.decode else { "bytes": Value("binary" ), "path": Value("string" ), } ) def __a ( self , a ): if pa.types.is_string(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCamelCase__ = storage.field("bytes" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCamelCase__ = storage.field("path" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): UpperCamelCase__ = pa.array( [encode_np_array(np.array(a ) )["bytes"] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays( [bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def __a ( self , a ): @no_op_if_value_is_null def path_to_bytes(a ): with xopen(a , "rb" ) as f: UpperCamelCase__ = f.read() return bytes_ UpperCamelCase__ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCamelCase__ = pa.array( [os.path.basename(a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def _UpperCamelCase ( ) -> List[str]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() UpperCamelCase__ = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def _UpperCamelCase ( __A ) -> bytes: '''simple docstring''' UpperCamelCase__ = BytesIO() if image.format in list_image_compression_formats(): UpperCamelCase__ = image.format else: UpperCamelCase__ = "PNG" if image.mode in ["1", "L", "LA", "RGB", "RGBA"] else "TIFF" image.save(__A , format=__A ) return buffer.getvalue() def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if hasattr(__A , "filename" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) UpperCamelCase__ = array.dtype UpperCamelCase__ = dtype.byteorder if dtype.byteorder != "=" else _NATIVE_BYTEORDER UpperCamelCase__ = dtype.kind UpperCamelCase__ = dtype.itemsize UpperCamelCase__ = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: UpperCamelCase__ = np.dtype("|u1" ) if dtype_kind not in ["u", "i"]: raise TypeError( F'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.''' ) if dtype is not dest_dtype: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: UpperCamelCase__ = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: UpperCamelCase__ = dtype_byteorder + dtype_kind + str(__A ) UpperCamelCase__ = np.dtype(__A ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}''' ) UpperCamelCase__ = PIL.Image.fromarray(array.astype(__A ) ) return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> List[dict]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if objs: UpperCamelCase__ , UpperCamelCase__ = first_non_null_value(__A ) if isinstance(__A , __A ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__A , np.ndarray ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] elif isinstance(__A , PIL.Image.Image ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] else: return objs else: return objs
80
0
"""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 A : int = logging.get_logger(__name__) A : Tuple = { "Salesforce/instruct-blip-flan-t5": "https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json", } class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Any ="""instructblip_vision_model""" def __init__( self , __a=14_08 , __a=61_44 , __a=39 , __a=16 , __a=2_24 , __a=14 , __a="gelu" , __a=1e-6 , __a=0.0 , __a=1e-1_0 , __a=True , **__a , ): super().__init__(**__a ) __lowerCAmelCase = hidden_size __lowerCAmelCase = intermediate_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = patch_size __lowerCAmelCase = image_size __lowerCAmelCase = initializer_range __lowerCAmelCase = attention_dropout __lowerCAmelCase = layer_norm_eps __lowerCAmelCase = hidden_act __lowerCAmelCase = qkv_bias @classmethod def snake_case ( cls , __a , **__a ): cls._set_token_in_kwargs(__a ) __lowerCAmelCase , __lowerCAmelCase = cls.get_config_dict(__a , **__a ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get("model_type" ) == "instructblip": __lowerCAmelCase = 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 _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : str ="""instructblip_qformer""" def __init__( self , __a=3_05_22 , __a=7_68 , __a=12 , __a=12 , __a=30_72 , __a="gelu" , __a=0.1 , __a=0.1 , __a=5_12 , __a=0.0_2 , __a=1e-1_2 , __a=0 , __a="absolute" , __a=2 , __a=14_08 , **__a , ): super().__init__(pad_token_id=__a , **__a ) __lowerCAmelCase = vocab_size __lowerCAmelCase = hidden_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = hidden_act __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = max_position_embeddings __lowerCAmelCase = initializer_range __lowerCAmelCase = layer_norm_eps __lowerCAmelCase = position_embedding_type __lowerCAmelCase = cross_attention_frequency __lowerCAmelCase = encoder_hidden_size @classmethod def snake_case ( cls , __a , **__a ): cls._set_token_in_kwargs(__a ) __lowerCAmelCase , __lowerCAmelCase = cls.get_config_dict(__a , **__a ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get("model_type" ) == "instructblip": __lowerCAmelCase = 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 _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Dict ="""instructblip""" __UpperCAmelCase : Tuple =True def __init__( self , __a=None , __a=None , __a=None , __a=32 , **__a ): super().__init__(**__a ) if vision_config is None: __lowerCAmelCase = {} logger.info("vision_config is None. initializing the InstructBlipVisionConfig with default values." ) if qformer_config is None: __lowerCAmelCase = {} logger.info("qformer_config is None. Initializing the InstructBlipQFormerConfig with default values." ) if text_config is None: __lowerCAmelCase = {} logger.info("text_config is None. Initializing the text config with default values (`OPTConfig`)." ) __lowerCAmelCase = InstructBlipVisionConfig(**__a ) __lowerCAmelCase = InstructBlipQFormerConfig(**__a ) __lowerCAmelCase = text_config["model_type"] if "model_type" in text_config else "opt" __lowerCAmelCase = CONFIG_MAPPING[text_model_type](**__a ) __lowerCAmelCase = self.text_config.tie_word_embeddings __lowerCAmelCase = self.text_config.is_encoder_decoder __lowerCAmelCase = num_query_tokens __lowerCAmelCase = self.vision_config.hidden_size __lowerCAmelCase = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __lowerCAmelCase = 1.0 __lowerCAmelCase = 0.0_2 @classmethod def snake_case ( cls , __a , __a , __a , **__a , ): return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **__a , ) def snake_case ( self ): __lowerCAmelCase = copy.deepcopy(self.__dict__ ) __lowerCAmelCase = self.vision_config.to_dict() __lowerCAmelCase = self.qformer_config.to_dict() __lowerCAmelCase = self.text_config.to_dict() __lowerCAmelCase = self.__class__.model_type return output
57
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> int: '''simple docstring''' if depth < 0: raise ValueError("Depth cannot be less than 0" ) if not scores: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) ) def _UpperCamelCase ( ) -> None: '''simple docstring''' UpperCamelCase__ = [90, 23, 6, 33, 21, 65, 123, 34423] UpperCamelCase__ = math.log(len(__A ) , 2 ) print(F'''Optimal value : {minimax(0 , 0 , __A , __A , __A )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
80
0
'''simple docstring''' from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class a_ ( snake_case_ ): '''simple docstring''' def snake_case_( self ) -> Tuple: return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = {"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]} return Dataset.from_dict(A ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertListEqual(dset.column_names , ["""col_1""", """col_2"""] ) for i, r in enumerate(A ): self.assertDictEqual(A , example_records[i] ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) _SCREAMING_SNAKE_CASE = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def snake_case_( self ) -> Union[str, Any]: # checks what happens with missing columns _SCREAMING_SNAKE_CASE = [{"""col_1""": 1}, {"""col_2""": """x"""}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertDictEqual(dset[0] , {"""col_1""": 1} ) self.assertDictEqual(dset[1] , {"""col_1""": None} ) # NB: first record is used for columns def snake_case_( self ) -> Optional[Any]: # checks if the type can be inferred from the second record _SCREAMING_SNAKE_CASE = [{"""col_1""": []}, {"""col_1""": [1, 2]}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertEqual(dset.info.features["""col_1"""] , Sequence(Value("""int64""" ) ) ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = Dataset.from_list([] ) self.assertEqual(len(A ) , 0 ) self.assertListEqual(dset.column_names , [] )
58
'''simple docstring''' def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def _UpperCamelCase ( __A = 100 ) -> int: '''simple docstring''' UpperCamelCase__ = 1 UpperCamelCase__ = 2 for i in range(2 , max_n + 1 ): UpperCamelCase__ = pre_numerator UpperCamelCase__ = 2 * i // 3 if i % 3 == 0 else 1 UpperCamelCase__ = cur_numerator UpperCamelCase__ = e_cont * pre_numerator + temp return sum_digits(__A ) if __name__ == "__main__": print(F"""{solution() = }""")
80
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __lowerCamelCase = { """configuration_pix2struct""": [ """PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Pix2StructConfig""", """Pix2StructTextConfig""", """Pix2StructVisionConfig""", ], """processing_pix2struct""": ["""Pix2StructProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = ["""Pix2StructImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = [ """PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Pix2StructPreTrainedModel""", """Pix2StructForConditionalGeneration""", """Pix2StructVisionModel""", """Pix2StructTextModel""", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys __lowerCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
59
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' with open(__A ) as metadata_file: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = LukeConfig(use_entity_aware_attention=__A , **metadata["model_config"] ) # Load in the weights from the checkpoint_path UpperCamelCase__ = torch.load(__A , map_location="cpu" )["module"] # Load the entity vocab file UpperCamelCase__ = load_original_entity_vocab(__A ) # add an entry for [MASK2] UpperCamelCase__ = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase__ = XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase__ = AddedToken("<ent>" , lstrip=__A , rstrip=__A ) UpperCamelCase__ = AddedToken("<ent2>" , lstrip=__A , rstrip=__A ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'''Saving tokenizer to {pytorch_dump_folder_path}''' ) tokenizer.save_pretrained(__A ) with open(os.path.join(__A , "tokenizer_config.json" ) , "r" ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = "MLukeTokenizer" with open(os.path.join(__A , "tokenizer_config.json" ) , "w" ) as f: json.dump(__A , __A ) with open(os.path.join(__A , MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(__A , __A ) UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) # Initialize the embeddings of the special tokens UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["@"] )[0] UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["#"] )[0] UpperCamelCase__ = state_dict["embeddings.word_embeddings.weight"] UpperCamelCase__ = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase__ = state_dict[bias_name] UpperCamelCase__ = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: UpperCamelCase__ = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase__ = state_dict["entity_embeddings.entity_embeddings.weight"] UpperCamelCase__ = entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase__ = state_dict["entity_predictions.bias"] UpperCamelCase__ = entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase__ = LukeForMaskedLM(config=__A ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) UpperCamelCase__ = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): UpperCamelCase__ = state_dict[key] else: UpperCamelCase__ = state_dict[key] UpperCamelCase__ , UpperCamelCase__ = model.load_state_dict(__A , strict=__A ) if set(__A ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(__A ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A , task="entity_classification" ) UpperCamelCase__ = "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." UpperCamelCase__ = (0, 9) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 33, 768) ) UpperCamelCase__ = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}''' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 1, 768) ) UpperCamelCase__ = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is''' F''' {expected_shape}''' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) UpperCamelCase__ = "Tokyo is the capital of <mask>." UpperCamelCase__ = (24, 30) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) UpperCamelCase__ = encoding["input_ids"][0].tolist() UpperCamelCase__ = input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) UpperCamelCase__ = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(__A ) UpperCamelCase__ = outputs.entity_logits[0][0].argmax().item() UpperCamelCase__ = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(__A ) ) model.save_pretrained(__A ) def _UpperCamelCase ( __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = ["[MASK]", "[PAD]", "[UNK]"] UpperCamelCase__ = [json.loads(__A ) for line in open(__A )] UpperCamelCase__ = {} for entry in data: UpperCamelCase__ = entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase__ = entity_id break UpperCamelCase__ = F'''{language}:{entity_name}''' UpperCamelCase__ = entity_id return new_mapping if __name__ == "__main__": a__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) a__ : Any = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
80
0
"""simple docstring""" from manim import * class snake_case_( a__ ): def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase : List[str] = Rectangle(height=0.5 , width=0.5 ) lowerCAmelCase : Union[str, Any] = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) lowerCAmelCase : str = [mem.copy() for i in range(6 )] lowerCAmelCase : str = [mem.copy() for i in range(6 )] lowerCAmelCase : List[str] = VGroup(*UpperCamelCase_ ).arrange(UpperCamelCase_ , buff=0 ) lowerCAmelCase : Optional[Any] = VGroup(*UpperCamelCase_ ).arrange(UpperCamelCase_ , buff=0 ) lowerCAmelCase : Optional[Any] = VGroup(UpperCamelCase_ , UpperCamelCase_ ).arrange(UpperCamelCase_ , buff=0 ) lowerCAmelCase : Optional[int] = Text('''CPU''' , font_size=2_4 ) lowerCAmelCase : List[str] = Group(UpperCamelCase_ , UpperCamelCase_ ).arrange(UpperCamelCase_ , buff=0.5 , aligned_edge=UpperCamelCase_ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = [mem.copy() for i in range(1 )] lowerCAmelCase : Any = VGroup(*UpperCamelCase_ ).arrange(UpperCamelCase_ , buff=0 ) lowerCAmelCase : str = Text('''GPU''' , font_size=2_4 ) lowerCAmelCase : int = Group(UpperCamelCase_ , UpperCamelCase_ ).arrange(UpperCamelCase_ , buff=0.5 , aligned_edge=UpperCamelCase_ ) gpu.align_to(UpperCamelCase_ , UpperCamelCase_ ) gpu.set_x(gpu.get_x() - 1 ) self.add(UpperCamelCase_ ) lowerCAmelCase : Optional[int] = [mem.copy() for i in range(6 )] lowerCAmelCase : Union[str, Any] = VGroup(*UpperCamelCase_ ).arrange(UpperCamelCase_ , buff=0 ) lowerCAmelCase : List[Any] = Text('''Model''' , font_size=2_4 ) lowerCAmelCase : Any = Group(UpperCamelCase_ , UpperCamelCase_ ).arrange(UpperCamelCase_ , buff=0.5 , aligned_edge=UpperCamelCase_ ) model.move_to([3, -1.0, 0] ) self.play( Create(UpperCamelCase_ , run_time=1 ) , Create(UpperCamelCase_ , run_time=1 ) , Create(UpperCamelCase_ , run_time=1 ) , ) lowerCAmelCase : Union[str, Any] = MarkupText( F'''First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.''' , font_size=2_4 , ) lowerCAmelCase : Optional[int] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) lowerCAmelCase : Optional[Any] = MarkupText( F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=1_8 , ) key_text.move_to([-5, 2.4, 0] ) step_a.move_to([2, 2, 0] ) self.play(Write(UpperCamelCase_ , run_time=2.5 ) , Write(UpperCamelCase_ ) , Write(UpperCamelCase_ ) ) self.add(UpperCamelCase_ ) lowerCAmelCase : Dict = [] lowerCAmelCase : str = [] lowerCAmelCase : List[str] = [] for i, rect in enumerate(UpperCamelCase_ ): lowerCAmelCase : Optional[int] = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(UpperCamelCase_ , opacity=0.7 ) cpu_target.move_to(UpperCamelCase_ ) cpu_target.generate_target() lowerCAmelCase : Dict = 0.46 / 4 lowerCAmelCase : int = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=UpperCamelCase_ ) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 ) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target , direction=UpperCamelCase_ , buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target , direction=UpperCamelCase_ , buff=0.0 ) cpu_targs.append(UpperCamelCase_ ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(UpperCamelCase_ ) ) second_animations.append(MoveToTarget(UpperCamelCase_ , run_time=1.5 ) ) self.play(*UpperCamelCase_ ) self.play(*UpperCamelCase_ ) self.wait()
60
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Any = logging.get_logger(__name__) a__ : str = { 'SCUT-DLVCLab/lilt-roberta-en-base': ( 'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json' ), } class lowercase_ ( a__ ): __UpperCAmelCase = 'lilt' def __init__( self , a=3_05_22 , a=7_68 , a=12 , a=12 , a=30_72 , a="gelu" , a=0.1 , a=0.1 , a=5_12 , a=2 , a=0.02 , a=1e-12 , a=0 , a="absolute" , a=None , a=4 , a=10_24 , **a , ): super().__init__(pad_token_id=a , **a ) UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = position_embedding_type UpperCamelCase__ = classifier_dropout UpperCamelCase__ = channel_shrink_ratio UpperCamelCase__ = max_ad_position_embeddings
80
0
"""simple docstring""" from manim import * class A_ (lowercase__ ): '''simple docstring''' def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : str = Rectangle(height=0.5 , width=0.5 ) UpperCAmelCase_ : Optional[Any] = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) UpperCAmelCase_ : Union[str, Any] = [mem.copy() for i in range(6 )] UpperCAmelCase_ : List[Any] = [mem.copy() for i in range(6 )] UpperCAmelCase_ : List[str] = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) UpperCAmelCase_ : List[Any] = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) UpperCAmelCase_ : Dict = VGroup(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0 ) UpperCAmelCase_ : List[Any] = Text("CPU" , font_size=24 ) UpperCAmelCase_ : int = Group(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0.5 , aligned_edge=lowercase_ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(lowercase_ ) UpperCAmelCase_ : Union[str, Any] = [mem.copy() for i in range(1 )] UpperCAmelCase_ : Tuple = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) UpperCAmelCase_ : Any = Text("GPU" , font_size=24 ) UpperCAmelCase_ : Tuple = Group(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0.5 , aligned_edge=lowercase_ ) gpu.align_to(lowercase_ , lowercase_ ) gpu.set_x(gpu.get_x() - 1 ) self.add(lowercase_ ) UpperCAmelCase_ : Any = [mem.copy() for i in range(6 )] UpperCAmelCase_ : str = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) UpperCAmelCase_ : Dict = Text("Model" , font_size=24 ) UpperCAmelCase_ : Tuple = Group(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0.5 , aligned_edge=lowercase_ ) model.move_to([3, -1.0, 0] ) self.play( Create(lowercase_ , run_time=1 ) , Create(lowercase_ , run_time=1 ) , Create(lowercase_ , run_time=1 ) , ) UpperCAmelCase_ : Any = MarkupText( F"""First, an empty model skeleton is loaded\ninto <span fgcolor='{YELLOW}'>memory</span> without using much RAM.""" , font_size=24 , ) UpperCAmelCase_ : Union[str, Any] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) UpperCAmelCase_ : Any = MarkupText( F"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) step_a.move_to([2, 2, 0] ) self.play(Write(lowercase_ , run_time=2.5 ) , Write(lowercase_ ) , Write(lowercase_ ) ) self.add(lowercase_ ) UpperCAmelCase_ : Union[str, Any] = [] UpperCAmelCase_ : List[str] = [] UpperCAmelCase_ : Dict = [] for i, rect in enumerate(lowercase_ ): UpperCAmelCase_ : Union[str, Any] = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(lowercase_ , opacity=0.7 ) cpu_target.move_to(lowercase_ ) cpu_target.generate_target() UpperCAmelCase_ : int = 0.46 / 4 UpperCAmelCase_ : Dict = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=lowercase_ ) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 ) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target , direction=lowercase_ , buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target , direction=lowercase_ , buff=0.0 ) cpu_targs.append(lowercase_ ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(lowercase_ ) ) second_animations.append(MoveToTarget(lowercase_ , run_time=1.5 ) ) self.play(*lowercase_ ) self.play(*lowercase_ ) self.wait()
61
'''simple docstring''' a__ : Union[str, Any] = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution a__ : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 a__ : Optional[Any] = True a__ : Optional[Any] = False def _UpperCamelCase ( __A ) -> bool: '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__A ) ) UpperCamelCase__ = number_chain while number < 10000000: UpperCamelCase__ = number_chain number *= 10 return number_chain def _UpperCamelCase ( __A = 10000000 ) -> int: '''simple docstring''' for i in range(1 , __A ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__A ) if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution() = }""")
80
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : int = KandinskyImgaImgPipeline UpperCAmelCase__ : List[Any] = ["prompt", "image_embeds", "negative_image_embeds", "image"] UpperCAmelCase__ : str = [ "prompt", "negative_prompt", "image_embeds", "negative_image_embeds", "image", ] UpperCAmelCase__ : Optional[int] = [ "generator", "height", "width", "strength", "guidance_scale", "negative_prompt", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] UpperCAmelCase__ : Optional[Any] = False @property def _a ( self ) -> Optional[Any]: return 32 @property def _a ( self ) -> Dict: return 32 @property def _a ( self ) -> List[str]: return self.time_input_dim @property def _a ( self ) -> Union[str, Any]: return self.time_input_dim * 4 @property def _a ( self ) -> List[str]: return 100 @property def _a ( self ) -> str: __UpperCamelCase =XLMRobertaTokenizerFast.from_pretrained('YiYiXu/tiny-random-mclip-base' ) return tokenizer @property def _a ( self ) -> int: torch.manual_seed(0 ) __UpperCamelCase =MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) __UpperCamelCase =MultilingualCLIP(A_ ) __UpperCamelCase =text_encoder.eval() return text_encoder @property def _a ( self ) -> int: torch.manual_seed(0 ) __UpperCamelCase ={ 'in_channels': 4, # Out channels is double in channels because predicts mean and variance 'out_channels': 8, 'addition_embed_type': 'text_image', 'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'), 'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'), 'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn', 'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2), 'layers_per_block': 1, 'encoder_hid_dim': self.text_embedder_hidden_size, 'encoder_hid_dim_type': 'text_image_proj', 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': None, } __UpperCamelCase =UNetaDConditionModel(**A_ ) return model @property def _a ( self ) -> Any: return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def _a ( self ) -> int: torch.manual_seed(0 ) __UpperCamelCase =VQModel(**self.dummy_movq_kwargs ) return model def _a ( self ) -> Any: __UpperCamelCase =self.dummy_text_encoder __UpperCamelCase =self.dummy_tokenizer __UpperCamelCase =self.dummy_unet __UpperCamelCase =self.dummy_movq __UpperCamelCase ={ 'num_train_timesteps': 1000, 'beta_schedule': 'linear', 'beta_start': 0.0_0085, 'beta_end': 0.012, 'clip_sample': False, 'set_alpha_to_one': False, 'steps_offset': 0, 'prediction_type': 'epsilon', 'thresholding': False, } __UpperCamelCase =DDIMScheduler(**A_ ) __UpperCamelCase ={ 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def _a ( self , A_ , A_=0 ) -> int: __UpperCamelCase =floats_tensor((1, self.cross_attention_dim) , rng=random.Random(A_ ) ).to(A_ ) __UpperCamelCase =floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(A_ ) # create init_image __UpperCamelCase =floats_tensor((1, 3, 64, 64) , rng=random.Random(A_ ) ).to(A_ ) __UpperCamelCase =image.cpu().permute(0 , 2 , 3 , 1 )[0] __UpperCamelCase =Image.fromarray(np.uinta(A_ ) ).convert('RGB' ).resize((256, 256) ) if str(A_ ).startswith('mps' ): __UpperCamelCase =torch.manual_seed(A_ ) else: __UpperCamelCase =torch.Generator(device=A_ ).manual_seed(A_ ) __UpperCamelCase ={ 'prompt': 'horse', 'image': init_image, 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'generator': generator, 'height': 64, 'width': 64, 'num_inference_steps': 10, 'guidance_scale': 7.0, 'strength': 0.2, 'output_type': 'np', } return inputs def _a ( self ) -> Dict: __UpperCamelCase ='cpu' __UpperCamelCase =self.get_dummy_components() __UpperCamelCase =self.pipeline_class(**A_ ) __UpperCamelCase =pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =pipe(**self.get_dummy_inputs(A_ ) ) __UpperCamelCase =output.images __UpperCamelCase =pipe( **self.get_dummy_inputs(A_ ) , return_dict=A_ , )[0] __UpperCamelCase =image[0, -3:, -3:, -1] __UpperCamelCase =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __UpperCamelCase =np.array( [0.6147_4943, 0.607_3539, 0.4330_8544, 0.592_8269, 0.4749_3595, 0.4675_5973, 0.461_3838, 0.4536_8797, 0.5011_9233] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f' expected_slice {expected_slice}, but got {image_slice.flatten()}' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}' @slow @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> str: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> List[str]: __UpperCamelCase =load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/kandinsky_img2img_frog.npy' ) __UpperCamelCase =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png' ) __UpperCamelCase ='A red cartoon frog, 4k' __UpperCamelCase =KandinskyPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-1-prior' , torch_dtype=torch.floataa ) pipe_prior.to(A_ ) __UpperCamelCase =KandinskyImgaImgPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-1' , torch_dtype=torch.floataa ) __UpperCamelCase =pipeline.to(A_ ) pipeline.set_progress_bar_config(disable=A_ ) __UpperCamelCase =torch.Generator(device='cpu' ).manual_seed(0 ) __UpperCamelCase , __UpperCamelCase =pipe_prior( A_ , generator=A_ , num_inference_steps=5 , negative_prompt='' , ).to_tuple() __UpperCamelCase =pipeline( A_ , image=A_ , image_embeds=A_ , negative_image_embeds=A_ , generator=A_ , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type='np' , ) __UpperCamelCase =output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(A_ , A_ )
62
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def _UpperCamelCase ( __A , __A , __A=1024 , __A=1024 , __A=False , **__A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = AutoTokenizer.from_pretrained(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="train" , **__A ) UpperCamelCase__ = tok.pad_token_id def get_lens(__A ): UpperCamelCase__ = tqdm( DataLoader(__A , batch_size=512 , num_workers=8 , shuffle=__A , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) UpperCamelCase__ = [] for batch in dl: UpperCamelCase__ = batch["input_ids"].ne(__A ).sum(1 ).tolist() UpperCamelCase__ = batch["labels"].ne(__A ).sum(1 ).tolist() if consider_target: for src, tgt in zip(__A , __A ): max_lens.append(max(__A , __A ) ) else: max_lens.extend(__A ) return max_lens UpperCamelCase__ = get_lens(__A ) UpperCamelCase__ = SeqaSeqDataset(__A , __A , __A , __A , type_path="val" , **__A ) UpperCamelCase__ = get_lens(__A ) pickle_save(__A , train_ds.len_file ) pickle_save(__A , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
80
0
'''simple docstring''' def _lowerCamelCase ( lowercase : str ) -> str: return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
63
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer a__ : int = logging.get_logger(__name__) a__ : List[str] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a__ : List[Any] = { 'vocab_file': { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt' ), } } a__ : Optional[Any] = { 'junnyu/roformer_chinese_small': 1_5_3_6, 'junnyu/roformer_chinese_base': 1_5_3_6, 'junnyu/roformer_chinese_char_small': 5_1_2, 'junnyu/roformer_chinese_char_base': 5_1_2, 'junnyu/roformer_small_discriminator': 1_2_8, 'junnyu/roformer_small_generator': 1_2_8, } a__ : str = { 'junnyu/roformer_chinese_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_base': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_base': {'do_lower_case': True}, 'junnyu/roformer_small_discriminator': {'do_lower_case': True}, 'junnyu/roformer_small_generator': {'do_lower_case': True}, } class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase = RoFormerTokenizer def __init__( self , a=None , a=None , a=True , a="[UNK]" , a="[SEP]" , a="[PAD]" , a="[CLS]" , a="[MASK]" , a=True , a=None , **a , ): super().__init__( a , tokenizer_file=a , do_lower_case=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , tokenize_chinese_chars=a , strip_accents=a , **a , ) UpperCamelCase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , a ) != do_lower_case or pre_tok_state.get("strip_accents" , a ) != strip_accents ): UpperCamelCase__ = getattr(a , pre_tok_state.pop("type" ) ) UpperCamelCase__ = do_lower_case UpperCamelCase__ = strip_accents UpperCamelCase__ = pre_tok_class(**a ) UpperCamelCase__ = do_lower_case def __getstate__( self ): UpperCamelCase__ = self.__dict__.copy() UpperCamelCase__ = BertPreTokenizer() return state def __setstate__( self , a ): UpperCamelCase__ = d UpperCamelCase__ = self.__dict__["_tokenizer"].get_vocab() UpperCamelCase__ = PreTokenizer.custom(JiebaPreTokenizer(a ) ) def __a ( self , a , a=None ): UpperCamelCase__ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __a ( self , a , a = None ): UpperCamelCase__ = [self.sep_token_id] UpperCamelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __a ( self , a , a = None ): UpperCamelCase__ = self._tokenizer.model.save(a , name=a ) return tuple(a ) def __a ( self , a , a=None , a=None , a=False , **a , ): UpperCamelCase__ = BertPreTokenizer() return super().save_pretrained(a , a , a , a , **a )
80
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A_ = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''], '''tokenization_xlm''': ['''XLMTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMForMultipleChoice''', '''XLMForQuestionAnswering''', '''XLMForQuestionAnsweringSimple''', '''XLMForSequenceClassification''', '''XLMForTokenClassification''', '''XLMModel''', '''XLMPreTrainedModel''', '''XLMWithLMHeadModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMForMultipleChoice''', '''TFXLMForQuestionAnsweringSimple''', '''TFXLMForSequenceClassification''', '''TFXLMForTokenClassification''', '''TFXLMMainLayer''', '''TFXLMModel''', '''TFXLMPreTrainedModel''', '''TFXLMWithLMHeadModel''', ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
64
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : Optional[int] = {'vocab_file': 'vocab.txt'} a__ : Optional[Any] = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } a__ : Optional[int] = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def _UpperCamelCase ( __A ) -> str: '''simple docstring''' with open(__A , "r" ) as f: UpperCamelCase__ = f.read().splitlines() return [l.strip() for l in lines] class lowercase_ ( a__ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self , a , a="<unk>" , a="<cls>" , a="<pad>" , a="<mask>" , a="<eos>" , **a , ): super().__init__(**a ) UpperCamelCase__ = load_vocab_file(a ) UpperCamelCase__ = dict(enumerate(self.all_tokens ) ) UpperCamelCase__ = {tok: ind for ind, tok in enumerate(self.all_tokens )} UpperCamelCase__ = unk_token UpperCamelCase__ = cls_token UpperCamelCase__ = pad_token UpperCamelCase__ = mask_token UpperCamelCase__ = eos_token UpperCamelCase__ = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a , **a ): return text.split() def __a ( self , a=False ): return len(self._id_to_token ) def __a ( self ): return {token: i for i, token in enumerate(self.all_tokens )} def __a ( self , a ): return self._token_to_id.get(a , self._token_to_id.get(self.unk_token ) ) def __a ( self , a ): return self._id_to_token.get(a , self.unk_token ) def __a ( self , a , a = None ): UpperCamelCase__ = [self.cls_token_id] UpperCamelCase__ = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError("Cannot tokenize multiple sequences when EOS token is not set!" ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __a ( self , a , a = None , a = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] UpperCamelCase__ = [1] + ([0] * len(a )) + [1] if token_ids_a is not None: mask += [0] * len(a ) + [1] return mask def __a ( self , a , a ): UpperCamelCase__ = os.path.join(a , (filename_prefix + "-" if filename_prefix else "") + "vocab.txt" ) with open(a , "w" ) as f: f.write("\n".join(self.all_tokens ) ) return (vocab_file,) @property def __a ( self ): return self.get_vocab_size(with_added_tokens=a ) def __a ( self , a , a = False ): return super()._add_tokens(a , special_tokens=a )
80
0
import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def lowerCAmelCase_ ( __A ) -> str: '''simple docstring''' UpperCAmelCase__ = [] for line in lines: UpperCAmelCase__ = re.sub(r"#.*", "", __A ) # remove comments if line: filtered_lines.append(__A ) UpperCAmelCase__ = "\n".join(__A ) # Make a hash from all this code UpperCAmelCase__ = full_str.encode("utf-8" ) return shaaaa(__A ).hexdigest() # get importable module names and hash for caching UpperCamelCase__ = { 'csv': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), 'json': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), 'pandas': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), 'parquet': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), 'arrow': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), 'text': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), 'imagefolder': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), 'audiofolder': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions UpperCamelCase__ = { '.csv': ('csv', {}), '.tsv': ('csv', {'sep': '\t'}), '.json': ('json', {}), '.jsonl': ('json', {}), '.parquet': ('parquet', {}), '.arrow': ('arrow', {}), '.txt': ('text', {}), } _EXTENSION_TO_MODULE.update({ext: ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) UpperCamelCase__ = {'imagefolder', 'audiofolder'} # Used to filter data files based on extensions given a module name UpperCamelCase__ = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append('.zip') _MODULE_TO_EXTENSIONS["audiofolder"].append('.zip')
65
'''simple docstring''' from math import factorial, pi def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_sin() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(__A ) ) def _UpperCamelCase ( __A , __A = 30 ) -> float: '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError("maclaurin_cos() requires either an int or float for theta" ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy" ) UpperCamelCase__ = float(__A ) UpperCamelCase__ = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(__A ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(1_0)) print(maclaurin_sin(-1_0)) print(maclaurin_sin(1_0, 1_5)) print(maclaurin_sin(-1_0, 1_5)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(1_0, 1_5)) print(maclaurin_cos(-1_0, 1_5))
80
0
"""simple docstring""" import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class lowerCamelCase ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' _A : Union[str, Any] = BlenderbotSmallTokenizer _A : List[Any] = False def lowerCAmelCase_ ( self: Any ) -> Dict: super().setUp() snake_case_ :Dict = ["""__start__""", """adapt""", """act""", """ap@@""", """te""", """__end__""", """__unk__"""] snake_case_ :Dict = dict(zip(snake_case , range(len(snake_case ) ) ) ) snake_case_ :Union[str, Any] = ["""#version: 0.2""", """a p""", """t e</w>""", """ap t</w>""", """a d""", """ad apt</w>""", """a c""", """ac t</w>""", """"""] snake_case_ :Dict = {"""unk_token""": """__unk__""", """bos_token""": """__start__""", """eos_token""": """__end__"""} snake_case_ :Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) snake_case_ :str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(snake_case ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(snake_case ) ) def lowerCAmelCase_ ( self: List[Any] , **snake_case: Optional[int] ) -> str: kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **snake_case ) def lowerCAmelCase_ ( self: Any , snake_case: Optional[Any] ) -> Any: snake_case_ :Any = """adapt act apte""" snake_case_ :int = """adapt act apte""" return input_text, output_text def lowerCAmelCase_ ( self: Optional[int] ) -> Optional[int]: snake_case_ :Any = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) snake_case_ :Dict = """adapt act apte""" snake_case_ :Optional[Any] = ["""adapt""", """act""", """ap@@""", """te"""] snake_case_ :List[str] = tokenizer.tokenize(snake_case ) self.assertListEqual(snake_case , snake_case ) snake_case_ :int = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] snake_case_ :str = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case ) , snake_case ) def lowerCAmelCase_ ( self: Optional[Any] ) -> Union[str, Any]: snake_case_ :List[Any] = BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" ) assert tok("""sam""" ).input_ids == [1_384] snake_case_ :str = """I am a small frog.""" snake_case_ :Dict = tok([src_text] , padding=snake_case , truncation=snake_case )["""input_ids"""] snake_case_ :Optional[Any] = tok.batch_decode(snake_case , skip_special_tokens=snake_case , clean_up_tokenization_spaces=snake_case )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def lowerCAmelCase_ ( self: str ) -> str: snake_case_ :Optional[int] = BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" ) snake_case_ :str = """I am a small frog .""" snake_case_ :Dict = """.""" snake_case_ :int = tok(snake_case )["""input_ids"""] snake_case_ :List[Any] = tok(snake_case )["""input_ids"""] assert encoded[-1] == encoded_dot[0]
66
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class lowercase_ ( a__ ): def __init__( self , a , a , a = None , a = None , a = False , **a , ): super().__init__(features=a , cache_dir=a , keep_in_memory=a , **a ) UpperCamelCase__ = Sql( cache_dir=a , features=a , sql=a , con=a , **a , ) def __a ( self ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None self.builder.download_and_prepare( download_config=a , download_mode=a , verification_mode=a , base_path=a , ) # Build dataset for splits UpperCamelCase__ = self.builder.as_dataset( split="train" , verification_mode=a , in_memory=self.keep_in_memory ) return dataset class lowercase_ : def __init__( self , a , a , a , a = None , a = None , **a , ): if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) UpperCamelCase__ = dataset UpperCamelCase__ = name UpperCamelCase__ = con UpperCamelCase__ = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE UpperCamelCase__ = num_proc UpperCamelCase__ = to_sql_kwargs def __a ( self ): UpperCamelCase__ = self.to_sql_kwargs.pop("sql" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("con" , a ) UpperCamelCase__ = self.to_sql_kwargs.pop("index" , a ) UpperCamelCase__ = self._write(index=a , **self.to_sql_kwargs ) return written def __a ( self , a ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = args UpperCamelCase__ = {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs UpperCamelCase__ = query_table( table=self.dataset.data , key=slice(a , offset + self.batch_size ) , indices=self.dataset._indices , ) UpperCamelCase__ = batch.to_pandas() UpperCamelCase__ = df.to_sql(self.name , self.con , index=a , **a ) return num_rows or len(a ) def __a ( self , a , **a ): UpperCamelCase__ = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: UpperCamelCase__ , UpperCamelCase__ = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , a , a )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += num_rows return written
80
0
'''simple docstring''' import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer __lowerCamelCase = flax_key_tuple[:-1] + ('''weight''',) __lowerCamelCase = torch.permute(UpperCamelCase__ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(UpperCamelCase__ ): # linear layer __lowerCamelCase = flax_key_tuple[:-1] + ('''weight''',) __lowerCamelCase = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: __lowerCamelCase = flax_key_tuple[:-1] + ('''weight''',) return flax_key_tuple, flax_tensor def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]: if "metadata" in layer: __lowerCamelCase = layer.split('''metadata''' ) __lowerCamelCase = ''''''.join(split_layer[0] )[:-1] __lowerCamelCase = [tuple(('''metadata''' + split_layer[1]).split('''/''' ) )] elif "kvstore" in layer: __lowerCamelCase = layer.split('''kvstore''' ) __lowerCamelCase = ''''''.join(split_layer[0] )[:-1] __lowerCamelCase = [tuple(('''kvstore''' + split_layer[1]).split('''/''' ) )] else: __lowerCamelCase = layer.split('''/''' ) __lowerCamelCase = '''/'''.join(split_layer[:-1] ) __lowerCamelCase = (split_layer[-1],) if "kvstore/path" in layer: __lowerCamelCase = f"""{switch_checkpoint_path}/{checkpoint_info[layer]}""" elif "kvstore/driver" in layer: __lowerCamelCase = '''file''' else: __lowerCamelCase = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Dict: __lowerCamelCase = rename_keys(UpperCamelCase__ ) __lowerCamelCase = {} for k, v in current_block.items(): __lowerCamelCase = v __lowerCamelCase = new_current_block torch.save(UpperCamelCase__ , UpperCamelCase__ ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = WEIGHTS_NAME ) -> Tuple: __lowerCamelCase = convert_file_size_to_int(UpperCamelCase__ ) __lowerCamelCase = [] __lowerCamelCase = {} __lowerCamelCase = 0 __lowerCamelCase = 0 os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) with gfile.GFile(switch_checkpoint_path + '''/checkpoint''' , '''rb''' ) as fp: __lowerCamelCase = serialization.msgpack_restore(fp.read() )['''optimizer''']['''target'''] __lowerCamelCase = flatten_dict(UpperCamelCase__ , sep='''/''' ) __lowerCamelCase = {} for layer in checkpoint_info.keys(): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = get_key_and_tensorstore_dict( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if curr_real_layer_name in all_layers: __lowerCamelCase = content else: __lowerCamelCase = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file __lowerCamelCase = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() __lowerCamelCase = torch.tensor(UpperCamelCase__ ) __lowerCamelCase = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts __lowerCamelCase , __lowerCamelCase = rename_base_flax_keys(tuple(key.split('''/''' ) ) , UpperCamelCase__ ) __lowerCamelCase = '''/'''.join(UpperCamelCase__ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: __lowerCamelCase = os.path.join( UpperCamelCase__ , weights_name.replace('''.bin''' , f"""-{len(UpperCamelCase__ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(UpperCamelCase__ , UpperCamelCase__ ) sharded_state_dicts.append(current_block.keys() ) del current_block __lowerCamelCase = {} __lowerCamelCase = 0 __lowerCamelCase = raw_weights.to(getattr(UpperCamelCase__ , UpperCamelCase__ ) ) current_block_size += weight_size total_size += weight_size # Add the last block __lowerCamelCase = os.path.join(UpperCamelCase__ , weights_name.replace('''.bin''' , f"""-{len(UpperCamelCase__ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(UpperCamelCase__ , UpperCamelCase__ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(UpperCamelCase__ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index __lowerCamelCase = {} __lowerCamelCase = {} for idx, shard in enumerate(UpperCamelCase__ ): __lowerCamelCase = weights_name.replace( '''.bin''' , f"""-{idx+1:05d}-of-{len(UpperCamelCase__ ):05d}.bin""" ) # len(sharded_state_dicts):05d} __lowerCamelCase = os.path.join(UpperCamelCase__ , weights_name.replace('''.bin''' , f"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(UpperCamelCase__ , os.path.join(UpperCamelCase__ , UpperCamelCase__ ) ) __lowerCamelCase = shard for key in shard: __lowerCamelCase = shard_file # Add the metadata __lowerCamelCase = {'''total_size''': total_size} __lowerCamelCase = {'''metadata''': metadata, '''weight_map''': weight_map} with open(os.path.join(UpperCamelCase__ , UpperCamelCase__ ) , '''w''' , encoding='''utf-8''' ) as f: __lowerCamelCase = json.dumps(UpperCamelCase__ , indent=2 , sort_keys=UpperCamelCase__ ) + '''\n''' f.write(UpperCamelCase__ ) return metadata, index if __name__ == "__main__": __UpperCAmelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--switch_t5x_checkpoint_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600", type=str, required=False, help="Path to a directory containing a folder per layer. Follows the original Google format.", ) parser.add_argument("--max_shard_size", default="10GB", required=False, help="Max shard size") parser.add_argument("--dtype", default="bfloat16", type=str, required=False, help="dtype of the saved model") parser.add_argument( "--pytorch_dump_folder_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted", type=str, required=False, help="Path to the output pytorch model.", ) __UpperCAmelCase =parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def __lowerCAmelCase ( ) -> List[Any]: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer __lowerCamelCase = SwitchTransformersConfig.from_pretrained('''google/switch-base-8''' ) config.save_pretrained('''/home/arthur_huggingface_co/transformers/switch_converted''' ) __lowerCamelCase = SwitchTransformersForConditionalGeneration.from_pretrained( '''/home/arthur_huggingface_co/transformers/switch_converted''' , device_map='''auto''' ) __lowerCamelCase = TaTokenizer.from_pretrained('''t5-small''' ) __lowerCamelCase = '''A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''' __lowerCamelCase = tokenizer(UpperCamelCase__ , return_tensors='''pt''' ).input_ids __lowerCamelCase = model.generate(UpperCamelCase__ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
67
'''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. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu a__ : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def _UpperCamelCase ( __A , __A=None , __A=None , __A=None ) -> int: '''simple docstring''' UpperCamelCase__ = True while ask_again: UpperCamelCase__ = input(__A ) try: if default is not None and len(__A ) == 0: return default return convert_value(__A ) if convert_value is not None else result except Exception: if error_message is not None: print(__A ) def _UpperCamelCase ( __A , __A=[] , __A=None , __A=0 ) -> Any: '''simple docstring''' UpperCamelCase__ = BulletMenu(__A , __A ) UpperCamelCase__ = menu.run(default_choice=__A ) return convert_value(__A ) if convert_value is not None else result def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value] ) def _UpperCamelCase ( __A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = int(__A ) return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def _UpperCamelCase ( __A ) -> str: '''simple docstring''' UpperCamelCase__ = int(__A ) return PrecisionType(["no", "fp16", "bf16", "fp8"][value] ) def _UpperCamelCase ( __A ) -> Any: '''simple docstring''' UpperCamelCase__ = int(__A ) return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' return {"yes": True, "no": False}[value.lower()] class lowercase_ ( argparse.RawDescriptionHelpFormatter ): def __a ( self , a , a , a , a ): UpperCamelCase__ = super()._format_usage(a , a , a , a ) UpperCamelCase__ = usage.replace("<command> [<args>] " , "" ) return usage
80
0
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> list: '''simple docstring''' A__ = [0] * len(SCREAMING_SNAKE_CASE_ ) for i in range(1 , len(SCREAMING_SNAKE_CASE_ ) ): # use last results for better performance - dynamic programming A__ = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: A__ = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 A__ = j return prefix_result def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> int: '''simple docstring''' return max(prefix_function(SCREAMING_SNAKE_CASE_ ) ) if __name__ == "__main__": import doctest doctest.testmod()
68
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: if resistor <= 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative or zero value!''' raise ValueError(__A ) first_sum += 1 / float(__A ) index += 1 return 1 / first_sum def _UpperCamelCase ( __A ) -> float: '''simple docstring''' UpperCamelCase__ = 0.00 UpperCamelCase__ = 0 for resistor in resistors: sum_r += resistor if resistor < 0: UpperCamelCase__ = F'''Resistor at index {index} has a negative value!''' raise ValueError(__A ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
80
0
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __UpperCamelCase = logging.getLogger(__name__) def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase ) -> Optional[Any]: # save results if os.path.exists(UpperCAmelCase ): if os.path.exists(os.path.join(UpperCAmelCase , 'config.json' ) ) and os.path.isfile( os.path.join(UpperCAmelCase , 'config.json' ) ): os.remove(os.path.join(UpperCAmelCase , 'config.json' ) ) if os.path.exists(os.path.join(UpperCAmelCase , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(UpperCAmelCase , 'pytorch_model.bin' ) ): os.remove(os.path.join(UpperCAmelCase , 'pytorch_model.bin' ) ) else: os.makedirs(UpperCAmelCase ) model.save_pretrained(UpperCAmelCase ) def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase=False ) -> Union[str, Any]: snake_case_ = 2 if unlogit: snake_case_ = torch.pow(UpperCAmelCase , UpperCAmelCase ) snake_case_ = p * torch.log(UpperCAmelCase ) snake_case_ = 0 return -plogp.sum(dim=-1 ) def UpperCAmelCase ( UpperCAmelCase ) -> List[str]: logger.info('lv, h >\t' + '\t'.join(f'{x + 1}' for x in range(len(UpperCAmelCase ) ) ) ) for row in range(len(UpperCAmelCase ) ): if tensor.dtype != torch.long: logger.info(f'layer {row + 1}:\t' + '\t'.join(f'{x:.5f}' for x in tensor[row].cpu().data ) ) else: logger.info(f'layer {row + 1}:\t' + '\t'.join(f'{x:d}' for x in tensor[row].cpu().data ) ) def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=True , UpperCAmelCase=True , UpperCAmelCase=None , UpperCAmelCase=False ) -> Union[str, Any]: snake_case_ , snake_case_ = model.config.num_hidden_layers, model.config.num_attention_heads snake_case_ = torch.zeros(UpperCAmelCase , UpperCAmelCase ).to(args.device ) snake_case_ = torch.zeros(UpperCAmelCase , UpperCAmelCase ).to(args.device ) if head_mask is None: snake_case_ = torch.ones(UpperCAmelCase , UpperCAmelCase ).to(args.device ) head_mask.requires_grad_(requires_grad=UpperCAmelCase ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: snake_case_ = None snake_case_ = 0.0 snake_case_ = 0.0 for step, inputs in enumerate(tqdm(UpperCAmelCase , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): snake_case_ = tuple(t.to(args.device ) for t in inputs ) ((snake_case_) , ) = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) snake_case_ = model(UpperCAmelCase , labels=UpperCAmelCase , head_mask=UpperCAmelCase ) # (loss), lm_logits, presents, (all hidden_states), (attentions) snake_case_ , snake_case_ , snake_case_ = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(UpperCAmelCase ): snake_case_ = entropy(attn.detach() , UpperCAmelCase ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(UpperCAmelCase ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: snake_case_ = 2 snake_case_ = torch.pow(torch.pow(UpperCAmelCase , UpperCAmelCase ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: snake_case_ = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(UpperCAmelCase ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(UpperCAmelCase ) logger.info('Head ranked by importance scores' ) snake_case_ = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) snake_case_ = torch.arange( head_importance.numel() , device=args.device ) snake_case_ = head_ranks.view_as(UpperCAmelCase ) print_ad_tensor(UpperCAmelCase ) return attn_entropy, head_importance, total_loss def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> List[Any]: snake_case_ , snake_case_ , snake_case_ = compute_heads_importance(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , compute_entropy=UpperCAmelCase ) snake_case_ = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , UpperCAmelCase , original_score * args.masking_threshold ) snake_case_ = torch.ones_like(UpperCAmelCase ) snake_case_ = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) snake_case_ = original_score while current_score >= original_score * args.masking_threshold: snake_case_ = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads snake_case_ = float('Inf' ) snake_case_ = head_importance.view(-1 ).sort()[1] if len(UpperCAmelCase ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads snake_case_ = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) snake_case_ = new_head_mask.view(-1 ) snake_case_ = 0.0 snake_case_ = new_head_mask.view_as(UpperCAmelCase ) snake_case_ = new_head_mask.clone().detach() print_ad_tensor(UpperCAmelCase ) # Compute metric and head importance again snake_case_ , snake_case_ , snake_case_ = compute_heads_importance( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , compute_entropy=UpperCAmelCase , head_mask=UpperCAmelCase ) snake_case_ = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , UpperCAmelCase , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info('Final head mask' ) print_ad_tensor(UpperCAmelCase ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Union[str, Any]: snake_case_ = datetime.now() snake_case_ , snake_case_ , snake_case_ = compute_heads_importance( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , compute_entropy=UpperCAmelCase , compute_importance=UpperCAmelCase , head_mask=UpperCAmelCase ) snake_case_ = 1 / loss snake_case_ = datetime.now() - before_time snake_case_ = sum(p.numel() for p in model.parameters() ) snake_case_ = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(UpperCAmelCase ) ) } for k, v in heads_to_prune.items(): if isinstance(UpperCAmelCase , UpperCAmelCase ): snake_case_ = [ v, ] assert sum(len(UpperCAmelCase ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(UpperCAmelCase ) snake_case_ = sum(p.numel() for p in model.parameters() ) snake_case_ = datetime.now() snake_case_ , snake_case_ , snake_case_ = compute_heads_importance( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , compute_entropy=UpperCAmelCase , compute_importance=UpperCAmelCase , head_mask=UpperCAmelCase , actually_pruned=UpperCAmelCase , ) snake_case_ = 1 / loss snake_case_ = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , UpperCAmelCase , UpperCAmelCase , pruned_num_params / original_num_params * 100 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , UpperCAmelCase , UpperCAmelCase ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 100 ) save_model(UpperCAmelCase , args.output_dir ) def UpperCAmelCase ( ) -> List[str]: snake_case_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=UpperCAmelCase , type=UpperCAmelCase , required=UpperCAmelCase , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=UpperCAmelCase , type=UpperCAmelCase , required=UpperCAmelCase , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=UpperCAmelCase , type=UpperCAmelCase , required=UpperCAmelCase , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=UpperCAmelCase , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=UpperCAmelCase , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=UpperCAmelCase , type=UpperCAmelCase , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=UpperCAmelCase , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=UpperCAmelCase , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=UpperCAmelCase , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=UpperCAmelCase , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=128 , type=UpperCAmelCase , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=UpperCAmelCase , help='Batch size.' ) parser.add_argument('--seed' , type=UpperCAmelCase , default=42 ) parser.add_argument('--local_rank' , type=UpperCAmelCase , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=UpperCAmelCase , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=UpperCAmelCase , default='' , help='Can be used for distant debugging.' ) snake_case_ = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=UpperCAmelCase ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: snake_case_ = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) snake_case_ = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) snake_case_ = torch.device('cuda' , args.local_rank ) snake_case_ = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) snake_case_ = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: snake_case_ = nn.parallel.DistributedDataParallel( UpperCAmelCase , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=UpperCAmelCase ) elif args.n_gpu > 1: snake_case_ = nn.DataParallel(UpperCAmelCase ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=UpperCAmelCase ) torch.save(UpperCAmelCase , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , UpperCAmelCase ) # Prepare dataset snake_case_ = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) snake_case_ = (torch.from_numpy(UpperCAmelCase ),) snake_case_ = TensorDataset(*UpperCAmelCase ) snake_case_ = RandomSampler(UpperCAmelCase ) snake_case_ = DataLoader(UpperCAmelCase , sampler=UpperCAmelCase , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: snake_case_ = mask_heads(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) prune_heads(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) if __name__ == "__main__": main()
69
'''simple docstring''' import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class lowercase_ ( enum.Enum ): __UpperCAmelCase = 0 __UpperCAmelCase = 1 __UpperCAmelCase = 2 @add_end_docstrings(a__ ) class lowercase_ ( a__ ): __UpperCAmelCase = '\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n ' def __init__( self , *a , **a ): super().__init__(*a , **a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. UpperCamelCase__ = None if self.model.config.prefix is not None: UpperCamelCase__ = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. UpperCamelCase__ = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._sanitize_parameters(prefix=a , **self._forward_params ) UpperCamelCase__ = {**self._preprocess_params, **preprocess_params} UpperCamelCase__ = {**self._forward_params, **forward_params} def __a ( self , a=None , a=None , a=None , a=None , a=None , a=None , a=None , a=None , **a , ): UpperCamelCase__ = {} if prefix is not None: UpperCamelCase__ = prefix if prefix: UpperCamelCase__ = self.tokenizer( a , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = prefix_inputs["input_ids"].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' " [None, 'hole']" ) UpperCamelCase__ = handle_long_generation preprocess_params.update(a ) UpperCamelCase__ = generate_kwargs UpperCamelCase__ = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("`return_text` is mutually exclusive with `return_full_text`" ) if return_tensors is not None: raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`" ) UpperCamelCase__ = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("`return_text` is mutually exclusive with `return_tensors`" ) UpperCamelCase__ = ReturnType.TENSORS if return_type is not None: UpperCamelCase__ = return_type if clean_up_tokenization_spaces is not None: UpperCamelCase__ = clean_up_tokenization_spaces if stop_sequence is not None: UpperCamelCase__ = self.tokenizer.encode(a , add_special_tokens=a ) if len(a ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) UpperCamelCase__ = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __a ( self , *a , **a ): # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"add_space_before_punct_symbol": True} ) return super()._parse_and_tokenize(*a , **a ) def __call__( self , a , **a ): return super().__call__(a , **a ) def __a ( self , a , a="" , a=None , **a ): UpperCamelCase__ = self.tokenizer( prefix + prompt_text , padding=a , add_special_tokens=a , return_tensors=self.framework ) UpperCamelCase__ = prompt_text if handle_long_generation == "hole": UpperCamelCase__ = inputs["input_ids"].shape[-1] if "max_new_tokens" in generate_kwargs: UpperCamelCase__ = generate_kwargs["max_new_tokens"] else: UpperCamelCase__ = generate_kwargs.get("max_length" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("We cannot infer how many new tokens are expected" ) if cur_len + new_tokens > self.tokenizer.model_max_length: UpperCamelCase__ = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( "We cannot use `hole` to handle this generation the number of desired tokens exceeds the" " models max length" ) UpperCamelCase__ = inputs["input_ids"][:, -keep_length:] if "attention_mask" in inputs: UpperCamelCase__ = inputs["attention_mask"][:, -keep_length:] return inputs def __a ( self , a , **a ): UpperCamelCase__ = model_inputs["input_ids"] UpperCamelCase__ = model_inputs.get("attention_mask" , a ) # Allow empty prompts if input_ids.shape[1] == 0: UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = 1 else: UpperCamelCase__ = input_ids.shape[0] UpperCamelCase__ = model_inputs.pop("prompt_text" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. UpperCamelCase__ = generate_kwargs.pop("prefix_length" , 0 ) if prefix_length > 0: UpperCamelCase__ = "max_new_tokens" in generate_kwargs or ( "generation_config" in generate_kwargs and generate_kwargs["generation_config"].max_new_tokens is not None ) if not has_max_new_tokens: UpperCamelCase__ = generate_kwargs.get("max_length" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length UpperCamelCase__ = "min_new_tokens" in generate_kwargs or ( "generation_config" in generate_kwargs and generate_kwargs["generation_config"].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL UpperCamelCase__ = self.model.generate(input_ids=a , attention_mask=a , **a ) UpperCamelCase__ = generated_sequence.shape[0] if self.framework == "pt": UpperCamelCase__ = generated_sequence.reshape(a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": UpperCamelCase__ = tf.reshape(a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def __a ( self , a , a=ReturnType.FULL_TEXT , a=True ): UpperCamelCase__ = model_outputs["generated_sequence"][0] UpperCamelCase__ = model_outputs["input_ids"] UpperCamelCase__ = model_outputs["prompt_text"] UpperCamelCase__ = generated_sequence.numpy().tolist() UpperCamelCase__ = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: UpperCamelCase__ = {"generated_token_ids": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text UpperCamelCase__ = self.tokenizer.decode( a , skip_special_tokens=a , clean_up_tokenization_spaces=a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: UpperCamelCase__ = 0 else: UpperCamelCase__ = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=a , clean_up_tokenization_spaces=a , ) ) if return_type == ReturnType.FULL_TEXT: UpperCamelCase__ = prompt_text + text[prompt_length:] else: UpperCamelCase__ = text[prompt_length:] UpperCamelCase__ = {"generated_text": all_text} records.append(a ) return records
80
0
'''simple docstring''' from collections.abc import Sequence def UpperCamelCase__ ( lowerCAmelCase = None ): """simple docstring""" if nums is None or not nums: raise ValueError("""Input sequence should not be empty""" ) _lowerCAmelCase = nums[0] for i in range(1 , len(lowerCAmelCase ) ): _lowerCAmelCase = nums[i] _lowerCAmelCase = max(lowerCAmelCase , ans + num , lowerCAmelCase ) return ans if __name__ == "__main__": import doctest doctest.testmod() # Try on a sample input from the user A__ : Optional[Any] =int(input('''Enter number of elements : ''').strip()) A__ : Any =list(map(int, input('''\nEnter the numbers : ''').strip().split()))[:n] print(max_subsequence_sum(array))
70
'''simple docstring''' from ....utils import logging a__ : Optional[Any] = logging.get_logger(__name__) class lowercase_ ( a__ ): def __init__( self , a , a=None , a=20_48 ): UpperCamelCase__ = config.__dict__ UpperCamelCase__ = modal_hidden_size if num_labels: UpperCamelCase__ = num_labels
80
0
def A ( a_ ) -> List[str]: __UpperCamelCase : List[Any] =len(a_ ) __UpperCamelCase : Optional[int] =sum(a_ ) __UpperCamelCase : Optional[int] =[[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 ,n + 1 ): __UpperCamelCase : Dict =True for i in range(1 ,s + 1 ): __UpperCamelCase : List[Any] =False for i in range(1 ,n + 1 ): for j in range(1 ,s + 1 ): __UpperCamelCase : str =dp[i][j - 1] if arr[i - 1] <= j: __UpperCamelCase : Any =dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) ,-1 ,-1 ): if dp[n][j] is True: __UpperCamelCase : List[Any] =s - 2 * j break return diff
71
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent a__ : Tuple = {'UserAgent': UserAgent().random} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' UpperCamelCase__ = script.contents[0] UpperCamelCase__ = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class lowercase_ : def __init__( self , a ): UpperCamelCase__ = f'''https://www.instagram.com/{username}/''' UpperCamelCase__ = self.get_json() def __a ( self ): UpperCamelCase__ = requests.get(self.url , headers=a ).text UpperCamelCase__ = BeautifulSoup(a , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self ): return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self ): return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def __a ( self ): return self.user_data["username"] @property def __a ( self ): return self.user_data["full_name"] @property def __a ( self ): return self.user_data["biography"] @property def __a ( self ): return self.user_data["business_email"] @property def __a ( self ): return self.user_data["external_url"] @property def __a ( self ): return self.user_data["edge_followed_by"]["count"] @property def __a ( self ): return self.user_data["edge_follow"]["count"] @property def __a ( self ): return self.user_data["edge_owner_to_timeline_media"]["count"] @property def __a ( self ): return self.user_data["profile_pic_url_hd"] @property def __a ( self ): return self.user_data["is_verified"] @property def __a ( self ): return self.user_data["is_private"] def _UpperCamelCase ( __A = "github" ) -> None: '''simple docstring''' import os if os.environ.get("CI" ): return # test failing on GitHub Actions UpperCamelCase__ = InstagramUser(__A ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __A ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() a__ : Any = InstagramUser('github') print(instagram_user) print(F"""{instagram_user.number_of_posts = }""") print(F"""{instagram_user.number_of_followers = }""") print(F"""{instagram_user.number_of_followings = }""") print(F"""{instagram_user.email = }""") print(F"""{instagram_user.website = }""") print(F"""{instagram_user.profile_picture_url = }""") print(F"""{instagram_user.is_verified = }""") print(F"""{instagram_user.is_private = }""")
80
0
"""simple docstring""" import os # Precomputes a list of the 100 first triangular numbers lowerCAmelCase__ = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Tuple = os.path.dirname(os.path.realpath(A_ ) ) _lowerCamelCase : Optional[Any] = os.path.join(A_, '''words.txt''' ) _lowerCamelCase : Dict = '''''' with open(A_ ) as f: _lowerCamelCase : Any = f.readline() _lowerCamelCase : List[str] = [word.strip('''"''' ) for word in words.strip('''\r\n''' ).split(''',''' )] _lowerCamelCase : Union[str, Any] = [ word for word in [sum(ord(A_ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(A_ ) if __name__ == "__main__": print(solution())
72
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A , __A , __A ) -> dict[str, float]: '''simple docstring''' if (voltage, current, resistance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if resistance < 0: raise ValueError("Resistance cannot be negative" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
80
0
from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> List[Any]: # noqa: E741 while r - l > 1: __lowerCamelCase : int = (l + r) // 2 if v[m] >= key: __lowerCamelCase : str = m else: __lowerCamelCase : Tuple = m # noqa: E741 return r def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: if len(lowerCamelCase__ ) == 0: return 0 __lowerCamelCase : Union[str, Any] = [0] * len(lowerCamelCase__ ) __lowerCamelCase : Optional[int] = 1 __lowerCamelCase : str = v[0] for i in range(1 , len(lowerCamelCase__ ) ): if v[i] < tail[0]: __lowerCamelCase : Optional[Any] = v[i] elif v[i] > tail[length - 1]: __lowerCamelCase : List[str] = v[i] length += 1 else: __lowerCamelCase : str = v[i] return length if __name__ == "__main__": import doctest doctest.testmod()
73
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Union[str, Any] = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys a__ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
80
0
"""simple docstring""" from __future__ import annotations import math _lowercase = '''2020.9.26''' _lowercase = '''xcodz-dot, cclaus, dhruvmanila''' def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float ): if not all(isinstance(snake_case__ , (float, int) ) for val in locals().values() ): A = F'Input values must either be float or int: {list(locals().values() )}' raise TypeError(snake_case__ ) A = ((x * distance) / (z + distance)) * scale A = ((y * distance) / (z + distance)) * scale return projected_x, projected_y def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : str , snake_case__ : float ): if not isinstance(snake_case__ , snake_case__ ): raise TypeError('Axis must be a str' ) A = locals() del input_variables["axis"] if not all(isinstance(snake_case__ , (float, int) ) for val in input_variables.values() ): A = ( 'Input values except axis must either be float or int: ' F'{list(input_variables.values() )}' ) raise TypeError(snake_case__ ) A = (angle % 360) / 450 * 180 / math.pi if axis == "z": A = x * math.cos(snake_case__ ) - y * math.sin(snake_case__ ) A = y * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = z elif axis == "x": A = y * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + y * math.sin(snake_case__ ) A = x elif axis == "y": A = x * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = y else: raise ValueError('not a valid axis, choose one of \'x\', \'y\', \'z\'' ) return new_x, new_y, new_z if __name__ == "__main__": import doctest doctest.testmod() print(F"""{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }""") print(F"""{rotate(1.0, 2.0, 3.0, 'y', 90.0) = }""")
74
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if len(__A ) != 2 or len(a[0] ) != 2 or len(__A ) != 2 or len(b[0] ) != 2: raise Exception("Matrices are not 2x2" ) UpperCamelCase__ = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _UpperCamelCase ( __A , __A ) -> str: '''simple docstring''' return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__A ) ) ] def _UpperCamelCase ( __A ) -> tuple[list, list, list, list]: '''simple docstring''' if len(__A ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception("Odd matrices are not supported!" ) UpperCamelCase__ = len(__A ) UpperCamelCase__ = matrix_length // 2 UpperCamelCase__ = [[a[i][j] for j in range(__A , __A )] for i in range(__A )] UpperCamelCase__ = [ [a[i][j] for j in range(__A , __A )] for i in range(__A , __A ) ] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A )] UpperCamelCase__ = [[a[i][j] for j in range(__A )] for i in range(__A , __A )] return top_left, top_right, bot_left, bot_right def _UpperCamelCase ( __A ) -> tuple[int, int]: '''simple docstring''' return len(__A ), len(matrix[0] ) def _UpperCamelCase ( __A ) -> None: '''simple docstring''' print("\n".join(str(__A ) for line in matrix ) ) def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A ) == (2, 2): return default_matrix_multiplication(__A , __A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = split_matrix(__A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , __A ) UpperCamelCase__ = actual_strassen(__A , matrix_subtraction(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_addition(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = actual_strassen(matrix_subtraction(__A , __A ) , matrix_addition(__A , __A ) ) UpperCamelCase__ = matrix_addition(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_addition(__A , __A ) UpperCamelCase__ = matrix_subtraction(matrix_subtraction(matrix_addition(__A , __A ) , __A ) , __A ) # construct the new matrix from our 4 quadrants UpperCamelCase__ = [] for i in range(len(__A ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(__A ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _UpperCamelCase ( __A , __A ) -> list: '''simple docstring''' if matrix_dimensions(__A )[1] != matrix_dimensions(__A )[0]: UpperCamelCase__ = ( "Unable to multiply these matrices, please check the dimensions.\n" F'''Matrix A: {matrixa}\n''' F'''Matrix B: {matrixa}''' ) raise Exception(__A ) UpperCamelCase__ = matrix_dimensions(__A ) UpperCamelCase__ = matrix_dimensions(__A ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] UpperCamelCase__ = max(*__A , *__A ) UpperCamelCase__ = int(math.pow(2 , math.ceil(math.loga(__A ) ) ) ) UpperCamelCase__ = matrixa UpperCamelCase__ = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) UpperCamelCase__ = actual_strassen(__A , __A ) # Removing the additional zeros for i in range(0 , __A ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __A ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a__ : int = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a__ : str = [[0, 2, 1, 1], [1_6, 2, 3, 3], [2, 2, 7, 7], [1_3, 1_1, 2_2, 4]] print(strassen(matrixa, matrixa))
80
0
'''simple docstring''' import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __UpperCamelCase ( unittest.TestCase ): @property def lowercase__ ( self ): """simple docstring""" torch.manual_seed(0 ) lowerCamelCase_ =UNetaDModel( block_out_channels=(32, 64), layers_per_block=2, sample_size=32, in_channels=3, out_channels=3, down_block_types=('''DownBlock2D''', '''AttnDownBlock2D'''), up_block_types=('''AttnUpBlock2D''', '''UpBlock2D'''), ) return model def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self.dummy_uncond_unet lowerCamelCase_ =ScoreSdeVeScheduler() lowerCamelCase_ =ScoreSdeVePipeline(unet=lowerCAmelCase, scheduler=lowerCAmelCase ) sde_ve.to(lowerCAmelCase ) sde_ve.set_progress_bar_config(disable=lowerCAmelCase ) lowerCamelCase_ =torch.manual_seed(0 ) lowerCamelCase_ =sde_ve(num_inference_steps=2, output_type='''numpy''', generator=lowerCAmelCase ).images lowerCamelCase_ =torch.manual_seed(0 ) lowerCamelCase_ =sde_ve(num_inference_steps=2, output_type='''numpy''', generator=lowerCAmelCase, return_dict=lowerCAmelCase )[ 0 ] lowerCamelCase_ =image[0, -3:, -3:, -1] lowerCamelCase_ =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCamelCase_ =np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class __UpperCamelCase ( unittest.TestCase ): def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ ='''google/ncsnpp-church-256''' lowerCamelCase_ =UNetaDModel.from_pretrained(lowerCAmelCase ) lowerCamelCase_ =ScoreSdeVeScheduler.from_pretrained(lowerCAmelCase ) lowerCamelCase_ =ScoreSdeVePipeline(unet=lowerCAmelCase, scheduler=lowerCAmelCase ) sde_ve.to(lowerCAmelCase ) sde_ve.set_progress_bar_config(disable=lowerCAmelCase ) lowerCamelCase_ =torch.manual_seed(0 ) lowerCamelCase_ =sde_ve(num_inference_steps=10, output_type='''numpy''', generator=lowerCAmelCase ).images lowerCamelCase_ =image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) lowerCamelCase_ =np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
75
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging a__ : List[str] = logging.get_logger(__name__) if is_vision_available(): import PIL class lowercase_ ( a__ ): __UpperCAmelCase = ['pixel_values'] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = None , a = True , a = 1 / 2_55 , a = True , a = None , a = None , a = True , **a , ): super().__init__(**a ) UpperCamelCase__ = size if size is not None else {"shortest_edge": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a ) UpperCamelCase__ = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24} UpperCamelCase__ = get_size_dict(a , default_to_square=a , param_name="crop_size" ) UpperCamelCase__ = do_resize UpperCamelCase__ = size UpperCamelCase__ = resample UpperCamelCase__ = do_center_crop UpperCamelCase__ = crop_size UpperCamelCase__ = do_rescale UpperCamelCase__ = rescale_factor UpperCamelCase__ = do_normalize UpperCamelCase__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN UpperCamelCase__ = image_std if image_std is not None else OPENAI_CLIP_STD UpperCamelCase__ = do_convert_rgb def __a ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ): UpperCamelCase__ = get_size_dict(a , default_to_square=a ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) UpperCamelCase__ = get_resize_output_image_size(a , size=size["shortest_edge"] , default_to_square=a ) return resize(a , size=a , resample=a , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): UpperCamelCase__ = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(a , size=(size["height"], size["width"]) , data_format=a , **a ) def __a ( self , a , a , a = None , **a , ): return rescale(a , scale=a , data_format=a , **a ) def __a ( self , a , a , a , a = None , **a , ): return normalize(a , mean=a , std=a , data_format=a , **a ) def __a ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ): UpperCamelCase__ = do_resize if do_resize is not None else self.do_resize UpperCamelCase__ = size if size is not None else self.size UpperCamelCase__ = get_size_dict(a , param_name="size" , default_to_square=a ) UpperCamelCase__ = resample if resample is not None else self.resample UpperCamelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase__ = crop_size if crop_size is not None else self.crop_size UpperCamelCase__ = get_size_dict(a , param_name="crop_size" , default_to_square=a ) UpperCamelCase__ = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase__ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase__ = image_mean if image_mean is not None else self.image_mean UpperCamelCase__ = image_std if image_std is not None else self.image_std UpperCamelCase__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase__ = make_list_of_images(a ) if not valid_images(a ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase__ = [convert_to_rgb(a ) for image in images] # All transformations expect numpy arrays. UpperCamelCase__ = [to_numpy_array(a ) for image in images] if do_resize: UpperCamelCase__ = [self.resize(image=a , size=a , resample=a ) for image in images] if do_center_crop: UpperCamelCase__ = [self.center_crop(image=a , size=a ) for image in images] if do_rescale: UpperCamelCase__ = [self.rescale(image=a , scale=a ) for image in images] if do_normalize: UpperCamelCase__ = [self.normalize(image=a , mean=a , std=a ) for image in images] UpperCamelCase__ = [to_channel_dimension_format(a , a ) for image in images] UpperCamelCase__ = {"pixel_values": images} return BatchFeature(data=a , tensor_type=a )
80
0
import json import sys def lowerCamelCase__ ( _a , _a): with open(_a , encoding="utf-8") as f: SCREAMING_SNAKE_CASE : Any = json.load(_a) SCREAMING_SNAKE_CASE : Any = ["<details>", "<summary>Show updated benchmarks!</summary>", " "] for benchmark_name in sorted(_a): SCREAMING_SNAKE_CASE : str = results[benchmark_name] SCREAMING_SNAKE_CASE : Optional[int] = benchmark_name.split("/")[-1] output_md.append(f"### Benchmark: {benchmark_file_name}") SCREAMING_SNAKE_CASE : str = "| metric |" SCREAMING_SNAKE_CASE : str = "|--------|" SCREAMING_SNAKE_CASE : List[Any] = "| new / old (diff) |" for metric_name in sorted(_a): SCREAMING_SNAKE_CASE : Optional[int] = benchmark_res[metric_name] SCREAMING_SNAKE_CASE : Any = metric_vals["new"] SCREAMING_SNAKE_CASE : Optional[Any] = metric_vals.get("old" , _a) SCREAMING_SNAKE_CASE : Optional[Any] = metric_vals.get("diff" , _a) SCREAMING_SNAKE_CASE : int = f" {new_val:f}" if isinstance(_a , (int, float)) else "None" if old_val is not None: val_str += f" / {old_val:f}" if isinstance(_a , (int, float)) else "None" if dif_val is not None: val_str += f" ({dif_val:f})" if isinstance(_a , (int, float)) else "None" title += " " + metric_name + " |" lines += "---|" value += val_str + " |" output_md += [title, lines, value, " "] output_md.append("</details>") with open(_a , "w" , encoding="utf-8") as f: f.writelines("\n".join(_a)) if __name__ == "__main__": a_ = sys.argv[1] a_ = sys.argv[2] format_json_to_md(input_json_file, output_md_file)
76
'''simple docstring''' import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase_ ( a__ , unittest.TestCase ): __UpperCAmelCase = CLIPTokenizer __UpperCAmelCase = CLIPTokenizerFast __UpperCAmelCase = True __UpperCAmelCase = {} __UpperCAmelCase = False def __a ( self ): super().setUp() # fmt: off UpperCamelCase__ = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on UpperCamelCase__ = dict(zip(a , range(len(a ) ) ) ) UpperCamelCase__ = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] UpperCamelCase__ = {"unk_token": "<unk>"} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(a ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(a ) ) def __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def __a ( self , **a ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def __a ( self , a ): UpperCamelCase__ = "lower newer" UpperCamelCase__ = "lower newer" return input_text, output_text def __a ( self ): UpperCamelCase__ = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = "lower newer" UpperCamelCase__ = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] UpperCamelCase__ = tokenizer.tokenize(a ) self.assertListEqual(a , a ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def __a ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = self.tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(a , **a ) UpperCamelCase__ = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways UpperCamelCase__ = "xa\u0303y" + " " + "x\xe3y" UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type UpperCamelCase__ = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type UpperCamelCase__ = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: UpperCamelCase__ = tokenizer_s.tokenize(a ) UpperCamelCase__ = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def __a ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase__ = "hello" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = f'''{text_of_1_token} {text_of_1_token}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) UpperCamelCase__ = f''' {text}''' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) UpperCamelCase__ = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def __a ( self ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def __a ( self ): super().test_tokenization_python_rust_equals() def __a ( self ): # CLIP always lower cases letters pass
80
0
"""simple docstring""" from maths.prime_factors import prime_factors def a_ ( _lowerCAmelCase : int ): '''simple docstring''' if not isinstance(_lowerCAmelCase , _lowerCAmelCase ): lowercase__ : Union[str, Any] = f"""Input value of [number={number}] must be an integer""" raise TypeError(_lowerCAmelCase ) if number < 1: raise ValueError('Input must be a positive integer' ) return -1 if len(prime_factors(_lowerCAmelCase ) ) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
77
'''simple docstring''' import argparse import collections import json import os import re import string import sys import numpy as np a__ : Optional[int] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a__ : int = None def _UpperCamelCase ( ) -> Dict: '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0." ) parser.add_argument("data_file" , metavar="data.json" , help="Input data JSON file." ) parser.add_argument("pred_file" , metavar="pred.json" , help="Model predictions." ) parser.add_argument( "--out-file" , "-o" , metavar="eval.json" , help="Write accuracy metrics to file (default is stdout)." ) parser.add_argument( "--na-prob-file" , "-n" , metavar="na_prob.json" , help="Model estimates of probability of no answer." ) parser.add_argument( "--na-prob-thresh" , "-t" , type=__A , default=1.0 , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)." , ) parser.add_argument( "--out-image-dir" , "-p" , metavar="out_images" , default=__A , help="Save precision-recall curves to directory." ) parser.add_argument("--verbose" , "-v" , action="store_true" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = bool(qa["answers"]["text"] ) return qid_to_has_ans def _UpperCamelCase ( __A ) -> Optional[Any]: '''simple docstring''' def remove_articles(__A ): return ARTICLES_REGEX.sub(" " , __A ) def white_space_fix(__A ): return " ".join(text.split() ) def remove_punc(__A ): UpperCamelCase__ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__A ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__A ) ) ) ) def _UpperCamelCase ( __A ) -> int: '''simple docstring''' if not s: return [] return normalize_answer(__A ).split() def _UpperCamelCase ( __A , __A ) -> List[Any]: '''simple docstring''' return int(normalize_answer(__A ) == normalize_answer(__A ) ) def _UpperCamelCase ( __A , __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = get_tokens(__A ) UpperCamelCase__ = collections.Counter(__A ) & collections.Counter(__A ) UpperCamelCase__ = sum(common.values() ) if len(__A ) == 0 or len(__A ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = 1.0 * num_same / len(__A ) UpperCamelCase__ = (2 * precision * recall) / (precision + recall) return fa def _UpperCamelCase ( __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} UpperCamelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: UpperCamelCase__ = qa["id"] UpperCamelCase__ = [t for t in qa["answers"]["text"] if normalize_answer(__A )] if not gold_answers: # For unanswerable questions, only correct answer is empty string UpperCamelCase__ = [""] if qid not in preds: print(F'''Missing prediction for {qid}''' ) continue UpperCamelCase__ = preds[qid] # Take max over all gold answers UpperCamelCase__ = max(compute_exact(__A , __A ) for a in gold_answers ) UpperCamelCase__ = max(compute_fa(__A , __A ) for a in gold_answers ) return exact_scores, fa_scores def _UpperCamelCase ( __A , __A , __A , __A ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = {} for qid, s in scores.items(): UpperCamelCase__ = na_probs[qid] > na_prob_thresh if pred_na: UpperCamelCase__ = float(not qid_to_has_ans[qid] ) else: UpperCamelCase__ = s return new_scores def _UpperCamelCase ( __A , __A , __A=None ) -> List[Any]: '''simple docstring''' if not qid_list: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores.values() ) / total), ("f1", 100.0 * sum(fa_scores.values() ) / total), ("total", total), ] ) else: UpperCamelCase__ = len(__A ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("f1", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("total", total), ] ) def _UpperCamelCase ( __A , __A , __A ) -> Optional[int]: '''simple docstring''' for k in new_eval: UpperCamelCase__ = new_eval[k] def _UpperCamelCase ( __A , __A , __A , __A ) -> Optional[int]: '''simple docstring''' plt.step(__A , __A , color="b" , alpha=0.2 , where="post" ) plt.fill_between(__A , __A , step="post" , alpha=0.2 , color="b" ) plt.xlabel("Recall" ) plt.ylabel("Precision" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__A ) plt.savefig(__A ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A , __A=None , __A=None ) -> Any: '''simple docstring''' UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) UpperCamelCase__ = 0.0 UpperCamelCase__ = 1.0 UpperCamelCase__ = 0.0 UpperCamelCase__ = [1.0] UpperCamelCase__ = [0.0] UpperCamelCase__ = 0.0 for i, qid in enumerate(__A ): if qid_to_has_ans[qid]: true_pos += scores[qid] UpperCamelCase__ = true_pos / float(i + 1 ) UpperCamelCase__ = true_pos / float(__A ) if i == len(__A ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__A ) recalls.append(__A ) if out_image: plot_pr_curve(__A , __A , __A , __A ) return {"ap": 100.0 * avg_prec} def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if out_image_dir and not os.path.exists(__A ): os.makedirs(__A ) UpperCamelCase__ = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_exact.png" ) , title="Precision-Recall curve for Exact Match score" , ) UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_f1.png" ) , title="Precision-Recall curve for F1 score" , ) UpperCamelCase__ = {k: float(__A ) for k, v in qid_to_has_ans.items()} UpperCamelCase__ = make_precision_recall_eval( __A , __A , __A , __A , out_image=os.path.join(__A , "pr_oracle.png" ) , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)" , ) merge_eval(__A , __A , "pr_exact" ) merge_eval(__A , __A , "pr_f1" ) merge_eval(__A , __A , "pr_oracle" ) def _UpperCamelCase ( __A , __A , __A , __A ) -> List[str]: '''simple docstring''' if not qid_list: return UpperCamelCase__ = [na_probs[k] for k in qid_list] UpperCamelCase__ = np.ones_like(__A ) / float(len(__A ) ) plt.hist(__A , weights=__A , bins=20 , range=(0.0, 1.0) ) plt.xlabel("Model probability of no-answer" ) plt.ylabel("Proportion of dataset" ) plt.title(F'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__A , F'''na_prob_hist_{name}.png''' ) ) plt.clf() def _UpperCamelCase ( __A , __A , __A , __A ) -> Tuple: '''simple docstring''' UpperCamelCase__ = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) UpperCamelCase__ = num_no_ans UpperCamelCase__ = cur_score UpperCamelCase__ = 0.0 UpperCamelCase__ = sorted(__A , key=lambda __A : na_probs[k] ) for i, qid in enumerate(__A ): if qid not in scores: continue if qid_to_has_ans[qid]: UpperCamelCase__ = scores[qid] else: if preds[qid]: UpperCamelCase__ = -1 else: UpperCamelCase__ = 0 cur_score += diff if cur_score > best_score: UpperCamelCase__ = cur_score UpperCamelCase__ = na_probs[qid] return 100.0 * best_score / len(__A ), best_thresh def _UpperCamelCase ( __A , __A , __A , __A , __A , __A ) -> Dict: '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ , UpperCamelCase__ = find_best_thresh(__A , __A , __A , __A ) UpperCamelCase__ = best_exact UpperCamelCase__ = exact_thresh UpperCamelCase__ = best_fa UpperCamelCase__ = fa_thresh def _UpperCamelCase ( ) -> Any: '''simple docstring''' with open(OPTS.data_file ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = dataset_json["data"] with open(OPTS.pred_file ) as f: UpperCamelCase__ = json.load(__A ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: UpperCamelCase__ = json.load(__A ) else: UpperCamelCase__ = {k: 0.0 for k in preds} UpperCamelCase__ = make_qid_to_has_ans(__A ) # maps qid to True/False UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if v] UpperCamelCase__ = [k for k, v in qid_to_has_ans.items() if not v] UpperCamelCase__ , UpperCamelCase__ = get_raw_scores(__A , __A ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = apply_no_ans_threshold(__A , __A , __A , OPTS.na_prob_thresh ) UpperCamelCase__ = make_eval_dict(__A , __A ) if has_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "HasAns" ) if no_ans_qids: UpperCamelCase__ = make_eval_dict(__A , __A , qid_list=__A ) merge_eval(__A , __A , "NoAns" ) if OPTS.na_prob_file: find_all_best_thresh(__A , __A , __A , __A , __A , __A ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__A , __A , __A , __A , __A , OPTS.out_image_dir ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "hasAns" ) histogram_na_prob(__A , __A , OPTS.out_image_dir , "noAns" ) if OPTS.out_file: with open(OPTS.out_file , "w" ) as f: json.dump(__A , __A ) else: print(json.dumps(__A , indent=2 ) ) if __name__ == "__main__": a__ : Optional[int] = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
80
0
"""simple docstring""" from manim import * class A_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def UpperCAmelCase__ ( self :List[Any] ) -> Tuple: UpperCAmelCase = Rectangle(height=0.5 , width=0.5 ) UpperCAmelCase = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) UpperCAmelCase = Rectangle(height=0.25 , width=0.25 ) UpperCAmelCase = [mem.copy() for i in range(6 )] UpperCAmelCase = [mem.copy() for i in range(6 )] UpperCAmelCase = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) UpperCAmelCase = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) UpperCAmelCase = VGroup(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0 ) UpperCAmelCase = Text('CPU' , font_size=24 ) UpperCAmelCase = Group(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0.5 , aligned_edge=lowercase_ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(lowercase_ ) UpperCAmelCase = [mem.copy() for i in range(4 )] UpperCAmelCase = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) UpperCAmelCase = Text('GPU' , font_size=24 ) UpperCAmelCase = Group(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0.5 , aligned_edge=lowercase_ ) gpu.move_to([-1, -1, 0] ) self.add(lowercase_ ) UpperCAmelCase = [mem.copy() for i in range(6 )] UpperCAmelCase = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) UpperCAmelCase = Text('Model' , font_size=24 ) UpperCAmelCase = Group(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0.5 , aligned_edge=lowercase_ ) model.move_to([3, -1.0, 0] ) self.add(lowercase_ ) UpperCAmelCase = [] UpperCAmelCase = [] for i, rect in enumerate(lowercase_ ): UpperCAmelCase = fill.copy().set_fill(lowercase_ , opacity=0.8 ) target.move_to(lowercase_ ) model_arr.append(lowercase_ ) UpperCAmelCase = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(lowercase_ , opacity=0.8 ) cpu_target.move_to(cpu_left_col_base[i] ) model_cpu_arr.append(lowercase_ ) self.add(*lowercase_ , *lowercase_ ) UpperCAmelCase = [meta_mem.copy() for i in range(6 )] UpperCAmelCase = [meta_mem.copy() for i in range(6 )] UpperCAmelCase = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) UpperCAmelCase = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) UpperCAmelCase = VGroup(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0 ) UpperCAmelCase = Text('Disk' , font_size=24 ) UpperCAmelCase = Group(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0.5 , aligned_edge=lowercase_ ) disk.move_to([-4, -1.25, 0] ) self.add(lowercase_ , lowercase_ ) UpperCAmelCase = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) UpperCAmelCase = MarkupText( f"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(lowercase_ , lowercase_ ) UpperCAmelCase = MarkupText( f"""<span fgcolor='{BLUE}'>●</span> Checkpoint""" , font_size=18 , ) blue_text.next_to(lowercase_ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(lowercase_ ) UpperCAmelCase = MarkupText( f"""Now watch as an input is passed through the model\nand how the memory is utilized and handled.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(lowercase_ ) ) UpperCAmelCase = Square(0.3 ) input.set_fill(lowercase_ , opacity=1.0 ) input.set_stroke(width=0.0 ) input.next_to(model_base[0] , lowercase_ , buff=0.5 ) self.play(Write(lowercase_ ) ) input.generate_target() input.target.next_to(model_arr[0] , direction=lowercase_ , buff=0.02 ) self.play(MoveToTarget(lowercase_ ) ) self.play(FadeOut(lowercase_ ) ) UpperCAmelCase = Arrow(start=lowercase_ , end=lowercase_ , color=lowercase_ , buff=0.5 ) a.next_to(model_arr[0].get_left() , lowercase_ , buff=0.2 ) model_cpu_arr[0].generate_target() model_cpu_arr[0].target.move_to(gpu_rect[0] ) UpperCAmelCase = MarkupText( f"""As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(lowercase_ , run_time=3 ) ) UpperCAmelCase = {'run_time': 1, 'fade_in': True, 'fade_out': True, 'buff': 0.02} self.play( Write(lowercase_ ) , Circumscribe(model_arr[0] , color=lowercase_ , **lowercase_ ) , Circumscribe(model_cpu_arr[0] , color=lowercase_ , **lowercase_ ) , Circumscribe(gpu_rect[0] , color=lowercase_ , **lowercase_ ) , ) self.play(MoveToTarget(model_cpu_arr[0] ) ) UpperCAmelCase = a.copy() for i in range(6 ): a_c.next_to(model_arr[i].get_right() + 0.02 , lowercase_ , buff=0.2 ) input.generate_target() input.target.move_to(model_arr[i].get_right() + 0.02 ) UpperCAmelCase = AnimationGroup( FadeOut(lowercase_ , run_time=0.5 ) , MoveToTarget(lowercase_ , run_time=0.5 ) , FadeIn(lowercase_ , run_time=0.5 ) , lag_ratio=0.2 ) self.play(lowercase_ ) model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[i] ) if i < 5: model_cpu_arr[i + 1].generate_target() model_cpu_arr[i + 1].target.move_to(gpu_rect[0] ) if i >= 1: UpperCAmelCase = 0.7 self.play( Circumscribe(model_arr[i] , **lowercase_ ) , Circumscribe(cpu_left_col_base[i] , **lowercase_ ) , Circumscribe(cpu_left_col_base[i + 1] , color=lowercase_ , **lowercase_ ) , Circumscribe(gpu_rect[0] , color=lowercase_ , **lowercase_ ) , Circumscribe(model_arr[i + 1] , color=lowercase_ , **lowercase_ ) , ) if i < 1: self.play( MoveToTarget(model_cpu_arr[i] ) , MoveToTarget(model_cpu_arr[i + 1] ) , ) else: self.play( MoveToTarget(model_cpu_arr[i] , run_time=0.7 ) , MoveToTarget(model_cpu_arr[i + 1] , run_time=0.7 ) , ) else: model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[-1] ) input.generate_target() input.target.next_to(model_arr[-1].get_right() , RIGHT + 0.02 , buff=0.2 ) self.play( Circumscribe(model_arr[-1] , color=lowercase_ , **lowercase_ ) , Circumscribe(cpu_left_col_base[-1] , color=lowercase_ , **lowercase_ ) , Circumscribe(gpu_rect[0] , color=lowercase_ , **lowercase_ ) , ) self.play(MoveToTarget(model_cpu_arr[i] ) ) UpperCAmelCase = a_c UpperCAmelCase = a_c.copy() input.generate_target() input.target.next_to(model_base[-1] , RIGHT + 0.02 , buff=0.5 ) self.play( FadeOut(lowercase_ ) , FadeOut(lowercase_ , run_time=0.5 ) , ) UpperCAmelCase = MarkupText(f"""Inference on a model too large for GPU memory\nis successfully completed.""" , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(lowercase_ , run_time=3 ) , MoveToTarget(lowercase_ ) ) self.wait()
78
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType a__ : Optional[List[str]] = None a__ : Dict = '<' if sys.byteorder == 'little' else '>' # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image a__ : Any = [ np.dtype('|b1'), np.dtype('|u1'), np.dtype('<u2'), np.dtype('>u2'), np.dtype('<i2'), np.dtype('>i2'), np.dtype('<u4'), np.dtype('>u4'), np.dtype('<i4'), np.dtype('>i4'), np.dtype('<f4'), np.dtype('>f4'), np.dtype('<f8'), np.dtype('>f8'), ] @dataclass class lowercase_ : __UpperCAmelCase = True __UpperCAmelCase = None # Automatically constructed __UpperCAmelCase = "PIL.Image.Image" __UpperCAmelCase = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) __UpperCAmelCase = field(default='Image' , init=a__ , repr=a__ ) def __call__( self ): return self.pa_type def __a ( self , a ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if isinstance(a , a ): UpperCamelCase__ = np.array(a ) if isinstance(a , a ): return {"path": value, "bytes": None} elif isinstance(a , a ): return {"path": None, "bytes": value} elif isinstance(a , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(a ) elif isinstance(a , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(a ) elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def __a ( self , a , a=None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Image(decode=True) instead." ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support decoding images, please install 'Pillow'." ) if token_per_repo_id is None: UpperCamelCase__ = {} UpperCamelCase__ , UpperCamelCase__ = value["path"], value["bytes"] if bytes_ is None: if path is None: raise ValueError(f'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) else: if is_local_path(a ): UpperCamelCase__ = PIL.Image.open(a ) else: UpperCamelCase__ = path.split("::" )[-1] try: UpperCamelCase__ = string_to_dict(a , config.HUB_DATASETS_URL )["repo_id"] UpperCamelCase__ = token_per_repo_id.get(a ) except ValueError: UpperCamelCase__ = None with xopen(a , "rb" , use_auth_token=a ) as f: UpperCamelCase__ = BytesIO(f.read() ) UpperCamelCase__ = PIL.Image.open(bytes_ ) else: UpperCamelCase__ = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __a ( self ): from .features import Value return ( self if self.decode else { "bytes": Value("binary" ), "path": Value("string" ), } ) def __a ( self , a ): if pa.types.is_string(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCamelCase__ = storage.field("bytes" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCamelCase__ = storage.field("path" ) else: UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): UpperCamelCase__ = pa.array( [encode_np_array(np.array(a ) )["bytes"] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) UpperCamelCase__ = pa.array([None] * len(a ) , type=pa.string() ) UpperCamelCase__ = pa.StructArray.from_arrays( [bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def __a ( self , a ): @no_op_if_value_is_null def path_to_bytes(a ): with xopen(a , "rb" ) as f: UpperCamelCase__ = f.read() return bytes_ UpperCamelCase__ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCamelCase__ = pa.array( [os.path.basename(a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCamelCase__ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(a , self.pa_type ) def _UpperCamelCase ( ) -> List[str]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() UpperCamelCase__ = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def _UpperCamelCase ( __A ) -> bytes: '''simple docstring''' UpperCamelCase__ = BytesIO() if image.format in list_image_compression_formats(): UpperCamelCase__ = image.format else: UpperCamelCase__ = "PNG" if image.mode in ["1", "L", "LA", "RGB", "RGBA"] else "TIFF" image.save(__A , format=__A ) return buffer.getvalue() def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if hasattr(__A , "filename" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> dict: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) UpperCamelCase__ = array.dtype UpperCamelCase__ = dtype.byteorder if dtype.byteorder != "=" else _NATIVE_BYTEORDER UpperCamelCase__ = dtype.kind UpperCamelCase__ = dtype.itemsize UpperCamelCase__ = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: UpperCamelCase__ = np.dtype("|u1" ) if dtype_kind not in ["u", "i"]: raise TypeError( F'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.''' ) if dtype is not dest_dtype: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: UpperCamelCase__ = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: UpperCamelCase__ = dtype_byteorder + dtype_kind + str(__A ) UpperCamelCase__ = np.dtype(__A ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}''' ) UpperCamelCase__ = PIL.Image.fromarray(array.astype(__A ) ) return {"path": None, "bytes": image_to_bytes(__A )} def _UpperCamelCase ( __A ) -> List[dict]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if objs: UpperCamelCase__ , UpperCamelCase__ = first_non_null_value(__A ) if isinstance(__A , __A ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__A , np.ndarray ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] elif isinstance(__A , PIL.Image.Image ): UpperCamelCase__ = no_op_if_value_is_null(__A ) return [obj_to_image_dict_func(__A ) for obj in objs] else: return objs else: return objs
80
0
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
79
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> int: '''simple docstring''' if depth < 0: raise ValueError("Depth cannot be less than 0" ) if not scores: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) ) def _UpperCamelCase ( ) -> None: '''simple docstring''' UpperCamelCase__ = [90, 23, 6, 33, 21, 65, 123, 34423] UpperCamelCase__ = math.log(len(__A ) , 2 ) print(F'''Optimal value : {minimax(0 , 0 , __A , __A , __A )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
80
0