code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): # Initialise PyTorch model _A : List[Any] = MobileBertConfig.from_json_file(snake_case_ ) print(f'''Building PyTorch model from configuration: {config}''' ) _A : Tuple = MobileBertForPreTraining(snake_case_ ) # Load weights from tf checkpoint _A : Tuple = load_tf_weights_in_mobilebert(snake_case_,snake_case_,snake_case_ ) # Save pytorch-model print(f'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict(),snake_case_ ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--mobilebert_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained MobileBERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) _snake_case = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
343
import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class lowercase ( unittest.TestCase ): @property def a__ ( self ) -> Dict: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def a__ ( self ) -> List[Any]: _A : int = ort.SessionOptions() _A : Any = False return options def a__ ( self ) -> Union[str, Any]: _A : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) _A : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) _A : List[str] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy""" ) # using the PNDM scheduler by default _A : str = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=_a , feature_extractor=_a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_a ) _A : Optional[Any] = """A red cat sitting on a park bench""" _A : Optional[Any] = np.random.RandomState(0 ) _A : Dict = pipe( prompt=_a , image=_a , mask_image=_a , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=_a , output_type="""np""" , ) _A : Optional[int] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1e-2
343
1
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import evaluate import numpy as np import torch from datasets import load_dataset from PIL import Image from torchvision.transforms import ( CenterCrop, Compose, Normalize, RandomHorizontalFlip, RandomResizedCrop, Resize, ToTensor, ) import transformers from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForImageClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version _snake_case = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-classification/requirements.txt") _snake_case = list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys()) _snake_case = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) def lowerCAmelCase_ ( snake_case_ ): with open(snake_case_,"""rb""" ) as f: _A : Tuple = Image.open(snake_case_ ) return im.convert("""RGB""" ) @dataclass class lowercase : _a = field( default=UpperCamelCase__,metadata={ "help": "Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)." },) _a = field( default=UpperCamelCase__,metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) _a = field(default=UpperCamelCase__,metadata={"help": "A folder containing the training data."} ) _a = field(default=UpperCamelCase__,metadata={"help": "A folder containing the validation data."} ) _a = field( default=0.15,metadata={"help": "Percent to split off of train for validation."} ) _a = field( default=UpperCamelCase__,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) },) _a = field( default=UpperCamelCase__,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) },) def a__ ( self ) -> List[Any]: if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None): raise ValueError( """You must specify either a dataset name from the hub or a train and/or validation directory.""" ) @dataclass class lowercase : _a = field( default="google/vit-base-patch16-224-in21k",metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"},) _a = field( default=UpperCamelCase__,metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(UpperCamelCase__ )},) _a = field( default=UpperCamelCase__,metadata={"help": "Pretrained config name or path if not the same as model_name"} ) _a = field( default=UpperCamelCase__,metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} ) _a = field( default="main",metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},) _a = field(default=UpperCamelCase__,metadata={"help": "Name or path of preprocessor config."} ) _a = field( default=UpperCamelCase__,metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) },) _a = field( default=UpperCamelCase__,metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."},) def lowerCAmelCase_ ( snake_case_ ): _A : str = torch.stack([example["""pixel_values"""] for example in examples] ) _A : str = torch.tensor([example["""labels"""] for example in examples] ) return {"pixel_values": pixel_values, "labels": labels} def lowerCAmelCase_ ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. _A : Dict = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _A , _A , _A : Dict = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _A , _A , _A : Dict = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_image_classification""",snake_case_,snake_case_ ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""",datefmt="""%m/%d/%Y %H:%M:%S""",handlers=[logging.StreamHandler(sys.stdout )],) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _A : List[Any] = training_args.get_process_log_level() logger.setLevel(snake_case_ ) transformers.utils.logging.set_verbosity(snake_case_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + f'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(f'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. _A : Dict = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _A : Optional[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Set seed before initializing model. set_seed(training_args.seed ) # Initialize our dataset and prepare it for the 'image-classification' task. if data_args.dataset_name is not None: _A : Optional[int] = load_dataset( data_args.dataset_name,data_args.dataset_config_name,cache_dir=model_args.cache_dir,task="""image-classification""",use_auth_token=True if model_args.use_auth_token else None,) else: _A : Tuple = {} if data_args.train_dir is not None: _A : Any = os.path.join(data_args.train_dir,"""**""" ) if data_args.validation_dir is not None: _A : str = os.path.join(data_args.validation_dir,"""**""" ) _A : List[str] = load_dataset( """imagefolder""",data_files=snake_case_,cache_dir=model_args.cache_dir,task="""image-classification""",) # If we don't have a validation split, split off a percentage of train as validation. _A : Tuple = None if """validation""" in dataset.keys() else data_args.train_val_split if isinstance(data_args.train_val_split,snake_case_ ) and data_args.train_val_split > 0.0: _A : Union[str, Any] = dataset["""train"""].train_test_split(data_args.train_val_split ) _A : List[Any] = split["""train"""] _A : Optional[Any] = split["""test"""] # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. _A : Any = dataset["""train"""].features["""labels"""].names _A , _A : Dict = {}, {} for i, label in enumerate(snake_case_ ): _A : List[str] = str(snake_case_ ) _A : Dict = label # Load the accuracy metric from the datasets package _A : Tuple = evaluate.load("""accuracy""" ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(snake_case_ ): return metric.compute(predictions=np.argmax(p.predictions,axis=1 ),references=p.label_ids ) _A : Any = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path,num_labels=len(snake_case_ ),labelaid=snake_case_,idalabel=snake_case_,finetuning_task="""image-classification""",cache_dir=model_args.cache_dir,revision=model_args.model_revision,use_auth_token=True if model_args.use_auth_token else None,) _A : Union[str, Any] = AutoModelForImageClassification.from_pretrained( model_args.model_name_or_path,from_tf=bool(""".ckpt""" in model_args.model_name_or_path ),config=snake_case_,cache_dir=model_args.cache_dir,revision=model_args.model_revision,use_auth_token=True if model_args.use_auth_token else None,ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,) _A : Union[str, Any] = AutoImageProcessor.from_pretrained( model_args.image_processor_name or model_args.model_name_or_path,cache_dir=model_args.cache_dir,revision=model_args.model_revision,use_auth_token=True if model_args.use_auth_token else None,) # Define torchvision transforms to be applied to each image. if "shortest_edge" in image_processor.size: _A : Optional[int] = image_processor.size["""shortest_edge"""] else: _A : List[str] = (image_processor.size["""height"""], image_processor.size["""width"""]) _A : Optional[Any] = Normalize(mean=image_processor.image_mean,std=image_processor.image_std ) _A : int = Compose( [ RandomResizedCrop(snake_case_ ), RandomHorizontalFlip(), ToTensor(), normalize, ] ) _A : Union[str, Any] = Compose( [ Resize(snake_case_ ), CenterCrop(snake_case_ ), ToTensor(), normalize, ] ) def train_transforms(snake_case_ ): _A : List[Any] = [ _train_transforms(pil_img.convert("""RGB""" ) ) for pil_img in example_batch["""image"""] ] return example_batch def val_transforms(snake_case_ ): _A : Tuple = [_val_transforms(pil_img.convert("""RGB""" ) ) for pil_img in example_batch["""image"""]] return example_batch if training_args.do_train: if "train" not in dataset: raise ValueError("""--do_train requires a train dataset""" ) if data_args.max_train_samples is not None: _A : str = ( dataset["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms dataset["train"].set_transform(snake_case_ ) if training_args.do_eval: if "validation" not in dataset: raise ValueError("""--do_eval requires a validation dataset""" ) if data_args.max_eval_samples is not None: _A : Optional[int] = ( dataset["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms dataset["validation"].set_transform(snake_case_ ) # Initalize our trainer _A : Optional[int] = Trainer( model=snake_case_,args=snake_case_,train_dataset=dataset["""train"""] if training_args.do_train else None,eval_dataset=dataset["""validation"""] if training_args.do_eval else None,compute_metrics=snake_case_,tokenizer=snake_case_,data_collator=snake_case_,) # Training if training_args.do_train: _A : List[str] = None if training_args.resume_from_checkpoint is not None: _A : Any = training_args.resume_from_checkpoint elif last_checkpoint is not None: _A : Optional[Any] = last_checkpoint _A : Any = trainer.train(resume_from_checkpoint=snake_case_ ) trainer.save_model() trainer.log_metrics("""train""",train_result.metrics ) trainer.save_metrics("""train""",train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _A : Optional[int] = trainer.evaluate() trainer.log_metrics("""eval""",snake_case_ ) trainer.save_metrics("""eval""",snake_case_ ) # Write model card and (optionally) push to hub _A : Any = { """finetuned_from""": model_args.model_name_or_path, """tasks""": """image-classification""", """dataset""": data_args.dataset_name, """tags""": ["""image-classification""", """vision"""], } if training_args.push_to_hub: trainer.push_to_hub(**snake_case_ ) else: trainer.create_model_card(**snake_case_ ) if __name__ == "__main__": main()
343
from __future__ import annotations def lowerCAmelCase_ ( snake_case_ ): create_state_space_tree(snake_case_,[],0,[0 for i in range(len(snake_case_ ) )] ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,): if index == len(snake_case_ ): print(snake_case_ ) return for i in range(len(snake_case_ ) ): if not index_used[i]: current_sequence.append(sequence[i] ) _A : Optional[Any] = True create_state_space_tree(snake_case_,snake_case_,index + 1,snake_case_ ) current_sequence.pop() _A : str = False _snake_case = [3, 1, 2, 4] generate_all_permutations(sequence) _snake_case = ["A", "B", "C"] generate_all_permutations(sequence_a)
343
1
from collections.abc import Sequence def lowerCAmelCase_ ( snake_case_ = None ): if nums is None or not nums: raise ValueError("""Input sequence should not be empty""" ) _A : str = nums[0] for i in range(1,len(snake_case_ ) ): _A : List[Any] = nums[i] _A : Optional[Any] = max(snake_case_,ans + num,snake_case_ ) return ans if __name__ == "__main__": import doctest doctest.testmod() # Try on a sample input from the user _snake_case = int(input("Enter number of elements : ").strip()) _snake_case = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n] print(max_subsequence_sum(array))
343
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def lowerCAmelCase_ ( snake_case_ ): _A : Tuple = filter(lambda snake_case_ : p.requires_grad,model.parameters() ) _A : str = sum([np.prod(p.size() ) for p in model_parameters] ) return params _snake_case = logging.getLogger(__name__) def lowerCAmelCase_ ( snake_case_,snake_case_ ): if metric == "rouge2": _A : Optional[int] = """{val_avg_rouge2:.4f}-{step_count}""" elif metric == "bleu": _A : Dict = """{val_avg_bleu:.4f}-{step_count}""" elif metric == "em": _A : List[str] = """{val_avg_em:.4f}-{step_count}""" else: raise NotImplementedError( f'''seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this''' """ function.""" ) _A : Optional[int] = ModelCheckpoint( dirpath=snake_case_,filename=snake_case_,monitor=f'''val_{metric}''',mode="""max""",save_top_k=3,every_n_epochs=1,) return checkpoint_callback def lowerCAmelCase_ ( snake_case_,snake_case_ ): return EarlyStopping( monitor=f'''val_{metric}''',mode="""min""" if """loss""" in metric else """max""",patience=snake_case_,verbose=snake_case_,) class lowercase ( pl.Callback ): def a__ ( self , _a , _a ) -> Optional[Any]: _A : List[Any] = {F'''lr_group_{i}''': param["""lr"""] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(_a ) @rank_zero_only def a__ ( self , _a , _a , _a , _a=True ) -> None: logger.info(F'''***** {type_path} results at step {trainer.global_step:05d} *****''' ) _A : int = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["""log""", """progress_bar""", """preds"""]} ) # Log results _A : Dict = Path(pl_module.hparams.output_dir ) if type_path == "test": _A : List[Any] = od / """test_results.txt""" _A : List[Any] = od / """test_generations.txt""" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _A : Optional[int] = od / F'''{type_path}_results/{trainer.global_step:05d}.txt''' _A : int = od / F'''{type_path}_generations/{trainer.global_step:05d}.txt''' results_file.parent.mkdir(exist_ok=_a ) generations_file.parent.mkdir(exist_ok=_a ) with open(_a , """a+""" ) as writer: for key in sorted(_a ): if key in ["log", "progress_bar", "preds"]: continue _A : List[Any] = metrics[key] if isinstance(_a , torch.Tensor ): _A : str = val.item() _A : str = F'''{key}: {val:.6f}\n''' writer.write(_a ) if not save_generations: return if "preds" in metrics: _A : List[Any] = """\n""".join(metrics["""preds"""] ) generations_file.open("""w+""" ).write(_a ) @rank_zero_only def a__ ( self , _a , _a ) -> str: try: _A : int = pl_module.model.model.num_parameters() except AttributeError: _A : str = pl_module.model.num_parameters() _A : Optional[int] = count_trainable_parameters(_a ) # mp stands for million parameters trainer.logger.log_metrics({"""n_params""": npars, """mp""": npars / 1e6, """grad_mp""": n_trainable_pars / 1e6} ) @rank_zero_only def a__ ( self , _a , _a ) -> Optional[int]: save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_a , _a , """test""" ) @rank_zero_only def a__ ( self , _a , _a ) -> Tuple: save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
343
1
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowercase ( UpperCamelCase__ ): _a = ["image_processor", "tokenizer"] _a = "BlipImageProcessor" _a = ("BertTokenizer", "BertTokenizerFast") def __init__( self , _a , _a ) -> Any: _A : List[Any] = False super().__init__(_a , _a ) _A : Optional[int] = self.image_processor def __call__( self , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ) -> BatchEncoding: if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None: _A : Dict = self.tokenizer _A : Dict = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) return text_encoding # add pixel_values _A : int = self.image_processor(_a , return_tensors=_a ) if text is not None: _A : List[Any] = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) else: _A : int = None if text_encoding is not None: encoding_image_processor.update(_a ) return encoding_image_processor def a__ ( self , *_a , **_a ) -> Any: return self.tokenizer.batch_decode(*_a , **_a ) def a__ ( self , *_a , **_a ) -> List[str]: return self.tokenizer.decode(*_a , **_a ) @property def a__ ( self ) -> Optional[Any]: _A : Any = self.tokenizer.model_input_names _A : List[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
343
from __future__ import annotations from collections.abc import Callable _snake_case = list[list[float | int]] def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : int = len(snake_case_ ) _A : Matrix = [[0 for _ in range(size + 1 )] for _ in range(snake_case_ )] _A : int _A : int _A : int _A : int _A : int _A : float for row in range(snake_case_ ): for col in range(snake_case_ ): _A : Dict = matrix[row][col] _A : List[Any] = vector[row][0] _A : List[Any] = 0 _A : Optional[Any] = 0 while row < size and col < size: # pivoting _A : Any = max((abs(augmented[rowa][col] ), rowa) for rowa in range(snake_case_,snake_case_ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: _A , _A : Optional[Any] = augmented[pivot_row], augmented[row] for rowa in range(row + 1,snake_case_ ): _A : str = augmented[rowa][col] / augmented[row][col] _A : List[Any] = 0 for cola in range(col + 1,size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1,snake_case_ ): for row in range(snake_case_ ): _A : int = augmented[row][col] / augmented[col][col] for cola in range(snake_case_,size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row],10 )] for row in range(snake_case_ ) ] def lowerCAmelCase_ ( snake_case_ ): _A : int = len(snake_case_ ) _A : Matrix = [[0 for _ in range(snake_case_ )] for _ in range(snake_case_ )] _A : Matrix = [[0] for _ in range(snake_case_ )] _A : Matrix _A : int _A : int _A : int for x_val, y_val in enumerate(snake_case_ ): for col in range(snake_case_ ): _A : str = (x_val + 1) ** (size - col - 1) _A : List[str] = y_val _A : Any = solve(snake_case_,snake_case_ ) def interpolated_func(snake_case_ ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(snake_case_ ) ) return interpolated_func def lowerCAmelCase_ ( snake_case_ ): return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def lowerCAmelCase_ ( snake_case_ = question_function,snake_case_ = 10 ): _A : list[int] = [func(snake_case_ ) for x_val in range(1,order + 1 )] _A : list[Callable[[int], int]] = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1,order + 1 ) ] _A : int = 0 _A : Callable[[int], int] _A : int for poly in polynomials: _A : Optional[int] = 1 while func(snake_case_ ) == poly(snake_case_ ): x_val += 1 ret += poly(snake_case_ ) return ret if __name__ == "__main__": print(f"""{solution() = }""")
343
1
import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() _snake_case = logging.get_logger(__name__) set_seed(770) _snake_case = { "c_attn": "att_proj", "c_proj": "out_proj", "c_fc": "in_proj", "transformer.": "", "h.": "layers.", "ln_1": "layernorm_1", "ln_2": "layernorm_2", "ln_f": "layernorm_final", "wpe": "position_embeds_layer", "wte": "input_embeds_layer", } _snake_case = { "text_small": { "repo_id": "suno/bark", "file_name": "text.pt", }, "coarse_small": { "repo_id": "suno/bark", "file_name": "coarse.pt", }, "fine_small": { "repo_id": "suno/bark", "file_name": "fine.pt", }, "text": { "repo_id": "suno/bark", "file_name": "text_2.pt", }, "coarse": { "repo_id": "suno/bark", "file_name": "coarse_2.pt", }, "fine": { "repo_id": "suno/bark", "file_name": "fine_2.pt", }, } _snake_case = os.path.dirname(os.path.abspath(__file__)) _snake_case = os.path.join(os.path.expanduser("~"), ".cache") _snake_case = os.path.join(os.getenv("XDG_CACHE_HOME", default_cache_dir), "suno", "bark_v0") def lowerCAmelCase_ ( snake_case_,snake_case_=False ): _A : List[Any] = model_type if use_small: key += "_small" return os.path.join(snake_case_,REMOTE_MODEL_PATHS[key]["""file_name"""] ) def lowerCAmelCase_ ( snake_case_,snake_case_ ): os.makedirs(snake_case_,exist_ok=snake_case_ ) hf_hub_download(repo_id=snake_case_,filename=snake_case_,local_dir=snake_case_ ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_=False,snake_case_="text" ): if model_type == "text": _A : Union[str, Any] = BarkSemanticModel _A : Any = BarkSemanticConfig _A : str = BarkSemanticGenerationConfig elif model_type == "coarse": _A : Any = BarkCoarseModel _A : List[Any] = BarkCoarseConfig _A : Dict = BarkCoarseGenerationConfig elif model_type == "fine": _A : str = BarkFineModel _A : List[Any] = BarkFineConfig _A : List[str] = BarkFineGenerationConfig else: raise NotImplementedError() _A : Union[str, Any] = f'''{model_type}_small''' if use_small else model_type _A : Union[str, Any] = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(snake_case_ ): logger.info(f'''{model_type} model not found, downloading into `{CACHE_DIR}`.''' ) _download(model_info["""repo_id"""],model_info["""file_name"""] ) _A : Optional[Any] = torch.load(snake_case_,map_location=snake_case_ ) # this is a hack _A : Optional[int] = checkpoint["""model_args"""] if "input_vocab_size" not in model_args: _A : Optional[Any] = model_args["""vocab_size"""] _A : Tuple = model_args["""vocab_size"""] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments _A : Optional[Any] = model_args.pop("""n_head""" ) _A : Optional[Any] = model_args.pop("""n_embd""" ) _A : int = model_args.pop("""n_layer""" ) _A : List[str] = ConfigClass(**checkpoint["""model_args"""] ) _A : str = ModelClass(config=snake_case_ ) _A : Optional[Any] = GenerationConfigClass() _A : Union[str, Any] = model_generation_config _A : Dict = checkpoint["""model"""] # fixup checkpoint _A : Any = """_orig_mod.""" for k, v in list(state_dict.items() ): if k.startswith(snake_case_ ): # replace part of the key with corresponding layer name in HF implementation _A : List[Any] = k[len(snake_case_ ) :] for old_layer_name in new_layer_name_dict: _A : int = new_k.replace(snake_case_,new_layer_name_dict[old_layer_name] ) _A : List[str] = state_dict.pop(snake_case_ ) _A : str = set(state_dict.keys() ) - set(model.state_dict().keys() ) _A : Tuple = {k for k in extra_keys if not k.endswith(""".attn.bias""" )} _A : Any = set(model.state_dict().keys() ) - set(state_dict.keys() ) _A : Dict = {k for k in missing_keys if not k.endswith(""".attn.bias""" )} if len(snake_case_ ) != 0: raise ValueError(f'''extra keys found: {extra_keys}''' ) if len(snake_case_ ) != 0: raise ValueError(f'''missing keys: {missing_keys}''' ) model.load_state_dict(snake_case_,strict=snake_case_ ) _A : Any = model.num_parameters(exclude_embeddings=snake_case_ ) _A : Tuple = checkpoint["""best_val_loss"""].item() logger.info(f'''model loaded: {round(n_params/1e6,1 )}M params, {round(snake_case_,3 )} loss''' ) model.eval() model.to(snake_case_ ) del checkpoint, state_dict return model def lowerCAmelCase_ ( snake_case_,snake_case_=False,snake_case_="text" ): if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() _A : List[str] = """cpu""" # do conversion on cpu _A : Optional[Any] = _get_ckpt_path(snake_case_,use_small=snake_case_ ) _A : List[str] = _load_model(snake_case_,snake_case_,model_type=snake_case_,use_small=snake_case_ ) # load bark initial model _A : Optional[int] = _bark_load_model(snake_case_,"""cpu""",model_type=snake_case_,use_small=snake_case_ ) if model_type == "text": _A : Optional[Any] = bark_model["""model"""] if model.num_parameters(exclude_embeddings=snake_case_ ) != bark_model.get_num_params(): raise ValueError("""initial and new models don't have the same number of parameters""" ) # check if same output as the bark model _A : Tuple = 5 _A : Dict = 10 if model_type in ["text", "coarse"]: _A : Dict = torch.randint(256,(batch_size, sequence_length),dtype=torch.int ) _A : Tuple = bark_model(snake_case_ )[0] _A : int = model(snake_case_ ) # take last logits _A : Dict = output_new_model_total.logits[:, [-1], :] else: _A : Dict = 3 _A : List[Any] = 8 _A : List[Any] = torch.randint(256,(batch_size, sequence_length, n_codes_total),dtype=torch.int ) _A : Tuple = model(snake_case_,snake_case_ ) _A : Optional[int] = bark_model(snake_case_,snake_case_ ) _A : str = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError("""initial and new outputs don't have the same shape""" ) if (output_new_model - output_old_model).abs().max().item() > 1e-3: raise ValueError("""initial and new outputs are not equal""" ) Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) model.save_pretrained(snake_case_ ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_,snake_case_,): _A : Optional[Any] = os.path.join(snake_case_,snake_case_ ) _A : Tuple = BarkSemanticConfig.from_pretrained(os.path.join(snake_case_,"""config.json""" ) ) _A : Dict = BarkCoarseConfig.from_pretrained(os.path.join(snake_case_,"""config.json""" ) ) _A : List[Any] = BarkFineConfig.from_pretrained(os.path.join(snake_case_,"""config.json""" ) ) _A : Tuple = EncodecConfig.from_pretrained("""facebook/encodec_24khz""" ) _A : str = BarkSemanticModel.from_pretrained(snake_case_ ) _A : Any = BarkCoarseModel.from_pretrained(snake_case_ ) _A : List[Any] = BarkFineModel.from_pretrained(snake_case_ ) _A : int = EncodecModel.from_pretrained("""facebook/encodec_24khz""" ) _A : str = BarkConfig.from_sub_model_configs( snake_case_,snake_case_,snake_case_,snake_case_ ) _A : Any = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config,coarseAcoustic.generation_config,fineAcoustic.generation_config ) _A : int = BarkModel(snake_case_ ) _A : Any = semantic _A : Any = coarseAcoustic _A : Optional[int] = fineAcoustic _A : Any = codec _A : Optional[Any] = bark_generation_config Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) bark.save_pretrained(snake_case_,repo_id=snake_case_,push_to_hub=snake_case_ ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument("model_type", type=str, help="text, coarse or fine.") parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--is_small", action="store_true", help="convert the small version instead of the large.") _snake_case = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
343
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup _snake_case = "https://www.indeed.co.in/jobs?q=mobile+app+development&l=" def lowerCAmelCase_ ( snake_case_ = "mumbai" ): _A : Optional[Any] = BeautifulSoup(requests.get(url + location ).content,"""html.parser""" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("""div""",attrs={"""data-tn-component""": """organicJob"""} ): _A : Tuple = job.find("""a""",attrs={"""data-tn-element""": """jobTitle"""} ).text.strip() _A : Optional[int] = job.find("""span""",{"""class""": """company"""} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs("Bangalore"), 1): print(f"""Job {i:>2} is {job[0]} at {job[1]}""")
343
1
def lowerCAmelCase_ ( snake_case_ ): return " ".join( """""".join(word[::-1] ) if len(snake_case_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words("Hey wollef sroirraw"))
343
from __future__ import annotations from decimal import Decimal from numpy import array def lowerCAmelCase_ ( snake_case_ ): _A : Tuple = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(snake_case_ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix _A : List[Any] = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creates a copy of the matrix with swapped positions of the elements _A : Tuple = [[0.0, 0.0], [0.0, 0.0]] _A , _A : List[str] = matrix[1][1], matrix[0][0] _A , _A : List[str] = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(snake_case_ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(snake_case_ ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule _A : List[str] = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creating cofactor matrix _A : List[Any] = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] _A : Union[str, Any] = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) _A : Optional[Any] = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) _A : Any = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) _A : List[Any] = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) _A : int = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) _A : Union[str, Any] = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) _A : Any = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) _A : List[str] = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) _A : Optional[int] = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) _A : List[Any] = array(snake_case_ ) for i in range(3 ): for j in range(3 ): _A : List[str] = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix _A : Union[str, Any] = array(snake_case_ ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(snake_case_ ) # Calculate the inverse of the matrix return [[float(d(snake_case_ ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError("""Please provide a matrix of size 2x2 or 3x3.""" )
343
1
import numpy as np # Importing the Keras libraries and packages import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": # Initialising the CNN # (Sequential- Building the model layer by layer) _snake_case = models.Sequential() # Step 1 - Convolution # Here 64,64 is the length & breadth of dataset images and 3 is for the RGB channel # (3,3) is the kernel size (filter matrix) classifier.add( layers.ConvaD(32, (3, 3), input_shape=(64, 64, 3), activation="relu") ) # Step 2 - Pooling classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Adding a second convolutional layer classifier.add(layers.ConvaD(32, (3, 3), activation="relu")) classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Step 3 - Flattening classifier.add(layers.Flatten()) # Step 4 - Full connection classifier.add(layers.Dense(units=128, activation="relu")) classifier.add(layers.Dense(units=1, activation="sigmoid")) # Compiling the CNN classifier.compile( optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"] ) # Part 2 - Fitting the CNN to the images # Load Trained model weights # from keras.models import load_model # regressor=load_model('cnn.h5') _snake_case = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1.0 / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) _snake_case = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 255) _snake_case = train_datagen.flow_from_directory( "dataset/training_set", target_size=(64, 64), batch_size=32, class_mode="binary" ) _snake_case = test_datagen.flow_from_directory( "dataset/test_set", target_size=(64, 64), batch_size=32, class_mode="binary" ) classifier.fit_generator( training_set, steps_per_epoch=5, epochs=30, validation_data=test_set ) classifier.save("cnn.h5") # Part 3 - Making new predictions _snake_case = tf.keras.preprocessing.image.load_img( "dataset/single_prediction/image.png", target_size=(64, 64) ) _snake_case = tf.keras.preprocessing.image.img_to_array(test_image) _snake_case = np.expand_dims(test_image, axis=0) _snake_case = classifier.predict(test_image) # training_set.class_indices if result[0][0] == 0: _snake_case = "Normal" if result[0][0] == 1: _snake_case = "Abnormality detected"
343
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class lowercase ( UpperCamelCase__ ): _a = 42 class lowercase ( UpperCamelCase__,UpperCamelCase__ ): @register_to_config def __init__( self , _a = 32 , _a = 64 , _a = 20 , _a = 768 , _a=77 , _a=4 , _a = 0.0 , _a = "silu" , _a = None , _a = None , _a = "linear" , _a = "prd" , _a = None , _a = None , _a = None , ) -> Any: super().__init__() _A : int = num_attention_heads _A : Union[str, Any] = attention_head_dim _A : Tuple = num_attention_heads * attention_head_dim _A : Any = additional_embeddings _A : Any = time_embed_dim or inner_dim _A : List[str] = embedding_proj_dim or embedding_dim _A : Optional[int] = clip_embed_dim or embedding_dim _A : Union[str, Any] = Timesteps(_a , _a , 0 ) _A : str = TimestepEmbedding(_a , _a , out_dim=_a , act_fn=_a ) _A : Dict = nn.Linear(_a , _a ) if embedding_proj_norm_type is None: _A : int = None elif embedding_proj_norm_type == "layer": _A : Optional[Any] = nn.LayerNorm(_a ) else: raise ValueError(F'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}''' ) _A : Optional[Any] = nn.Linear(_a , _a ) if encoder_hid_proj_type is None: _A : Union[str, Any] = None elif encoder_hid_proj_type == "linear": _A : Tuple = nn.Linear(_a , _a ) else: raise ValueError(F'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}''' ) _A : List[str] = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , _a ) ) if added_emb_type == "prd": _A : str = nn.Parameter(torch.zeros(1 , 1 , _a ) ) elif added_emb_type is None: _A : Union[str, Any] = None else: raise ValueError( F'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.''' ) _A : int = nn.ModuleList( [ BasicTransformerBlock( _a , _a , _a , dropout=_a , activation_fn="""gelu""" , attention_bias=_a , ) for d in range(_a ) ] ) if norm_in_type == "layer": _A : Union[str, Any] = nn.LayerNorm(_a ) elif norm_in_type is None: _A : Tuple = None else: raise ValueError(F'''Unsupported norm_in_type: {norm_in_type}.''' ) _A : int = nn.LayerNorm(_a ) _A : str = nn.Linear(_a , _a ) _A : Any = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -10000.0 ) causal_attention_mask.triu_(1 ) _A : Optional[int] = causal_attention_mask[None, ...] self.register_buffer("""causal_attention_mask""" , _a , persistent=_a ) _A : Tuple = nn.Parameter(torch.zeros(1 , _a ) ) _A : Dict = nn.Parameter(torch.zeros(1 , _a ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def a__ ( self ) -> Dict[str, AttentionProcessor]: _A : List[str] = {} def fn_recursive_add_processors(_a , _a , _a ): if hasattr(_a , """set_processor""" ): _A : Tuple = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F'''{name}.{sub_name}''' , _a , _a ) return processors for name, module in self.named_children(): fn_recursive_add_processors(_a , _a , _a ) return processors def a__ ( self , _a ) -> List[str]: _A : Optional[int] = len(self.attn_processors.keys() ) if isinstance(_a , _a ) and len(_a ) != count: raise ValueError( F'''A dict of processors was passed, but the number of processors {len(_a )} does not match the''' F''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''' ) def fn_recursive_attn_processor(_a , _a , _a ): if hasattr(_a , """set_processor""" ): if not isinstance(_a , _a ): module.set_processor(_a ) else: module.set_processor(processor.pop(F'''{name}.processor''' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F'''{name}.{sub_name}''' , _a , _a ) for name, module in self.named_children(): fn_recursive_attn_processor(_a , _a , _a ) def a__ ( self ) -> Union[str, Any]: self.set_attn_processor(AttnProcessor() ) def a__ ( self , _a , _a , _a , _a = None , _a = None , _a = True , ) -> Optional[Any]: _A : Tuple = hidden_states.shape[0] _A : List[Any] = timestep if not torch.is_tensor(_a ): _A : Dict = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(_a ) and len(timesteps.shape ) == 0: _A : Tuple = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML _A : Optional[int] = timesteps * torch.ones(_a , dtype=timesteps.dtype , device=timesteps.device ) _A : Dict = self.time_proj(_a ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. _A : Tuple = timesteps_projected.to(dtype=self.dtype ) _A : List[Any] = self.time_embedding(_a ) if self.embedding_proj_norm is not None: _A : Dict = self.embedding_proj_norm(_a ) _A : List[Any] = self.embedding_proj(_a ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: _A : List[Any] = self.encoder_hidden_states_proj(_a ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""" ) _A : Optional[int] = self.proj_in(_a ) _A : Optional[int] = self.positional_embedding.to(hidden_states.dtype ) _A : Union[str, Any] = [] _A : List[str] = 0 if encoder_hidden_states is not None: additional_embeds.append(_a ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: _A : List[str] = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: _A : List[str] = hidden_states[:, None, :] _A : Dict = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: _A : Optional[int] = self.prd_embedding.to(hidden_states.dtype ).expand(_a , -1 , -1 ) additional_embeds.append(_a ) _A : str = torch.cat( _a , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens _A : Dict = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: _A : Union[str, Any] = F.pad( _a , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) _A : Optional[Any] = hidden_states + positional_embeddings if attention_mask is not None: _A : Optional[Any] = (1 - attention_mask.to(hidden_states.dtype )) * -10000.0 _A : List[Any] = F.pad(_a , (0, self.additional_embeddings) , value=0.0 ) _A : Optional[Any] = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) _A : int = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: _A : str = self.norm_in(_a ) for block in self.transformer_blocks: _A : List[Any] = block(_a , attention_mask=_a ) _A : Any = self.norm_out(_a ) if self.prd_embedding is not None: _A : int = hidden_states[:, -1] else: _A : Any = hidden_states[:, additional_embeddings_len:] _A : Union[str, Any] = self.proj_to_clip_embeddings(_a ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=_a ) def a__ ( self , _a ) -> Tuple: _A : List[Any] = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
343
1
import contextlib import copy import random from typing import Any, Dict, Iterable, Optional, Union import numpy as np import torch from .utils import deprecate, is_transformers_available if is_transformers_available(): import transformers def lowerCAmelCase_ ( snake_case_ ): random.seed(snake_case_ ) np.random.seed(snake_case_ ) torch.manual_seed(snake_case_ ) torch.cuda.manual_seed_all(snake_case_ ) # ^^ safe to call this function even if cuda is not available class lowercase : def __init__( self , _a , _a = 0.9999 , _a = 0.0 , _a = 0 , _a = False , _a = 1.0 , _a = 2 / 3 , _a = None , _a = None , **_a , ) -> int: if isinstance(_a , torch.nn.Module ): _A : Any = ( """Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. """ """Please pass the parameters of the module instead.""" ) deprecate( """passing a `torch.nn.Module` to `ExponentialMovingAverage`""" , """1.0.0""" , _a , standard_warn=_a , ) _A : Dict = parameters.parameters() # set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility _A : Tuple = True if kwargs.get("""max_value""" , _a ) is not None: _A : Any = """The `max_value` argument is deprecated. Please use `decay` instead.""" deprecate("""max_value""" , """1.0.0""" , _a , standard_warn=_a ) _A : List[Any] = kwargs["""max_value"""] if kwargs.get("""min_value""" , _a ) is not None: _A : Dict = """The `min_value` argument is deprecated. Please use `min_decay` instead.""" deprecate("""min_value""" , """1.0.0""" , _a , standard_warn=_a ) _A : Tuple = kwargs["""min_value"""] _A : Dict = list(_a ) _A : Union[str, Any] = [p.clone().detach() for p in parameters] if kwargs.get("""device""" , _a ) is not None: _A : List[str] = """The `device` argument is deprecated. Please use `to` instead.""" deprecate("""device""" , """1.0.0""" , _a , standard_warn=_a ) self.to(device=kwargs["""device"""] ) _A : List[str] = None _A : Any = decay _A : Dict = min_decay _A : Union[str, Any] = update_after_step _A : List[Any] = use_ema_warmup _A : Tuple = inv_gamma _A : Dict = power _A : Tuple = 0 _A : Optional[Any] = None # set in `step()` _A : List[Any] = model_cls _A : int = model_config @classmethod def a__ ( cls , _a , _a ) -> "EMAModel": _A , _A : Optional[int] = model_cls.load_config(_a , return_unused_kwargs=_a ) _A : Union[str, Any] = model_cls.from_pretrained(_a ) _A : Tuple = cls(model.parameters() , model_cls=_a , model_config=model.config ) ema_model.load_state_dict(_a ) return ema_model def a__ ( self , _a ) -> Tuple: if self.model_cls is None: raise ValueError("""`save_pretrained` can only be used if `model_cls` was defined at __init__.""" ) if self.model_config is None: raise ValueError("""`save_pretrained` can only be used if `model_config` was defined at __init__.""" ) _A : Any = self.model_cls.from_config(self.model_config ) _A : Tuple = self.state_dict() state_dict.pop("""shadow_params""" , _a ) model.register_to_config(**_a ) self.copy_to(model.parameters() ) model.save_pretrained(_a ) def a__ ( self , _a ) -> float: _A : Optional[int] = max(0 , optimization_step - self.update_after_step - 1 ) if step <= 0: return 0.0 if self.use_ema_warmup: _A : Union[str, Any] = 1 - (1 + step / self.inv_gamma) ** -self.power else: _A : Dict = (1 + step) / (10 + step) _A : Optional[Any] = min(_a , self.decay ) # make sure decay is not smaller than min_decay _A : str = max(_a , self.min_decay ) return cur_decay_value @torch.no_grad() def a__ ( self , _a ) -> str: if isinstance(_a , torch.nn.Module ): _A : List[str] = ( """Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. """ """Please pass the parameters of the module instead.""" ) deprecate( """passing a `torch.nn.Module` to `ExponentialMovingAverage.step`""" , """1.0.0""" , _a , standard_warn=_a , ) _A : str = parameters.parameters() _A : int = list(_a ) self.optimization_step += 1 # Compute the decay factor for the exponential moving average. _A : Union[str, Any] = self.get_decay(self.optimization_step ) _A : List[str] = decay _A : List[Any] = 1 - decay _A : Optional[Any] = contextlib.nullcontext if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): import deepspeed for s_param, param in zip(self.shadow_params , _a ): if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): _A : Optional[Any] = deepspeed.zero.GatheredParameters(_a , modifier_rank=_a ) with context_manager(): if param.requires_grad: s_param.sub_(one_minus_decay * (s_param - param) ) else: s_param.copy_(_a ) def a__ ( self , _a ) -> None: _A : Union[str, Any] = list(_a ) for s_param, param in zip(self.shadow_params , _a ): param.data.copy_(s_param.to(param.device ).data ) def a__ ( self , _a=None , _a=None ) -> None: _A : int = [ p.to(device=_a , dtype=_a ) if p.is_floating_point() else p.to(device=_a ) for p in self.shadow_params ] def a__ ( self ) -> dict: return { "decay": self.decay, "min_decay": self.min_decay, "optimization_step": self.optimization_step, "update_after_step": self.update_after_step, "use_ema_warmup": self.use_ema_warmup, "inv_gamma": self.inv_gamma, "power": self.power, "shadow_params": self.shadow_params, } def a__ ( self , _a ) -> None: _A : str = [param.detach().cpu().clone() for param in parameters] def a__ ( self , _a ) -> None: if self.temp_stored_params is None: raise RuntimeError("""This ExponentialMovingAverage has no `store()`ed weights """ """to `restore()`""" ) for c_param, param in zip(self.temp_stored_params , _a ): param.data.copy_(c_param.data ) # Better memory-wise. _A : List[Any] = None def a__ ( self , _a ) -> None: _A : Optional[Any] = copy.deepcopy(_a ) _A : List[str] = state_dict.get("""decay""" , self.decay ) if self.decay < 0.0 or self.decay > 1.0: raise ValueError("""Decay must be between 0 and 1""" ) _A : Optional[int] = state_dict.get("""min_decay""" , self.min_decay ) if not isinstance(self.min_decay , _a ): raise ValueError("""Invalid min_decay""" ) _A : int = state_dict.get("""optimization_step""" , self.optimization_step ) if not isinstance(self.optimization_step , _a ): raise ValueError("""Invalid optimization_step""" ) _A : str = state_dict.get("""update_after_step""" , self.update_after_step ) if not isinstance(self.update_after_step , _a ): raise ValueError("""Invalid update_after_step""" ) _A : Dict = state_dict.get("""use_ema_warmup""" , self.use_ema_warmup ) if not isinstance(self.use_ema_warmup , _a ): raise ValueError("""Invalid use_ema_warmup""" ) _A : int = state_dict.get("""inv_gamma""" , self.inv_gamma ) if not isinstance(self.inv_gamma , (float, int) ): raise ValueError("""Invalid inv_gamma""" ) _A : List[Any] = state_dict.get("""power""" , self.power ) if not isinstance(self.power , (float, int) ): raise ValueError("""Invalid power""" ) _A : Optional[Any] = state_dict.get("""shadow_params""" , _a ) if shadow_params is not None: _A : str = shadow_params if not isinstance(self.shadow_params , _a ): raise ValueError("""shadow_params must be a list""" ) if not all(isinstance(_a , torch.Tensor ) for p in self.shadow_params ): raise ValueError("""shadow_params must all be Tensors""" )
343
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : Any = None if token is not None: _A : int = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} _A : Any = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' _A : Union[str, Any] = requests.get(snake_case_,headers=snake_case_ ).json() _A : str = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) _A : int = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(snake_case_ ): _A : List[str] = requests.get(url + f'''&page={i + 2}''',headers=snake_case_ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : int = None if token is not None: _A : List[str] = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} _A : str = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100''' _A : Optional[Any] = requests.get(snake_case_,headers=snake_case_ ).json() _A : Any = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) _A : Tuple = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(snake_case_ ): _A : List[Any] = requests.get(url + f'''&page={i + 2}''',headers=snake_case_ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_ ): _A : Dict = None if token is not None: _A : int = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} _A : Tuple = requests.get(snake_case_,headers=snake_case_,allow_redirects=snake_case_ ) _A : Tuple = result.headers["""Location"""] _A : Union[str, Any] = requests.get(snake_case_,allow_redirects=snake_case_ ) _A : Dict = os.path.join(snake_case_,f'''{artifact_name}.zip''' ) with open(snake_case_,"""wb""" ) as fp: fp.write(response.content ) def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : List[str] = [] _A : int = [] _A : Tuple = None with zipfile.ZipFile(snake_case_ ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case_ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(snake_case_ ) as f: for line in f: _A : Any = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs _A : Dict = line[: line.index(""": """ )] _A : Dict = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed _A : List[str] = line[len("""FAILED """ ) :] failed_tests.append(snake_case_ ) elif filename == "job_name.txt": _A : Optional[int] = line if len(snake_case_ ) != len(snake_case_ ): raise ValueError( f'''`errors` and `failed_tests` should have the same number of elements. Got {len(snake_case_ )} for `errors` ''' f'''and {len(snake_case_ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some''' """ problem.""" ) _A : Any = None if job_name and job_links: _A : Dict = job_links.get(snake_case_,snake_case_ ) # A list with elements of the form (line of error, error, failed test) _A : Optional[int] = [x + [y] + [job_link] for x, y in zip(snake_case_,snake_case_ )] return result def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : Dict = [] _A : Optional[int] = [os.path.join(snake_case_,snake_case_ ) for p in os.listdir(snake_case_ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(snake_case_,job_links=snake_case_ ) ) return errors def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : Dict = Counter() counter.update([x[1] for x in logs] ) _A : Tuple = counter.most_common() _A : Tuple = {} for error, count in counts: if error_filter is None or error not in error_filter: _A : str = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} _A : Union[str, Any] = dict(sorted(r.items(),key=lambda snake_case_ : item[1]["count"],reverse=snake_case_ ) ) return r def lowerCAmelCase_ ( snake_case_ ): _A : Union[str, Any] = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): _A : Dict = test.split("""/""" )[2] else: _A : str = None return test def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : str = [(x[0], x[1], get_model(x[2] )) for x in logs] _A : Union[str, Any] = [x for x in logs if x[2] is not None] _A : Optional[Any] = {x[2] for x in logs} _A : List[Any] = {} for test in tests: _A : Any = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) _A : Union[str, Any] = counter.most_common() _A : Any = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} _A : str = sum(error_counts.values() ) if n_errors > 0: _A : Optional[int] = {"""count""": n_errors, """errors""": error_counts} _A : Union[str, Any] = dict(sorted(r.items(),key=lambda snake_case_ : item[1]["count"],reverse=snake_case_ ) ) return r def lowerCAmelCase_ ( snake_case_ ): _A : Optional[int] = """| no. | error | status |""" _A : List[Any] = """|-:|:-|:-|""" _A : List[Any] = [header, sep] for error in reduced_by_error: _A : List[str] = reduced_by_error[error]["""count"""] _A : List[Any] = f'''| {count} | {error[:100]} | |''' lines.append(snake_case_ ) return "\n".join(snake_case_ ) def lowerCAmelCase_ ( snake_case_ ): _A : List[Any] = """| model | no. of errors | major error | count |""" _A : Optional[Any] = """|-:|-:|-:|-:|""" _A : Union[str, Any] = [header, sep] for model in reduced_by_model: _A : Dict = reduced_by_model[model]["""count"""] _A , _A : str = list(reduced_by_model[model]["""errors"""].items() )[0] _A : Union[str, Any] = f'''| {model} | {count} | {error[:60]} | {_count} |''' lines.append(snake_case_ ) return "\n".join(snake_case_ ) if __name__ == "__main__": _snake_case = 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.") _snake_case = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) _snake_case = get_job_links(args.workflow_run_id, token=args.token) _snake_case = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: _snake_case = k.find(" / ") _snake_case = k[index + len(" / ") :] _snake_case = v with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) _snake_case = 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) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) _snake_case = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error _snake_case = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors _snake_case = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) _snake_case = reduce_by_error(errors) _snake_case = reduce_by_model(errors) _snake_case = make_github_table(reduced_by_error) _snake_case = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: fp.write(sa) with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: fp.write(sa)
343
1
import requests _snake_case = "" # <-- Put your OpenWeatherMap appid here! _snake_case = "https://api.openweathermap.org/data/2.5/" def lowerCAmelCase_ ( snake_case_ = "Chicago",snake_case_ = APPID ): return requests.get(URL_BASE + """weather""",params=locals() ).json() def lowerCAmelCase_ ( snake_case_ = "Kolkata, India",snake_case_ = APPID ): return requests.get(URL_BASE + """forecast""",params=locals() ).json() def lowerCAmelCase_ ( snake_case_ = 55.68,snake_case_ = 12.57,snake_case_ = APPID ): return requests.get(URL_BASE + """onecall""",params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: _snake_case = input("Enter a location:").strip() if location: pprint(current_weather(location)) else: break
343
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class lowercase ( unittest.TestCase ): def a__ ( self ) -> List[str]: debug_launcher(test_script.main ) def a__ ( self ) -> Any: debug_launcher(test_ops.main )
343
1
import os from glob import glob import imageio import torch import torchvision import wandb from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan from loaders import load_vqgan from PIL import Image from torch import nn from transformers import CLIPModel, CLIPTokenizerFast from utils import get_device, get_timestamp, show_pil class lowercase : def __init__( self , _a = "cpu" , _a = "openai/clip-vit-large-patch14" ) -> None: _A : Optional[Any] = device _A : str = CLIPTokenizerFast.from_pretrained(_a ) _A : Dict = [0.48145466, 0.4578275, 0.40821073] _A : Optional[Any] = [0.26862954, 0.26130258, 0.27577711] _A : Any = torchvision.transforms.Normalize(self.image_mean , self.image_std ) _A : List[Any] = torchvision.transforms.Resize(224 ) _A : str = torchvision.transforms.CenterCrop(224 ) def a__ ( self , _a ) -> List[Any]: _A : List[str] = self.resize(_a ) _A : Union[str, Any] = self.center_crop(_a ) _A : str = self.normalize(_a ) return images def __call__( self , _a=None , _a=None , **_a ) -> Dict: _A : List[str] = self.tokenizer(text=_a , **_a ) _A : List[str] = self.preprocess_img(_a ) _A : List[Any] = {key: value.to(self.device ) for (key, value) in encoding.items()} return encoding class lowercase ( nn.Module ): def __init__( self , _a=10 , _a=0.01 , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=False , _a=True , _a="image" , _a=True , _a=False , _a=False , _a=False , ) -> None: super().__init__() _A : List[Any] = None _A : str = device if device else get_device() if vqgan: _A : List[Any] = vqgan else: _A : List[str] = load_vqgan(self.device , conf_path=_a , ckpt_path=_a ) self.vqgan.eval() if clip: _A : Optional[int] = clip else: _A : int = CLIPModel.from_pretrained("""openai/clip-vit-base-patch32""" ) self.clip.to(self.device ) _A : int = ProcessorGradientFlow(device=self.device ) _A : int = iterations _A : Dict = lr _A : Any = log _A : Tuple = make_grid _A : Union[str, Any] = return_val _A : str = quantize _A : Optional[Any] = self.vqgan.decoder.z_shape def a__ ( self , _a=None , _a=None , _a=5 , _a=True ) -> Union[str, Any]: _A : Any = [] if output_path is None: _A : Tuple = """./animation.gif""" if input_path is None: _A : List[Any] = self.save_path _A : Union[str, Any] = sorted(glob(input_path + """/*""" ) ) if not len(_a ): raise ValueError( """No images found in save path, aborting (did you pass save_intermediate=True to the generate""" """ function?)""" ) if len(_a ) == 1: print("""Only one image found in save path, (did you pass save_intermediate=True to the generate function?)""" ) _A : Any = total_duration / len(_a ) _A : Optional[int] = [frame_duration] * len(_a ) if extend_frames: _A : Union[str, Any] = 1.5 _A : Dict = 3 for file_name in paths: if file_name.endswith(""".png""" ): images.append(imageio.imread(_a ) ) imageio.mimsave(_a , _a , duration=_a ) print(F'''gif saved to {output_path}''' ) def a__ ( self , _a=None , _a=None ) -> Optional[int]: if not (path or img): raise ValueError("""Input either path or tensor""" ) if img is not None: raise NotImplementedError _A : str = preprocess(Image.open(_a ) , target_image_size=256 ).to(self.device ) _A : Any = preprocess_vqgan(_a ) _A , *_A : Union[str, Any] = self.vqgan.encode(_a ) return z def a__ ( self , _a ) -> Optional[Any]: _A : int = self.latent.detach().requires_grad_() _A : str = base_latent + transform_vector if self.quantize: _A , *_A : Dict = self.vqgan.quantize(_a ) else: _A : int = trans_latent return self.vqgan.decode(_a ) def a__ ( self , _a , _a , _a=None ) -> List[str]: _A : List[Any] = self.clip_preprocessor(text=_a , images=_a , return_tensors="""pt""" , padding=_a ) _A : Tuple = self.clip(**_a ) _A : int = clip_outputs.logits_per_image if weights is not None: _A : Tuple = similarity_logits * weights return similarity_logits.sum() def a__ ( self , _a , _a , _a ) -> str: _A : Optional[int] = self._get_clip_similarity(pos_prompts["""prompts"""] , _a , weights=(1 / pos_prompts["""weights"""]) ) if neg_prompts: _A : List[Any] = self._get_clip_similarity(neg_prompts["""prompts"""] , _a , weights=neg_prompts["""weights"""] ) else: _A : List[str] = torch.tensor([1] , device=self.device ) _A : str = -torch.log(_a ) + torch.log(_a ) return loss def a__ ( self , _a , _a , _a ) -> Dict: _A : int = torch.randn_like(self.latent , requires_grad=_a , device=self.device ) _A : List[Any] = torch.optim.Adam([vector] , lr=self.lr ) for i in range(self.iterations ): optim.zero_grad() _A : Tuple = self._add_vector(_a ) _A : int = loop_post_process(_a ) _A : Dict = self._get_CLIP_loss(_a , _a , _a ) print("""CLIP loss""" , _a ) if self.log: wandb.log({"""CLIP Loss""": clip_loss} ) clip_loss.backward(retain_graph=_a ) optim.step() if self.return_val == "image": yield custom_to_pil(transformed_img[0] ) else: yield vector def a__ ( self , _a , _a , _a ) -> int: wandb.init(reinit=_a , project="""face-editor""" ) wandb.config.update({"""Positive Prompts""": positive_prompts} ) wandb.config.update({"""Negative Prompts""": negative_prompts} ) wandb.config.update({"""lr""": self.lr, """iterations""": self.iterations} ) if image_path: _A : Optional[int] = Image.open(_a ) _A : Tuple = image.resize((256, 256) ) wandb.log("""Original Image""" , wandb.Image(_a ) ) def a__ ( self , _a ) -> Union[str, Any]: if not prompts: return [] _A : List[str] = [] _A : Optional[int] = [] if isinstance(_a , _a ): _A : Optional[Any] = [prompt.strip() for prompt in prompts.split("""|""" )] for prompt in prompts: if isinstance(_a , (tuple, list) ): _A : List[str] = prompt[0] _A : int = float(prompt[1] ) elif ":" in prompt: _A , _A : Optional[int] = prompt.split(""":""" ) _A : Any = float(_a ) else: _A : Any = prompt _A : Tuple = 1.0 processed_prompts.append(_a ) weights.append(_a ) return { "prompts": processed_prompts, "weights": torch.tensor(_a , device=self.device ), } def a__ ( self , _a , _a=None , _a=None , _a=True , _a=False , _a=True , _a=True , _a=None , ) -> List[Any]: if image_path: _A : List[str] = self._get_latent(_a ) else: _A : Optional[int] = torch.randn(self.latent_dim , device=self.device ) if self.log: self._init_logging(_a , _a , _a ) assert pos_prompts, "You must provide at least one positive prompt." _A : Optional[Any] = self.process_prompts(_a ) _A : Tuple = self.process_prompts(_a ) if save_final and save_path is None: _A : List[str] = os.path.join("""./outputs/""" , """_""".join(pos_prompts["""prompts"""] ) ) if not os.path.exists(_a ): os.makedirs(_a ) else: _A : Optional[int] = save_path + """_""" + get_timestamp() os.makedirs(_a ) _A : Any = save_path _A : Any = self.vqgan.decode(self.latent )[0] if show_intermediate: print("""Original Image""" ) show_pil(custom_to_pil(_a ) ) _A : Dict = loop_post_process(_a ) for iter, transformed_img in enumerate(self._optimize_CLIP(_a , _a , _a ) ): if show_intermediate: show_pil(_a ) if save_intermediate: transformed_img.save(os.path.join(self.save_path , F'''iter_{iter:03d}.png''' ) ) if self.log: wandb.log({"""Image""": wandb.Image(_a )} ) if show_final: show_pil(_a ) if save_final: transformed_img.save(os.path.join(self.save_path , F'''iter_{iter:03d}_final.png''' ) )
343
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _snake_case = logging.get_logger(__name__) _snake_case = { "microsoft/resnet-50": "https://huggingface.co/microsoft/resnet-50/blob/main/config.json", } class lowercase ( UpperCamelCase__,UpperCamelCase__ ): _a = "resnet" _a = ["basic", "bottleneck"] def __init__( self , _a=3 , _a=64 , _a=[256, 512, 1024, 2048] , _a=[3, 4, 6, 3] , _a="bottleneck" , _a="relu" , _a=False , _a=None , _a=None , **_a , ) -> int: super().__init__(**_a ) if layer_type not in self.layer_types: raise ValueError(F'''layer_type={layer_type} is not one of {",".join(self.layer_types )}''' ) _A : Optional[Any] = num_channels _A : List[Any] = embedding_size _A : int = hidden_sizes _A : Union[str, Any] = depths _A : Optional[int] = layer_type _A : Any = hidden_act _A : List[Any] = downsample_in_first_stage _A : int = ["""stem"""] + [F'''stage{idx}''' for idx in range(1 , len(_a ) + 1 )] _A , _A : str = get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names ) class lowercase ( UpperCamelCase__ ): _a = version.parse("1.11" ) @property def a__ ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def a__ ( self ) -> float: return 1e-3
343
1
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup _snake_case = "https://www.indeed.co.in/jobs?q=mobile+app+development&l=" def lowerCAmelCase_ ( snake_case_ = "mumbai" ): _A : Optional[Any] = BeautifulSoup(requests.get(url + location ).content,"""html.parser""" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("""div""",attrs={"""data-tn-component""": """organicJob"""} ): _A : Tuple = job.find("""a""",attrs={"""data-tn-element""": """jobTitle"""} ).text.strip() _A : Optional[int] = job.find("""span""",{"""class""": """company"""} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs("Bangalore"), 1): print(f"""Job {i:>2} is {job[0]} at {job[1]}""")
343
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowerCAmelCase_ ( snake_case_,snake_case_ ): # Load checkpoint _A : Optional[int] = torch.load(snake_case_,map_location="""cpu""" ) _A : Any = chkpt["""model"""] # We have the base model one level deeper than the original XLM repository _A : Any = {} for k, v in state_dict.items(): if "pred_layer" in k: _A : Tuple = v else: _A : Dict = v _A : Optional[Any] = chkpt["""params"""] _A : Union[str, Any] = {n: v for n, v in config.items() if not isinstance(snake_case_,(torch.FloatTensor, numpy.ndarray) )} _A : str = chkpt["""dico_word2id"""] _A : Optional[Any] = {s + """</w>""" if s.find("""@@""" ) == -1 and i > 13 else s.replace("""@@""","""""" ): i for s, i in vocab.items()} # Save pytorch-model _A : Dict = pytorch_dump_folder_path + """/""" + WEIGHTS_NAME _A : Any = pytorch_dump_folder_path + """/""" + CONFIG_NAME _A : Optional[int] = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""vocab_file"""] print(f'''Save PyTorch model to {pytorch_weights_dump_path}''' ) torch.save(snake_case_,snake_case_ ) print(f'''Save configuration file to {pytorch_config_dump_path}''' ) with open(snake_case_,"""w""",encoding="""utf-8""" ) as f: f.write(json.dumps(snake_case_,indent=2 ) + """\n""" ) print(f'''Save vocab file to {pytorch_config_dump_path}''' ) with open(snake_case_,"""w""",encoding="""utf-8""" ) as f: f.write(json.dumps(snake_case_,indent=2 ) + """\n""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( "--xlm_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) _snake_case = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
343
1
def lowerCAmelCase_ ( snake_case_ ): return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
343
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowercase ( UpperCamelCase__ ): _a = ["image_processor", "tokenizer"] _a = "BlipImageProcessor" _a = ("BertTokenizer", "BertTokenizerFast") def __init__( self , _a , _a ) -> Any: _A : List[Any] = False super().__init__(_a , _a ) _A : Optional[int] = self.image_processor def __call__( self , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ) -> BatchEncoding: if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None: _A : Dict = self.tokenizer _A : Dict = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) return text_encoding # add pixel_values _A : int = self.image_processor(_a , return_tensors=_a ) if text is not None: _A : List[Any] = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) else: _A : int = None if text_encoding is not None: encoding_image_processor.update(_a ) return encoding_image_processor def a__ ( self , *_a , **_a ) -> Any: return self.tokenizer.batch_decode(*_a , **_a ) def a__ ( self , *_a , **_a ) -> List[str]: return self.tokenizer.decode(*_a , **_a ) @property def a__ ( self ) -> Optional[Any]: _A : Any = self.tokenizer.model_input_names _A : List[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
343
1
def lowerCAmelCase_ ( snake_case_,snake_case_ ): return number | (1 << position) def lowerCAmelCase_ ( snake_case_,snake_case_ ): return number & ~(1 << position) def lowerCAmelCase_ ( snake_case_,snake_case_ ): return number ^ (1 << position) def lowerCAmelCase_ ( snake_case_,snake_case_ ): return ((number >> position) & 1) == 1 def lowerCAmelCase_ ( snake_case_,snake_case_ ): return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
343
from random import randint from tempfile import TemporaryFile import numpy as np def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : Tuple = 0 if start < end: _A : Tuple = randint(snake_case_,snake_case_ ) _A : Any = a[end] _A : int = a[pivot] _A : int = temp _A , _A : List[Any] = _in_place_partition(snake_case_,snake_case_,snake_case_ ) count += _in_place_quick_sort(snake_case_,snake_case_,p - 1 ) count += _in_place_quick_sort(snake_case_,p + 1,snake_case_ ) return count def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : str = 0 _A : List[str] = randint(snake_case_,snake_case_ ) _A : Union[str, Any] = a[end] _A : List[str] = a[pivot] _A : List[Any] = temp _A : List[str] = start - 1 for index in range(snake_case_,snake_case_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value _A : Union[str, Any] = new_pivot_index + 1 _A : List[Any] = a[new_pivot_index] _A : Optional[int] = a[index] _A : List[Any] = temp _A : Optional[Any] = a[new_pivot_index + 1] _A : Any = a[end] _A : Dict = temp return new_pivot_index + 1, count _snake_case = TemporaryFile() _snake_case = 100 # 1000 elements are to be sorted _snake_case , _snake_case = 0, 1 # mean and standard deviation _snake_case = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array _snake_case = np.load(outfile) _snake_case = len(M) - 1 _snake_case = _in_place_quick_sort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
343
1
def lowerCAmelCase_ ( snake_case_ ): _A : List[str] = [0] * len(snake_case_ ) for i in range(1,len(snake_case_ ) ): # use last results for better performance - dynamic programming _A : Union[str, Any] = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: _A : Union[str, Any] = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 _A : int = j return prefix_result def lowerCAmelCase_ ( snake_case_ ): return max(prefix_function(snake_case_ ) ) if __name__ == "__main__": import doctest doctest.testmod()
343
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { "MIT/ast-finetuned-audioset-10-10-0.4593": ( "https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json" ), } class lowercase ( UpperCamelCase__ ): _a = "audio-spectrogram-transformer" def __init__( self , _a=768 , _a=12 , _a=12 , _a=3072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1e-12 , _a=16 , _a=True , _a=10 , _a=10 , _a=1024 , _a=128 , **_a , ) -> List[Any]: super().__init__(**_a ) _A : Any = hidden_size _A : Tuple = num_hidden_layers _A : List[str] = num_attention_heads _A : Any = intermediate_size _A : Optional[Any] = hidden_act _A : Optional[Any] = hidden_dropout_prob _A : Any = attention_probs_dropout_prob _A : Optional[Any] = initializer_range _A : Optional[Any] = layer_norm_eps _A : str = patch_size _A : Tuple = qkv_bias _A : Dict = frequency_stride _A : Union[str, Any] = time_stride _A : Any = max_length _A : Tuple = num_mel_bins
343
1
import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart import shift_tokens_right from transformers.testing_utils import TestCasePlus, slow from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset _snake_case = "bert-base-cased" _snake_case = "google/pegasus-xsum" _snake_case = [" Sam ate lunch today.", "Sams lunch ingredients."] _snake_case = ["A very interesting story about what I ate for lunch.", "Avocado, celery, turkey, coffee"] _snake_case = "patrickvonplaten/t5-tiny-random" _snake_case = "sshleifer/bart-tiny-random" _snake_case = "sshleifer/tiny-mbart" _snake_case = "sshleifer/tiny-marian-en-de" def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : Union[str, Any] = """\n""".join(snake_case_ ) Path(snake_case_ ).open("""w""" ).writelines(snake_case_ ) def lowerCAmelCase_ ( snake_case_ ): for split in ["train", "val", "test"]: _dump_articles(os.path.join(snake_case_,f'''{split}.source''' ),snake_case_ ) _dump_articles(os.path.join(snake_case_,f'''{split}.target''' ),snake_case_ ) return tmp_dir class lowercase ( UpperCamelCase__ ): @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def a__ ( self , _a ) -> str: _A : List[str] = AutoTokenizer.from_pretrained(_a ) _A : Dict = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) _A : int = max(len(tokenizer.encode(_a ) ) for a in ARTICLES ) _A : Any = max(len(tokenizer.encode(_a ) ) for a in SUMMARIES ) _A : Optional[int] = 4 _A : Union[str, Any] = 8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated _A , _A : List[str] = """ro_RO""", """de_DE""" # ignored for all but mbart, but never causes error. _A : Union[str, Any] = SeqaSeqDataset( _a , data_dir=_a , type_path="""train""" , max_source_length=_a , max_target_length=_a , src_lang=_a , tgt_lang=_a , ) _A : int = DataLoader(_a , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert isinstance(_a , _a ) assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_src_len # show that targets are the same len assert batch["labels"].shape[1] == max_tgt_len if tok_name != MBART_TINY: continue # check language codes in correct place _A : List[Any] = shift_tokens_right(batch["""labels"""] , tokenizer.pad_token_id ) assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang] assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang] break # No need to test every batch @parameterized.expand([BART_TINY, BERT_BASE_CASED] ) def a__ ( self , _a ) -> List[Any]: _A : int = AutoTokenizer.from_pretrained(_a ) _A : Optional[int] = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) _A : int = max(len(tokenizer.encode(_a ) ) for a in ARTICLES ) _A : Optional[int] = max(len(tokenizer.encode(_a ) ) for a in SUMMARIES ) _A : Any = 4 _A : Optional[int] = LegacySeqaSeqDataset( _a , data_dir=_a , type_path="""train""" , max_source_length=20 , max_target_length=_a , ) _A : str = DataLoader(_a , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_len_source assert 20 >= batch["input_ids"].shape[1] # trimmed significantly # show that targets were truncated assert batch["labels"].shape[1] == trunc_target # Truncated assert max_len_target > trunc_target # Truncated break # No need to test every batch def a__ ( self ) -> Optional[Any]: _A : Union[str, Any] = AutoTokenizer.from_pretrained("""facebook/mbart-large-cc25""" ) _A : Dict = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) _A : str = tmp_dir.joinpath("""train.source""" ).open().readlines() _A : Optional[Any] = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) pack_data_dir(_a , _a , 128 , _a ) _A : int = {x.name for x in tmp_dir.iterdir()} _A : Optional[int] = {x.name for x in save_dir.iterdir()} _A : Tuple = save_dir.joinpath("""train.source""" ).open().readlines() # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.'] # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.'] assert len(_a ) < len(_a ) assert len(_a ) == 1 assert len(packed_examples[0] ) == sum(len(_a ) for x in orig_examples ) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason="""This test requires fairseq""" ) def a__ ( self ) -> int: if not FAIRSEQ_AVAILABLE: return _A , _A , _A : Dict = self._get_dataset(max_len=64 ) _A : Tuple = 64 _A : int = ds.make_dynamic_sampler(_a , required_batch_size_multiple=_a ) _A : List[str] = [len(_a ) for x in batch_sampler] assert len(set(_a ) ) > 1 # it's not dynamic batch size if every batch is the same length assert sum(_a ) == len(_a ) # no dropped or added examples _A : Union[str, Any] = DataLoader(_a , batch_sampler=_a , collate_fn=ds.collate_fn , num_workers=2 ) _A : Optional[int] = [] _A : Any = [] for batch in data_loader: _A : Tuple = batch["""input_ids"""].shape _A : Dict = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple _A : Dict = np.product(batch["""input_ids"""].shape ) num_src_per_batch.append(_a ) if num_src_tokens > (max_tokens * 1.1): failures.append(_a ) assert num_src_per_batch[0] == max(_a ) if failures: raise AssertionError(F'''too many tokens in {len(_a )} batches''' ) def a__ ( self ) -> str: _A , _A , _A : Any = self._get_dataset(max_len=512 ) _A : Union[str, Any] = 2 _A : List[str] = ds.make_sortish_sampler(_a , shuffle=_a ) _A : Optional[int] = DataLoader(_a , batch_size=_a , collate_fn=ds.collate_fn , num_workers=2 ) _A : Dict = DataLoader(_a , batch_size=_a , collate_fn=ds.collate_fn , num_workers=2 , sampler=_a ) _A : Any = tokenizer.pad_token_id def count_pad_tokens(_a , _a="input_ids" ): return [batch[k].eq(_a ).sum().item() for batch in data_loader] assert sum(count_pad_tokens(_a , k="""labels""" ) ) < sum(count_pad_tokens(_a , k="""labels""" ) ) assert sum(count_pad_tokens(_a ) ) < sum(count_pad_tokens(_a ) ) assert len(_a ) == len(_a ) def a__ ( self , _a=1000 , _a=128 ) -> str: if os.getenv("""USE_REAL_DATA""" , _a ): _A : Any = """examples/seq2seq/wmt_en_ro""" _A : List[str] = max_len * 2 * 64 if not Path(_a ).joinpath("""train.len""" ).exists(): save_len_file(_a , _a ) else: _A : int = """examples/seq2seq/test_data/wmt_en_ro""" _A : Union[str, Any] = max_len * 4 save_len_file(_a , _a ) _A : Tuple = AutoTokenizer.from_pretrained(_a ) _A : List[str] = SeqaSeqDataset( _a , data_dir=_a , type_path="""train""" , max_source_length=_a , max_target_length=_a , n_obs=_a , ) return ds, max_tokens, tokenizer def a__ ( self ) -> Tuple: _A , _A , _A : Optional[int] = self._get_dataset() _A : Optional[Any] = set(DistributedSortishSampler(_a , 256 , num_replicas=2 , rank=0 , add_extra_examples=_a ) ) _A : Any = set(DistributedSortishSampler(_a , 256 , num_replicas=2 , rank=1 , add_extra_examples=_a ) ) assert idsa.intersection(_a ) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def a__ ( self , _a ) -> List[str]: _A : Optional[int] = AutoTokenizer.from_pretrained(_a , use_fast=_a ) if tok_name == MBART_TINY: _A : Union[str, Any] = SeqaSeqDataset( _a , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="""train""" , max_source_length=4 , max_target_length=8 , src_lang="""EN""" , tgt_lang="""FR""" , ) _A : Tuple = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: _A : int = SeqaSeqDataset( _a , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="""train""" , max_source_length=4 , max_target_length=8 , ) _A : Tuple = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(_a ) == 1 if tok_name == BART_TINY else len(_a ) == 0
343
import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) _snake_case = logging.getLogger() def lowerCAmelCase_ ( ): _A : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""-f""" ) _A : Optional[Any] = parser.parse_args() return args.f class lowercase ( UpperCamelCase__ ): def a__ ( self ) -> None: _A : List[Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(_a ) def a__ ( self , _a ) -> Dict: _A : Tuple = get_gpu_count() if n_gpu > 1: pass # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560 # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py" # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split() # cmd = [sys.executable] + distributed_args + args # execute_subprocess_async(cmd, env=self.get_env()) # XXX: test the results - need to save them first into .json file else: args.insert(0 , """run_glue_deebert.py""" ) with patch.object(_a , """argv""" , _a ): _A : Optional[Any] = run_glue_deebert.main() for value in result.values(): self.assertGreaterEqual(_a , 0.666 ) @slow @require_torch_non_multi_gpu def a__ ( self ) -> Optional[int]: _A : Tuple = """ --model_type roberta --model_name_or_path roberta-base --task_name MRPC --do_train --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --max_seq_length 128 --per_gpu_eval_batch_size=1 --per_gpu_train_batch_size=8 --learning_rate 2e-4 --num_train_epochs 3 --overwrite_output_dir --seed 42 --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --save_steps 0 --overwrite_cache --eval_after_first_stage """.split() self.run_and_check(_a ) _A : Optional[Any] = """ --model_type roberta --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --task_name MRPC --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --max_seq_length 128 --eval_each_highway --eval_highway --overwrite_cache --per_gpu_eval_batch_size=1 """.split() self.run_and_check(_a ) _A : List[str] = """ --model_type roberta --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --task_name MRPC --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --max_seq_length 128 --early_exit_entropy 0.1 --eval_highway --overwrite_cache --per_gpu_eval_batch_size=1 """.split() self.run_and_check(_a )
343
1
from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cached_property, is_tf_available, is_vision_available from transformers.testing_utils import require_tf, require_vision, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTMAEForPreTraining, TFViTMAEModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowercase : def __init__( self , _a , _a=13 , _a=30 , _a=2 , _a=3 , _a=True , _a=True , _a=32 , _a=2 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=10 , _a=0.02 , _a=3 , _a=0.6 , _a=None , ) -> Any: _A : List[Any] = parent _A : Dict = batch_size _A : Optional[int] = image_size _A : Optional[int] = patch_size _A : Dict = num_channels _A : Dict = is_training _A : Union[str, Any] = use_labels _A : Union[str, Any] = hidden_size _A : str = num_hidden_layers _A : Tuple = num_attention_heads _A : Optional[Any] = intermediate_size _A : Optional[int] = hidden_act _A : Union[str, Any] = hidden_dropout_prob _A : List[str] = attention_probs_dropout_prob _A : Any = type_sequence_label_size _A : Optional[Any] = initializer_range _A : List[Any] = mask_ratio _A : str = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) _A : List[Any] = (image_size // patch_size) ** 2 _A : List[str] = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def a__ ( self ) -> Any: _A : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A : Optional[int] = None if self.use_labels: _A : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _A : int = self.get_config() return config, pixel_values, labels def a__ ( self ) -> List[Any]: return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , decoder_hidden_size=self.hidden_size , decoder_num_hidden_layers=self.num_hidden_layers , decoder_num_attention_heads=self.num_attention_heads , decoder_intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_a , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def a__ ( self , _a , _a , _a ) -> Tuple: _A : Optional[int] = TFViTMAEModel(config=_a ) _A : Union[str, Any] = model(_a , training=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a__ ( self , _a , _a , _a ) -> Optional[Any]: _A : Dict = TFViTMAEForPreTraining(_a ) _A : int = model(_a , training=_a ) # expected sequence length = num_patches _A : Union[str, Any] = (self.image_size // self.patch_size) ** 2 _A : List[str] = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images _A : int = 1 _A : Optional[Any] = TFViTMAEForPreTraining(_a ) _A : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _A : Optional[Any] = model(_a , training=_a ) _A : Union[str, Any] = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def a__ ( self ) -> List[Any]: _A : Optional[int] = self.prepare_config_and_inputs() ((_A) , (_A) , (_A)) : Tuple = config_and_inputs _A : List[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class lowercase ( UpperCamelCase__,UpperCamelCase__,unittest.TestCase ): _a = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else () _a = {"feature-extraction": TFViTMAEModel} if is_tf_available() else {} _a = False _a = False _a = False _a = False def a__ ( self ) -> int: _A : Dict = TFViTMAEModelTester(self ) _A : List[Any] = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def a__ ( self ) -> Dict: self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMAE does not use inputs_embeds""" ) def a__ ( self ) -> Tuple: pass def a__ ( self ) -> Any: _A , _A : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : Optional[int] = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) _A : List[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , tf.keras.layers.Layer ) ) def a__ ( self ) -> str: _A , _A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : Union[str, Any] = model_class(_a ) _A : Union[str, Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A : int = [*signature.parameters.keys()] _A : Optional[Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def a__ ( self ) -> Optional[Any]: _A : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def a__ ( self ) -> str: _A : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_a ) def a__ ( self ) -> Optional[Any]: # make the mask reproducible np.random.seed(2 ) _A , _A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() _A : Optional[Any] = int((config.image_size // config.patch_size) ** 2 ) _A : List[Any] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: _A : Optional[int] = model_class(_a ) _A : Dict = self._prepare_for_class(_a , _a ) _A : str = model(_a , noise=_a ) _A : int = copy.deepcopy(self._prepare_for_class(_a , _a ) ) _A : str = model(**_a , noise=_a ) _A : int = outputs_dict[0].numpy() _A : Any = outputs_keywords[0].numpy() self.assertLess(np.sum(np.abs(output_dict - output_keywords ) ) , 1e-6 ) def a__ ( self ) -> Union[str, Any]: # make the mask reproducible np.random.seed(2 ) _A , _A : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() _A : Union[str, Any] = int((config.image_size // config.patch_size) ** 2 ) _A : int = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) def prepare_numpy_arrays(_a ): _A : Tuple = {} for k, v in inputs_dict.items(): if tf.is_tensor(_a ): _A : List[str] = v.numpy() else: _A : Union[str, Any] = np.array(_a ) return inputs_np_dict for model_class in self.all_model_classes: _A : Dict = model_class(_a ) _A : int = self._prepare_for_class(_a , _a ) _A : Any = prepare_numpy_arrays(_a ) _A : List[str] = model(_a , noise=_a ) _A : List[Any] = model(**_a , noise=_a ) self.assert_outputs_same(_a , _a ) def a__ ( self , _a , _a , _a ) -> List[str]: # make masks reproducible np.random.seed(2 ) _A : Tuple = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2 ) _A : Optional[int] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) _A : Dict = tf.constant(_a ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument _A : str = tf_noise super().check_pt_tf_models(_a , _a , _a ) def a__ ( self ) -> Any: # make mask reproducible np.random.seed(2 ) _A , _A : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _A : str = { module_member for model_class in self.all_model_classes for module in (import_module(model_class.__module__ ),) for module_member_name in dir(_a ) if module_member_name.endswith("""MainLayer""" ) # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`. and module_member_name[: -len("""MainLayer""" )] == model_class.__name__[: -len("""Model""" )] for module_member in (getattr(_a , _a ),) if isinstance(_a , _a ) and tf.keras.layers.Layer in module_member.__bases__ and getattr(_a , """_keras_serializable""" , _a ) } _A : Any = int((config.image_size // config.patch_size) ** 2 ) _A : List[Any] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) _A : str = tf.convert_to_tensor(_a ) inputs_dict.update({"""noise""": noise} ) for main_layer_class in tf_main_layer_classes: _A : int = main_layer_class(_a ) _A : str = { name: tf.keras.Input(tensor.shape[1:] , dtype=tensor.dtype ) for name, tensor in inputs_dict.items() } _A : List[Any] = tf.keras.Model(_a , outputs=main_layer(_a ) ) _A : Any = model(_a ) with tempfile.TemporaryDirectory() as tmpdirname: _A : List[Any] = os.path.join(_a , """keras_model.h5""" ) model.save(_a ) _A : Tuple = tf.keras.models.load_model( _a , custom_objects={main_layer_class.__name__: main_layer_class} ) assert isinstance(_a , tf.keras.Model ) _A : List[Any] = model(_a ) self.assert_outputs_same(_a , _a ) @slow def a__ ( self ) -> Optional[Any]: # make mask reproducible np.random.seed(2 ) _A , _A : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() _A : str = int((config.image_size // config.patch_size) ** 2 ) _A : Any = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: _A : int = model_class(_a ) _A : List[str] = self._prepare_for_class(_a , _a ) _A : List[str] = model(_a , noise=_a ) if model_class.__name__ == "TFViTMAEModel": _A : Tuple = outputs.last_hidden_state.numpy() _A : Union[str, Any] = 0 else: _A : Optional[int] = outputs.logits.numpy() _A : Any = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_a , saved_model=_a ) _A : Optional[int] = model_class.from_pretrained(_a ) _A : List[Any] = model(_a , noise=_a ) if model_class.__name__ == "TFViTMAEModel": _A : int = after_outputs["""last_hidden_state"""].numpy() _A : str = 0 else: _A : Any = after_outputs["""logits"""].numpy() _A : str = 0 _A : Tuple = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_a , 1e-5 ) def a__ ( self ) -> List[str]: # make mask reproducible np.random.seed(2 ) _A , _A : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _A : int = int((config.image_size // config.patch_size) ** 2 ) _A : str = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: _A : Dict = model_class(_a ) _A : Any = self._prepare_for_class(_a , _a ) _A : int = model(_a , noise=_a ) _A : List[Any] = model.get_config() # make sure that returned config is jsonifiable, which is required by keras json.dumps(_a ) _A : Dict = model_class.from_config(model.get_config() ) # make sure it also accepts a normal config _A : int = model_class.from_config(model.config ) _A : List[str] = new_model(_a ) # Build model new_model.set_weights(model.get_weights() ) _A : Union[str, Any] = new_model(_a , noise=_a ) self.assert_outputs_same(_a , _a ) @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def a__ ( self ) -> List[str]: pass @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""" ) def a__ ( self ) -> int: pass @slow def a__ ( self ) -> str: _A : int = TFViTMAEModel.from_pretrained("""google/vit-base-patch16-224""" ) self.assertIsNotNone(_a ) def lowerCAmelCase_ ( ): _A : Optional[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class lowercase ( unittest.TestCase ): @cached_property def a__ ( self ) -> Tuple: return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""" ) if is_vision_available() else None @slow def a__ ( self ) -> Tuple: # make random mask reproducible across the PT and TF model np.random.seed(2 ) _A : Union[str, Any] = TFViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""" ) _A : Tuple = self.default_image_processor _A : Optional[int] = prepare_img() _A : Tuple = image_processor(images=_a , return_tensors="""tf""" ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) _A : Tuple = ViTMAEConfig() _A : List[str] = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) _A : Tuple = np.random.uniform(size=(1, num_patches) ) # forward pass _A : int = model(**_a , noise=_a ) # verify the logits _A : Any = tf.convert_to_tensor([1, 196, 768] ) self.assertEqual(outputs.logits.shape , _a ) _A : str = tf.convert_to_tensor( [[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]] ) tf.debugging.assert_near(outputs.logits[0, :3, :3] , _a , atol=1e-4 )
343
import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowercase : def __init__( self , _a , _a=13 , _a=30 , _a=2 , _a=3 , _a=True , _a=True , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=10 , _a=0.02 , _a=None , ) -> Union[str, Any]: _A : Optional[int] = parent _A : Dict = batch_size _A : Any = image_size _A : Optional[int] = patch_size _A : Optional[int] = num_channels _A : List[Any] = is_training _A : Optional[Any] = use_labels _A : Any = hidden_size _A : Any = num_hidden_layers _A : List[Any] = num_attention_heads _A : int = intermediate_size _A : Dict = hidden_act _A : Optional[int] = hidden_dropout_prob _A : str = attention_probs_dropout_prob _A : Any = type_sequence_label_size _A : str = initializer_range _A : Tuple = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) _A : List[Any] = (image_size // patch_size) ** 2 _A : str = num_patches + 1 def a__ ( self ) -> Dict: _A : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A : List[str] = None if self.use_labels: _A : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _A : List[Any] = self.get_config() return config, pixel_values, labels def a__ ( self ) -> Union[str, Any]: return ViTMSNConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , ) def a__ ( self , _a , _a , _a ) -> Dict: _A : List[str] = ViTMSNModel(config=_a ) model.to(_a ) model.eval() _A : List[str] = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a__ ( self , _a , _a , _a ) -> List[str]: _A : Union[str, Any] = self.type_sequence_label_size _A : Tuple = ViTMSNForImageClassification(_a ) model.to(_a ) model.eval() _A : Optional[int] = model(_a , labels=_a ) print("""Pixel and labels shape: {pixel_values.shape}, {labels.shape}""" ) print("""Labels: {labels}""" ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images _A : Dict = 1 _A : str = ViTMSNForImageClassification(_a ) model.to(_a ) model.eval() _A : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _A : int = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a__ ( self ) -> Any: _A : Optional[int] = self.prepare_config_and_inputs() _A , _A , _A : Dict = config_and_inputs _A : List[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowercase ( UpperCamelCase__,UpperCamelCase__,unittest.TestCase ): _a = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () _a = ( {"feature-extraction": ViTMSNModel, "image-classification": ViTMSNForImageClassification} if is_torch_available() else {} ) _a = False _a = False _a = False _a = False def a__ ( self ) -> Tuple: _A : Tuple = ViTMSNModelTester(self ) _A : List[Any] = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def a__ ( self ) -> Optional[int]: self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMSN does not use inputs_embeds""" ) def a__ ( self ) -> int: pass def a__ ( self ) -> Any: _A , _A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : Tuple = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _A : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , nn.Linear ) ) def a__ ( self ) -> str: _A , _A : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : int = model_class(_a ) _A : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A : str = [*signature.parameters.keys()] _A : Optional[int] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def a__ ( self ) -> List[Any]: _A : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def a__ ( self ) -> Any: _A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @slow def a__ ( self ) -> int: for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _A : int = ViTMSNModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowerCAmelCase_ ( ): _A : Dict = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class lowercase ( unittest.TestCase ): @cached_property def a__ ( self ) -> int: return ViTImageProcessor.from_pretrained("""facebook/vit-msn-small""" ) if is_vision_available() else None @slow def a__ ( self ) -> Optional[int]: torch.manual_seed(2 ) _A : Tuple = ViTMSNForImageClassification.from_pretrained("""facebook/vit-msn-small""" ).to(_a ) _A : Tuple = self.default_image_processor _A : Dict = prepare_img() _A : Optional[Any] = image_processor(images=_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): _A : int = model(**_a ) # verify the logits _A : Union[str, Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _a ) _A : Optional[int] = torch.tensor([-0.0803, -0.4454, -0.2375] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) )
343
1
from __future__ import annotations def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : int = sorted(numsa + numsa ) _A , _A : Optional[int] = divmod(len(snake_case_ ),2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _snake_case = [float(x) for x in input("Enter the elements of first array: ").split()] _snake_case = [float(x) for x in input("Enter the elements of second array: ").split()] print(f"""The median of two arrays is: {median_of_two_arrays(array_a, array_a)}""")
343
def lowerCAmelCase_ ( snake_case_ = 1000 ): _A : List[Any] = 3 _A : Tuple = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f"""{solution() = }""")
343
1
import argparse from collections import defaultdict import yaml _snake_case = "docs/source/en/_toctree.yml" def lowerCAmelCase_ ( snake_case_ ): _A : Any = defaultdict(snake_case_ ) _A : Optional[Any] = [] _A : List[Any] = [] for doc in doc_list: if "local" in doc: counts[doc["local"]] += 1 if doc["title"].lower() == "overview": overview_doc.append({"""local""": doc["""local"""], """title""": doc["""title"""]} ) else: new_doc_list.append(snake_case_ ) _A : List[str] = new_doc_list _A : List[str] = [key for key, value in counts.items() if value > 1] _A : List[str] = [] for duplicate_key in duplicates: _A : Optional[Any] = list({doc["""title"""] for doc in doc_list if doc["""local"""] == duplicate_key} ) if len(snake_case_ ) > 1: raise ValueError( f'''{duplicate_key} is present several times in the documentation table of content at ''' """`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the """ """others.""" ) # Only add this once new_doc.append({"""local""": duplicate_key, """title""": titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in doc_list if """local""" not in counts or counts[doc["""local"""]] == 1] ) _A : List[Any] = sorted(snake_case_,key=lambda snake_case_ : s["title"].lower() ) # "overview" gets special treatment and is always first if len(snake_case_ ) > 1: raise ValueError("""{doc_list} has two 'overview' docs which is not allowed.""" ) overview_doc.extend(snake_case_ ) # Sort return overview_doc def lowerCAmelCase_ ( snake_case_=False ): with open(snake_case_,encoding="""utf-8""" ) as f: _A : List[str] = yaml.safe_load(f.read() ) # Get to the API doc _A : List[Any] = 0 while content[api_idx]["title"] != "API": api_idx += 1 _A : Dict = content[api_idx]["""sections"""] # Then to the model doc _A : Dict = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 _A : Union[str, Any] = api_doc[scheduler_idx]["""sections"""] _A : Optional[int] = clean_doc_toc(snake_case_ ) _A : List[Any] = False if new_scheduler_doc != scheduler_doc: _A : str = True if overwrite: _A : Optional[Any] = new_scheduler_doc if diff: if overwrite: _A : List[Any] = api_doc with open(snake_case_,"""w""",encoding="""utf-8""" ) as f: f.write(yaml.dump(snake_case_,allow_unicode=snake_case_ ) ) else: raise ValueError( """The model doc part of the table of content is not properly sorted, run `make style` to fix this.""" ) def lowerCAmelCase_ ( snake_case_=False ): with open(snake_case_,encoding="""utf-8""" ) as f: _A : Union[str, Any] = yaml.safe_load(f.read() ) # Get to the API doc _A : List[Any] = 0 while content[api_idx]["title"] != "API": api_idx += 1 _A : Any = content[api_idx]["""sections"""] # Then to the model doc _A : str = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 _A : Any = False _A : Optional[int] = api_doc[pipeline_idx]["""sections"""] _A : Optional[Any] = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: _A : Dict = pipeline_doc["""section"""] _A : Dict = clean_doc_toc(snake_case_ ) if overwrite: _A : str = new_sub_pipeline_doc new_pipeline_docs.append(snake_case_ ) # sort overall pipeline doc _A : int = clean_doc_toc(snake_case_ ) if new_pipeline_docs != pipeline_docs: _A : Union[str, Any] = True if overwrite: _A : int = new_pipeline_docs if diff: if overwrite: _A : Union[str, Any] = api_doc with open(snake_case_,"""w""",encoding="""utf-8""" ) as f: f.write(yaml.dump(snake_case_,allow_unicode=snake_case_ ) ) else: raise ValueError( """The model doc part of the table of content is not properly sorted, run `make style` to fix this.""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") _snake_case = parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
343
import inspect import unittest from transformers import ConvNextConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase : def __init__( self , _a , _a=13 , _a=32 , _a=3 , _a=4 , _a=[10, 20, 30, 40] , _a=[2, 2, 3, 2] , _a=True , _a=True , _a=37 , _a="gelu" , _a=10 , _a=0.02 , _a=["stage2", "stage3", "stage4"] , _a=[2, 3, 4] , _a=None , ) -> List[Any]: _A : Tuple = parent _A : Any = batch_size _A : int = image_size _A : Tuple = num_channels _A : List[Any] = num_stages _A : Any = hidden_sizes _A : Union[str, Any] = depths _A : Union[str, Any] = is_training _A : Tuple = use_labels _A : Optional[Any] = intermediate_size _A : Union[str, Any] = hidden_act _A : Any = num_labels _A : List[str] = initializer_range _A : str = out_features _A : int = out_indices _A : List[Any] = scope def a__ ( self ) -> str: _A : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A : str = None if self.use_labels: _A : int = ids_tensor([self.batch_size] , self.num_labels ) _A : str = self.get_config() return config, pixel_values, labels def a__ ( self ) -> List[str]: return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=_a , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def a__ ( self , _a , _a , _a ) -> int: _A : int = ConvNextModel(config=_a ) model.to(_a ) model.eval() _A : int = model(_a ) # expected last hidden states: B, C, H // 32, W // 32 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 , _a ) -> List[Any]: _A : Union[str, Any] = ConvNextForImageClassification(_a ) model.to(_a ) model.eval() _A : List[Any] = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a__ ( self , _a , _a , _a ) -> str: _A : List[str] = ConvNextBackbone(config=_a ) model.to(_a ) model.eval() _A : Optional[int] = model(_a ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None _A : Optional[Any] = None _A : str = ConvNextBackbone(config=_a ) model.to(_a ) model.eval() _A : int = model(_a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def a__ ( self ) -> int: _A : int = self.prepare_config_and_inputs() _A , _A , _A : List[Any] = config_and_inputs _A : Any = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowercase ( UpperCamelCase__,UpperCamelCase__,unittest.TestCase ): _a = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) _a = ( {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification} if is_torch_available() else {} ) _a = True _a = False _a = False _a = False _a = False def a__ ( self ) -> Dict: _A : int = ConvNextModelTester(self ) _A : List[Any] = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def a__ ( self ) -> Any: 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 ) -> str: return @unittest.skip(reason="""ConvNext does not use inputs_embeds""" ) def a__ ( self ) -> Tuple: pass @unittest.skip(reason="""ConvNext does not support input and output embeddings""" ) def a__ ( self ) -> Optional[Any]: pass @unittest.skip(reason="""ConvNext does not use feedforward chunking""" ) def a__ ( self ) -> List[Any]: pass def a__ ( self ) -> Optional[Any]: _A , _A : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : Optional[Any] = model_class(_a ) _A : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A : List[Any] = [*signature.parameters.keys()] _A : int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def a__ ( self ) -> Union[str, Any]: _A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def a__ ( self ) -> Tuple: _A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_a ) def a__ ( self ) -> Tuple: def check_hidden_states_output(_a , _a , _a ): _A : Tuple = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): _A : Dict = model(**self._prepare_for_class(_a , _a ) ) _A : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _A : Dict = self.model_tester.num_stages self.assertEqual(len(_a ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) _A , _A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : List[Any] = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _A : Union[str, Any] = True check_hidden_states_output(_a , _a , _a ) def a__ ( self ) -> int: _A : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @slow def a__ ( self ) -> Optional[int]: for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _A : Optional[Any] = ConvNextModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowerCAmelCase_ ( ): _A : Optional[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class lowercase ( unittest.TestCase ): @cached_property def a__ ( self ) -> str: return AutoImageProcessor.from_pretrained("""facebook/convnext-tiny-224""" ) if is_vision_available() else None @slow def a__ ( self ) -> Optional[Any]: _A : Any = ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224""" ).to(_a ) _A : List[str] = self.default_image_processor _A : int = prepare_img() _A : Union[str, Any] = image_processor(images=_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): _A : Dict = model(**_a ) # verify the logits _A : Optional[Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _a ) _A : Any = torch.tensor([-0.0260, -0.4739, 0.1911] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) ) @require_torch class lowercase ( unittest.TestCase,UpperCamelCase__ ): _a = (ConvNextBackbone,) if is_torch_available() else () _a = ConvNextConfig _a = False def a__ ( self ) -> List[str]: _A : Optional[int] = ConvNextModelTester(self )
343
1
import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class lowercase ( UpperCamelCase__ ): _a = "M-CLIP" def __init__( self , _a=1024 , _a=768 , **_a ) -> Optional[int]: _A : str = transformerDimSize _A : Any = imageDimSize super().__init__(**_a ) class lowercase ( UpperCamelCase__ ): _a = MCLIPConfig def __init__( self , _a , *_a , **_a ) -> str: super().__init__(_a , *_a , **_a ) _A : Optional[int] = XLMRobertaModel(_a ) _A : int = torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims ) def a__ ( self , _a , _a ) -> int: _A : Optional[Any] = self.transformer(input_ids=_a , attention_mask=_a )[0] _A : Dict = (embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None] return self.LinearTransformation(_a ), embs
343
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _snake_case = { "configuration_roc_bert": ["ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoCBertConfig"], "tokenization_roc_bert": ["RoCBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ "ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "RoCBertForCausalLM", "RoCBertForMaskedLM", "RoCBertForMultipleChoice", "RoCBertForPreTraining", "RoCBertForQuestionAnswering", "RoCBertForSequenceClassification", "RoCBertForTokenClassification", "RoCBertLayer", "RoCBertModel", "RoCBertPreTrainedModel", "load_tf_weights_in_roc_bert", ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys _snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
343
1
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowercase : _a = 42 # setable values _a = 42 _a = 42 _a = None @classmethod def a__ ( cls , _a , _a , _a ) -> Tuple: return cls(common=_a , init_noise_sigma=_a , timesteps=_a ) @dataclass class lowercase ( UpperCamelCase__ ): _a = 42 class lowercase ( UpperCamelCase__,UpperCamelCase__ ): _a = [e.name for e in FlaxKarrasDiffusionSchedulers] _a = 42 @property def a__ ( self ) -> Dict: return True @register_to_config def __init__( self , _a = 1000 , _a = 0.0001 , _a = 0.02 , _a = "linear" , _a = None , _a = "fixed_small" , _a = True , _a = "epsilon" , _a = jnp.floataa , ) -> Tuple: _A : Tuple = dtype def a__ ( self , _a = None ) -> DDPMSchedulerState: if common is None: _A : Dict = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution _A : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) _A : Tuple = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=_a , init_noise_sigma=_a , timesteps=_a , ) def a__ ( self , _a , _a , _a = None ) -> jnp.ndarray: return sample def a__ ( self , _a , _a , _a = () ) -> DDPMSchedulerState: _A : Any = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 _A : Dict = (jnp.arange(0 , _a ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=_a , timesteps=_a , ) def a__ ( self , _a , _a , _a=None , _a=None ) -> Optional[int]: _A : Optional[Any] = state.common.alphas_cumprod[t] _A : int = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample _A : List[str] = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: _A : Optional[Any] = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": _A : Optional[Any] = jnp.clip(_a , a_min=1e-20 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": _A : Any = jnp.log(jnp.clip(_a , a_min=1e-20 ) ) elif variance_type == "fixed_large": _A : Optional[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log _A : Tuple = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": _A : str = variance _A : Union[str, Any] = state.common.betas[t] _A : Tuple = (predicted_variance + 1) / 2 _A : List[str] = frac * max_log + (1 - frac) * min_log return variance def a__ ( self , _a , _a , _a , _a , _a = None , _a = True , ) -> Union[FlaxDDPMSchedulerOutput, Tuple]: _A : Dict = timestep if key is None: _A : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: _A , _A : List[str] = jnp.split(_a , sample.shape[1] , axis=1 ) else: _A : int = None # 1. compute alphas, betas _A : int = state.common.alphas_cumprod[t] _A : List[str] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) _A : Union[str, Any] = 1 - alpha_prod_t _A : Optional[int] = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": _A : Dict = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": _A : Optional[int] = model_output elif self.config.prediction_type == "v_prediction": _A : Any = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' """ for the FlaxDDPMScheduler.""" ) # 3. Clip "predicted x_0" if self.config.clip_sample: _A : Union[str, Any] = jnp.clip(_a , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _A : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t _A : Dict = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _A : int = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): _A : Tuple = jax.random.split(_a , num=1 ) _A : Dict = jax.random.normal(_a , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(_a , _a , predicted_variance=_a ) ** 0.5) * noise _A : int = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) _A : Union[str, Any] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=_a , state=_a ) def a__ ( self , _a , _a , _a , _a , ) -> jnp.ndarray: return add_noise_common(state.common , _a , _a , _a ) def a__ ( self , _a , _a , _a , _a , ) -> jnp.ndarray: return get_velocity_common(state.common , _a , _a , _a ) def __len__( self ) -> List[Any]: return self.config.num_train_timesteps
343
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowercase : _a = 42 # setable values _a = 42 _a = 42 _a = None @classmethod def a__ ( cls , _a , _a , _a ) -> Tuple: return cls(common=_a , init_noise_sigma=_a , timesteps=_a ) @dataclass class lowercase ( UpperCamelCase__ ): _a = 42 class lowercase ( UpperCamelCase__,UpperCamelCase__ ): _a = [e.name for e in FlaxKarrasDiffusionSchedulers] _a = 42 @property def a__ ( self ) -> Dict: return True @register_to_config def __init__( self , _a = 1000 , _a = 0.0001 , _a = 0.02 , _a = "linear" , _a = None , _a = "fixed_small" , _a = True , _a = "epsilon" , _a = jnp.floataa , ) -> Tuple: _A : Tuple = dtype def a__ ( self , _a = None ) -> DDPMSchedulerState: if common is None: _A : Dict = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution _A : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) _A : Tuple = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=_a , init_noise_sigma=_a , timesteps=_a , ) def a__ ( self , _a , _a , _a = None ) -> jnp.ndarray: return sample def a__ ( self , _a , _a , _a = () ) -> DDPMSchedulerState: _A : Any = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 _A : Dict = (jnp.arange(0 , _a ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=_a , timesteps=_a , ) def a__ ( self , _a , _a , _a=None , _a=None ) -> Optional[int]: _A : Optional[Any] = state.common.alphas_cumprod[t] _A : int = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample _A : List[str] = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: _A : Optional[Any] = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": _A : Optional[Any] = jnp.clip(_a , a_min=1e-20 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": _A : Any = jnp.log(jnp.clip(_a , a_min=1e-20 ) ) elif variance_type == "fixed_large": _A : Optional[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log _A : Tuple = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": _A : str = variance _A : Union[str, Any] = state.common.betas[t] _A : Tuple = (predicted_variance + 1) / 2 _A : List[str] = frac * max_log + (1 - frac) * min_log return variance def a__ ( self , _a , _a , _a , _a , _a = None , _a = True , ) -> Union[FlaxDDPMSchedulerOutput, Tuple]: _A : Dict = timestep if key is None: _A : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: _A , _A : List[str] = jnp.split(_a , sample.shape[1] , axis=1 ) else: _A : int = None # 1. compute alphas, betas _A : int = state.common.alphas_cumprod[t] _A : List[str] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) _A : Union[str, Any] = 1 - alpha_prod_t _A : Optional[int] = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": _A : Dict = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": _A : Optional[int] = model_output elif self.config.prediction_type == "v_prediction": _A : Any = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' """ for the FlaxDDPMScheduler.""" ) # 3. Clip "predicted x_0" if self.config.clip_sample: _A : Union[str, Any] = jnp.clip(_a , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _A : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t _A : Dict = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _A : int = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): _A : Tuple = jax.random.split(_a , num=1 ) _A : Dict = jax.random.normal(_a , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(_a , _a , predicted_variance=_a ) ** 0.5) * noise _A : int = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) _A : Union[str, Any] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=_a , state=_a ) def a__ ( self , _a , _a , _a , _a , ) -> jnp.ndarray: return add_noise_common(state.common , _a , _a , _a ) def a__ ( self , _a , _a , _a , _a , ) -> jnp.ndarray: return get_velocity_common(state.common , _a , _a , _a ) def __len__( self ) -> List[Any]: return self.config.num_train_timesteps
343
1
def lowerCAmelCase_ ( snake_case_,snake_case_ ): assert x is not None assert y is not None _A : Tuple = len(snake_case_ ) _A : int = len(snake_case_ ) # declaring the array for storing the dp values _A : Union[str, Any] = [[0] * (n + 1) for _ in range(m + 1 )] # noqa: E741 for i in range(1,m + 1 ): for j in range(1,n + 1 ): _A : Any = 1 if x[i - 1] == y[j - 1] else 0 _A : Union[str, Any] = max(l[i - 1][j],l[i][j - 1],l[i - 1][j - 1] + match ) _A : Optional[Any] = """""" _A , _A : Any = m, n while i > 0 and j > 0: _A : Union[str, Any] = 1 if x[i - 1] == y[j - 1] else 0 if l[i][j] == l[i - 1][j - 1] + match: if match == 1: _A : Optional[Any] = x[i - 1] + seq i -= 1 j -= 1 elif l[i][j] == l[i - 1][j]: i -= 1 else: j -= 1 return l[m][n], seq if __name__ == "__main__": _snake_case = "AGGTAB" _snake_case = "GXTXAYB" _snake_case = 4 _snake_case = "GTAB" _snake_case , _snake_case = longest_common_subsequence(a, b) print("len =", ln, ", sub-sequence =", subseq) import doctest doctest.testmod()
343
# Copyright (c) 2021-, NVIDIA CORPORATION. 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. #################################################################################################### # # Note: If when running this conversion script you're getting an exception: # ModuleNotFoundError: No module named 'megatron.model.enums' # you need to tell python where to find the clone of Megatron-LM, e.g.: # # cd /tmp # git clone https://github.com/NVIDIA/Megatron-LM # PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ... # # if you already have it cloned elsewhere, simply adjust the path to the existing path # # If the training was done using a Megatron-LM fork, e.g., # https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one # in your path, i.e., /path/to/Megatron-DeepSpeed/ # import argparse import os import re import zipfile import torch from transformers import AutoTokenizer, GPTaConfig def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_=0 ): # Format the message. if name is None: _A : Union[str, Any] = None else: _A : Dict = """.""" * max(0,spaces - 2 ) + """# {:""" + str(50 - spaces ) + """s}""" _A : Tuple = fmt.format(snake_case_ ) # Print and recurse (if needed). if isinstance(snake_case_,snake_case_ ): if msg is not None: print(snake_case_ ) for k in val.keys(): recursive_print(snake_case_,val[k],spaces + 2 ) elif isinstance(snake_case_,torch.Tensor ): print(snake_case_,""":""",val.size() ) else: print(snake_case_,""":""",snake_case_ ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_ ): # Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :] # for compatibility with later versions of NVIDIA Megatron-LM. # The inverse operation is performed inside Megatron-LM to read checkpoints: # https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209 # If param is the weight tensor of the self-attention block, the returned tensor # will have to be transposed one more time to be read by HuggingFace GPT2. _A : str = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] _A : Union[str, Any] = (num_heads, hidden_size, num_splits) + input_shape[1:] _A : Tuple = param.view(*snake_case_ ) _A : Any = param.transpose(0,2 ) _A : int = param.transpose(1,2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] _A : Optional[Any] = (num_heads, num_splits, hidden_size) + input_shape[1:] _A : int = param.view(*snake_case_ ) _A : Any = param.transpose(0,1 ).contiguous() _A : Optional[int] = param.view(*snake_case_ ) return param def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): # The converted output model. _A : Any = {} # old versions did not store training args _A : str = input_state_dict.get("""args""",snake_case_ ) if ds_args is not None: # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint # from pprint import pprint # pprint(vars(ds_args)) _A : Union[str, Any] = ds_args.padded_vocab_size _A : List[Any] = ds_args.max_position_embeddings _A : Optional[int] = ds_args.hidden_size _A : List[Any] = ds_args.num_layers _A : List[str] = ds_args.num_attention_heads _A : int = ds_args.ffn_hidden_size # pprint(config) # The number of heads. _A : Union[str, Any] = config.n_head # The hidden_size per head. _A : List[Any] = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): _A : Tuple = input_state_dict["""checkpoint_version"""] else: _A : Any = 0.0 # The model. _A : Any = input_state_dict["""model"""] # The language model. _A : Tuple = model["""language_model"""] # The embeddings. _A : Any = lm["""embedding"""] # The word embeddings. _A : Dict = embeddings["""word_embeddings"""]["""weight"""] # Truncate the embedding table to vocab_size rows. _A : Union[str, Any] = word_embeddings[: config.vocab_size, :] _A : Tuple = word_embeddings # The position embeddings. _A : Tuple = embeddings["""position_embeddings"""]["""weight"""] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] _A : Any = pos_embeddings.size(0 ) if n_positions != config.n_positions: raise ValueError( f'''pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don\'t match''' ) # Store the position embeddings. _A : Optional[int] = pos_embeddings # The transformer. _A : Any = lm["""transformer"""] if """transformer""" in lm.keys() else lm["""encoder"""] # The regex to extract layer names. _A : Optional[int] = re.compile(r"""layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)""" ) # The simple map of names for "automated" rules. _A : Union[str, Any] = { """attention.dense""": """.attn.c_proj.""", """self_attention.dense""": """.attn.c_proj.""", """mlp.dense_h_to_4h""": """.mlp.c_fc.""", """mlp.dense_4h_to_h""": """.mlp.c_proj.""", } # Extract the layers. for key, val in transformer.items(): # Match the name. _A : List[str] = layer_re.match(snake_case_ ) # Stop if that's not a layer if m is None: break # The index of the layer. _A : Tuple = int(m.group(1 ) ) # The name of the operation. _A : Optional[Any] = m.group(2 ) # Is it a weight or a bias? _A : Dict = m.group(3 ) # The name of the layer. _A : Optional[Any] = f'''transformer.h.{layer_idx}''' # For layernorm(s), simply store the layer norm. if op_name.endswith("""layernorm""" ): _A : Union[str, Any] = """ln_1""" if op_name.startswith("""input""" ) else """ln_2""" _A : List[str] = val # Transpose the QKV matrix. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "weight": # Insert a tensor of 1x1xDxD bias. _A : List[str] = torch.tril(torch.ones((n_positions, n_positions),dtype=torch.floataa ) ).view( 1,1,snake_case_,snake_case_ ) _A : Any = causal_mask # Insert a "dummy" tensor for masked_bias. _A : List[str] = torch.tensor(-1e4,dtype=torch.floataa ) _A : Tuple = masked_bias _A : Tuple = fix_query_key_value_ordering(snake_case_,snake_case_,3,snake_case_,snake_case_ ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. _A : Tuple = out_val.transpose(0,1 ).contiguous() # Store. _A : Any = out_val # Transpose the bias. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "bias": _A : List[str] = fix_query_key_value_ordering(snake_case_,snake_case_,3,snake_case_,snake_case_ ) # Store. No change of shape. _A : Tuple = out_val # Transpose the weights. elif weight_or_bias == "weight": _A : List[str] = megatron_to_transformers[op_name] _A : Any = val.transpose(0,1 ) # Copy the bias. elif weight_or_bias == "bias": _A : Dict = megatron_to_transformers[op_name] _A : List[Any] = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. _A : Optional[Any] = transformer["""final_layernorm.weight"""] _A : Dict = transformer["""final_layernorm.bias"""] # For LM head, transformers' wants the matrix to weight embeddings. _A : List[str] = word_embeddings # It should be done! return output_state_dict def lowerCAmelCase_ ( ): # Create the argument parser. _A : Any = argparse.ArgumentParser() parser.add_argument("""--print-checkpoint-structure""",action="""store_true""" ) parser.add_argument( """path_to_checkpoint""",type=snake_case_,help="""Path to the checkpoint file (.zip archive or direct .pt file)""",) parser.add_argument( """--config_file""",default="""""",type=snake_case_,help="""An optional config json file describing the pre-trained model.""",) _A : Optional[int] = parser.parse_args() # Extract the basename. _A : Any = os.path.dirname(args.path_to_checkpoint ) # Load the model. # the .zip is very optional, let's keep it for backward compatibility print(f'''Extracting PyTorch state dictionary from {args.path_to_checkpoint}''' ) if args.path_to_checkpoint.endswith(""".zip""" ): with zipfile.ZipFile(args.path_to_checkpoint,"""r""" ) as checkpoint: with checkpoint.open("""release/mp_rank_00/model_optim_rng.pt""" ) as pytorch_dict: _A : Tuple = torch.load(snake_case_,map_location="""cpu""" ) else: _A : Tuple = torch.load(args.path_to_checkpoint,map_location="""cpu""" ) _A : Optional[Any] = input_state_dict.get("""args""",snake_case_ ) # Read the config, or default to the model released by NVIDIA. if args.config_file == "": if ds_args is not None: if ds_args.bias_gelu_fusion: _A : Union[str, Any] = """gelu_fast""" elif ds_args.openai_gelu: _A : int = """gelu_new""" else: _A : Optional[Any] = """gelu""" else: # in the very early days this used to be "gelu_new" _A : Any = """gelu_new""" # Spell out all parameters in case the defaults change. _A : Any = GPTaConfig( vocab_size=50257,n_positions=1024,n_embd=1024,n_layer=24,n_head=16,n_inner=4096,activation_function=snake_case_,resid_pdrop=0.1,embd_pdrop=0.1,attn_pdrop=0.1,layer_norm_epsilon=1e-5,initializer_range=0.02,summary_type="""cls_index""",summary_use_proj=snake_case_,summary_activation=snake_case_,summary_proj_to_labels=snake_case_,summary_first_dropout=0.1,scale_attn_weights=snake_case_,use_cache=snake_case_,bos_token_id=50256,eos_token_id=50256,) else: _A : Union[str, Any] = GPTaConfig.from_json_file(args.config_file ) _A : List[str] = ["""GPT2LMHeadModel"""] # Convert. print("""Converting""" ) _A : Optional[Any] = convert_megatron_checkpoint(snake_case_,snake_case_,snake_case_ ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(snake_case_,snake_case_ ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: _A : int = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": _A : Any = """gpt2""" elif tokenizer_type == "PretrainedFromHF": _A : List[Any] = ds_args.tokenizer_name_or_path else: raise ValueError(f'''Unrecognized tokenizer_type {tokenizer_type}''' ) else: _A : Optional[Any] = """gpt2""" _A : List[str] = AutoTokenizer.from_pretrained(snake_case_ ) _A : Tuple = type(snake_case_ ).__name__ _A : Union[str, Any] = tokenizer_class # Store the config to file. print("""Saving config""" ) config.save_pretrained(snake_case_ ) # Save tokenizer based on args print(f'''Adding {tokenizer_class} tokenizer files''' ) tokenizer.save_pretrained(snake_case_ ) # Store the state_dict to file. _A : Union[str, Any] = os.path.join(snake_case_,"""pytorch_model.bin""" ) print(f'''Saving checkpoint to "{output_checkpoint_file}"''' ) torch.save(snake_case_,snake_case_ ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
343
1
import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( "The `inpainting.py` script is outdated. Please use directly `from diffusers import" " StableDiffusionInpaintPipeline` instead." )
343
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer _snake_case = logging.get_logger(__name__) _snake_case = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _snake_case = { "vocab_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } _snake_case = { "vocab_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } _snake_case = { "vocab_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json" ), }, } _snake_case = { "facebook/dpr-ctx_encoder-single-nq-base": 512, "facebook/dpr-ctx_encoder-multiset-base": 512, } _snake_case = { "facebook/dpr-question_encoder-single-nq-base": 512, "facebook/dpr-question_encoder-multiset-base": 512, } _snake_case = { "facebook/dpr-reader-single-nq-base": 512, "facebook/dpr-reader-multiset-base": 512, } _snake_case = { "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True}, } _snake_case = { "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True}, } _snake_case = { "facebook/dpr-reader-single-nq-base": {"do_lower_case": True}, "facebook/dpr-reader-multiset-base": {"do_lower_case": True}, } class lowercase ( UpperCamelCase__ ): _a = VOCAB_FILES_NAMES _a = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _a = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION class lowercase ( UpperCamelCase__ ): _a = VOCAB_FILES_NAMES _a = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _a = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION _snake_case = collections.namedtuple( "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"] ) _snake_case = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"]) _snake_case = r"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n ```\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n ```\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Returns:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n " @add_start_docstrings(UpperCamelCase__ ) class lowercase : def __call__( self , _a , _a = None , _a = None , _a = False , _a = False , _a = None , _a = None , _a = None , **_a , ) -> BatchEncoding: if titles is None and texts is None: return super().__call__( _a , padding=_a , truncation=_a , max_length=_a , return_tensors=_a , return_attention_mask=_a , **_a , ) elif titles is None or texts is None: _A : Optional[Any] = titles if texts is None else texts return super().__call__( _a , _a , padding=_a , truncation=_a , max_length=_a , return_tensors=_a , return_attention_mask=_a , **_a , ) _A : Dict = titles if not isinstance(_a , _a ) else [titles] _A : Tuple = texts if not isinstance(_a , _a ) else [texts] _A : Any = len(_a ) _A : Optional[Any] = questions if not isinstance(_a , _a ) else [questions] * n_passages if len(_a ) != len(_a ): raise ValueError( F'''There should be as many titles than texts but got {len(_a )} titles and {len(_a )} texts.''' ) _A : str = super().__call__(_a , _a , padding=_a , truncation=_a )["""input_ids"""] _A : Optional[int] = super().__call__(_a , add_special_tokens=_a , padding=_a , truncation=_a )["""input_ids"""] _A : Optional[int] = { """input_ids""": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_a , _a ) ] } if return_attention_mask is not False: _A : Any = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) _A : str = attention_mask return self.pad(_a , padding=_a , max_length=_a , return_tensors=_a ) def a__ ( self , _a , _a , _a = 16 , _a = 64 , _a = 4 , ) -> List[DPRSpanPrediction]: _A : Dict = reader_input["""input_ids"""] _A , _A , _A : Tuple = reader_output[:3] _A : List[str] = len(_a ) _A : Tuple = sorted(range(_a ) , reverse=_a , key=relevance_logits.__getitem__ ) _A : List[DPRReaderOutput] = [] for doc_id in sorted_docs: _A : Tuple = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence _A : int = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: _A : Tuple = sequence_ids.index(self.pad_token_id ) else: _A : Tuple = len(_a ) _A : Union[str, Any] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_a , top_spans=_a , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_a , start_index=_a , end_index=_a , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_a ) >= num_spans: break return nbest_spans_predictions[:num_spans] def a__ ( self , _a , _a , _a , _a , ) -> List[DPRSpanPrediction]: _A : Tuple = [] for start_index, start_score in enumerate(_a ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) _A : Tuple = sorted(_a , key=lambda _a : x[1] , reverse=_a ) _A : Union[str, Any] = [] for (start_index, end_index), score in scores: if start_index > end_index: raise ValueError(F'''Wrong span indices: [{start_index}:{end_index}]''' ) _A : Dict = end_index - start_index + 1 if length > max_answer_length: raise ValueError(F'''Span is too long: {length} > {max_answer_length}''' ) if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_a ) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCamelCase__ ) class lowercase ( UpperCamelCase__,UpperCamelCase__ ): _a = VOCAB_FILES_NAMES _a = READER_PRETRAINED_VOCAB_FILES_MAP _a = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = READER_PRETRAINED_INIT_CONFIGURATION _a = ["input_ids", "attention_mask"]
343
1
def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_ ): global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: _A : List[str] = mf_knapsack(i - 1,snake_case_,snake_case_,snake_case_ ) else: _A : List[str] = max( mf_knapsack(i - 1,snake_case_,snake_case_,snake_case_ ),mf_knapsack(i - 1,snake_case_,snake_case_,j - wt[i - 1] ) + val[i - 1],) _A : Optional[Any] = val return f[i][j] def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_ ): _A : Any = [[0] * (w + 1) for _ in range(n + 1 )] for i in range(1,n + 1 ): for w_ in range(1,w + 1 ): if wt[i - 1] <= w_: _A : Dict = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]],dp[i - 1][w_] ) else: _A : List[Any] = dp[i - 1][w_] return dp[n][w_], dp def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): if not (isinstance(snake_case_,(list, tuple) ) and isinstance(snake_case_,(list, tuple) )): raise ValueError( """Both the weights and values vectors must be either lists or tuples""" ) _A : int = len(snake_case_ ) if num_items != len(snake_case_ ): _A : int = ( """The number of weights must be the same as the number of values.\n""" f'''But got {num_items} weights and {len(snake_case_ )} values''' ) raise ValueError(snake_case_ ) for i in range(snake_case_ ): if not isinstance(wt[i],snake_case_ ): _A : List[str] = ( """All weights must be integers but got weight of """ f'''type {type(wt[i] )} at index {i}''' ) raise TypeError(snake_case_ ) _A , _A : List[Any] = knapsack(snake_case_,snake_case_,snake_case_,snake_case_ ) _A : set = set() _construct_solution(snake_case_,snake_case_,snake_case_,snake_case_,snake_case_ ) return optimal_val, example_optional_set def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_ ): # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(snake_case_,snake_case_,i - 1,snake_case_,snake_case_ ) else: optimal_set.add(snake_case_ ) _construct_solution(snake_case_,snake_case_,i - 1,j - wt[i - 1],snake_case_ ) if __name__ == "__main__": _snake_case = [3, 2, 4, 4] _snake_case = [4, 3, 2, 3] _snake_case = 4 _snake_case = 6 _snake_case = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] _snake_case , _snake_case = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 _snake_case , _snake_case = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print("optimal_value = ", optimal_solution) print("An optimal subset corresponding to the optimal value", optimal_subset)
343
import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class lowercase ( unittest.TestCase ): @property def a__ ( self ) -> Dict: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def a__ ( self ) -> List[Any]: _A : int = ort.SessionOptions() _A : Any = False return options def a__ ( self ) -> Union[str, Any]: _A : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) _A : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) _A : List[str] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy""" ) # using the PNDM scheduler by default _A : str = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=_a , feature_extractor=_a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_a ) _A : Optional[Any] = """A red cat sitting on a park bench""" _A : Optional[Any] = np.random.RandomState(0 ) _A : Dict = pipe( prompt=_a , image=_a , mask_image=_a , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=_a , output_type="""np""" , ) _A : Optional[int] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1e-2
343
1
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowerCAmelCase_ ( snake_case_,snake_case_ ): # Load checkpoint _A : Optional[int] = torch.load(snake_case_,map_location="""cpu""" ) _A : Any = chkpt["""model"""] # We have the base model one level deeper than the original XLM repository _A : Any = {} for k, v in state_dict.items(): if "pred_layer" in k: _A : Tuple = v else: _A : Dict = v _A : Optional[Any] = chkpt["""params"""] _A : Union[str, Any] = {n: v for n, v in config.items() if not isinstance(snake_case_,(torch.FloatTensor, numpy.ndarray) )} _A : str = chkpt["""dico_word2id"""] _A : Optional[Any] = {s + """</w>""" if s.find("""@@""" ) == -1 and i > 13 else s.replace("""@@""","""""" ): i for s, i in vocab.items()} # Save pytorch-model _A : Dict = pytorch_dump_folder_path + """/""" + WEIGHTS_NAME _A : Any = pytorch_dump_folder_path + """/""" + CONFIG_NAME _A : Optional[int] = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""vocab_file"""] print(f'''Save PyTorch model to {pytorch_weights_dump_path}''' ) torch.save(snake_case_,snake_case_ ) print(f'''Save configuration file to {pytorch_config_dump_path}''' ) with open(snake_case_,"""w""",encoding="""utf-8""" ) as f: f.write(json.dumps(snake_case_,indent=2 ) + """\n""" ) print(f'''Save vocab file to {pytorch_config_dump_path}''' ) with open(snake_case_,"""w""",encoding="""utf-8""" ) as f: f.write(json.dumps(snake_case_,indent=2 ) + """\n""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( "--xlm_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) _snake_case = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
343
from __future__ import annotations def lowerCAmelCase_ ( snake_case_ ): create_state_space_tree(snake_case_,[],0,[0 for i in range(len(snake_case_ ) )] ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,): if index == len(snake_case_ ): print(snake_case_ ) return for i in range(len(snake_case_ ) ): if not index_used[i]: current_sequence.append(sequence[i] ) _A : Optional[Any] = True create_state_space_tree(snake_case_,snake_case_,index + 1,snake_case_ ) current_sequence.pop() _A : str = False _snake_case = [3, 1, 2, 4] generate_all_permutations(sequence) _snake_case = ["A", "B", "C"] generate_all_permutations(sequence_a)
343
1
import unittest from knapsack import greedy_knapsack as kp class lowercase ( unittest.TestCase ): def a__ ( self ) -> Dict: _A : Optional[Any] = [10, 20, 30, 40, 50, 60] _A : Tuple = [2, 4, 6, 8, 10, 12] _A : Any = 100 self.assertEqual(kp.calc_profit(_a , _a , _a ) , 210 ) def a__ ( self ) -> List[Any]: self.assertRaisesRegex(_a , """max_weight must greater than zero.""" ) def a__ ( self ) -> Dict: self.assertRaisesRegex(_a , """Weight can not be negative.""" ) def a__ ( self ) -> Dict: self.assertRaisesRegex(_a , """Profit can not be negative.""" ) def a__ ( self ) -> List[str]: self.assertRaisesRegex(_a , """max_weight must greater than zero.""" ) def a__ ( self ) -> Any: self.assertRaisesRegex( _a , """The length of profit and weight must be same.""" ) if __name__ == "__main__": unittest.main()
343
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def lowerCAmelCase_ ( snake_case_ ): _A : Tuple = filter(lambda snake_case_ : p.requires_grad,model.parameters() ) _A : str = sum([np.prod(p.size() ) for p in model_parameters] ) return params _snake_case = logging.getLogger(__name__) def lowerCAmelCase_ ( snake_case_,snake_case_ ): if metric == "rouge2": _A : Optional[int] = """{val_avg_rouge2:.4f}-{step_count}""" elif metric == "bleu": _A : Dict = """{val_avg_bleu:.4f}-{step_count}""" elif metric == "em": _A : List[str] = """{val_avg_em:.4f}-{step_count}""" else: raise NotImplementedError( f'''seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this''' """ function.""" ) _A : Optional[int] = ModelCheckpoint( dirpath=snake_case_,filename=snake_case_,monitor=f'''val_{metric}''',mode="""max""",save_top_k=3,every_n_epochs=1,) return checkpoint_callback def lowerCAmelCase_ ( snake_case_,snake_case_ ): return EarlyStopping( monitor=f'''val_{metric}''',mode="""min""" if """loss""" in metric else """max""",patience=snake_case_,verbose=snake_case_,) class lowercase ( pl.Callback ): def a__ ( self , _a , _a ) -> Optional[Any]: _A : List[Any] = {F'''lr_group_{i}''': param["""lr"""] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(_a ) @rank_zero_only def a__ ( self , _a , _a , _a , _a=True ) -> None: logger.info(F'''***** {type_path} results at step {trainer.global_step:05d} *****''' ) _A : int = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["""log""", """progress_bar""", """preds"""]} ) # Log results _A : Dict = Path(pl_module.hparams.output_dir ) if type_path == "test": _A : List[Any] = od / """test_results.txt""" _A : List[Any] = od / """test_generations.txt""" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _A : Optional[int] = od / F'''{type_path}_results/{trainer.global_step:05d}.txt''' _A : int = od / F'''{type_path}_generations/{trainer.global_step:05d}.txt''' results_file.parent.mkdir(exist_ok=_a ) generations_file.parent.mkdir(exist_ok=_a ) with open(_a , """a+""" ) as writer: for key in sorted(_a ): if key in ["log", "progress_bar", "preds"]: continue _A : List[Any] = metrics[key] if isinstance(_a , torch.Tensor ): _A : str = val.item() _A : str = F'''{key}: {val:.6f}\n''' writer.write(_a ) if not save_generations: return if "preds" in metrics: _A : List[Any] = """\n""".join(metrics["""preds"""] ) generations_file.open("""w+""" ).write(_a ) @rank_zero_only def a__ ( self , _a , _a ) -> str: try: _A : int = pl_module.model.model.num_parameters() except AttributeError: _A : str = pl_module.model.num_parameters() _A : Optional[int] = count_trainable_parameters(_a ) # mp stands for million parameters trainer.logger.log_metrics({"""n_params""": npars, """mp""": npars / 1e6, """grad_mp""": n_trainable_pars / 1e6} ) @rank_zero_only def a__ ( self , _a , _a ) -> Optional[int]: save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_a , _a , """test""" ) @rank_zero_only def a__ ( self , _a , _a ) -> Tuple: save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
343
1
from __future__ import annotations import os from collections.abc import Mapping _snake_case = tuple[int, int] class lowercase : def __init__( self , _a , _a ) -> None: _A : set[int] = vertices _A : dict[EdgeT, int] = { (min(_a ), max(_a )): weight for edge, weight in edges.items() } def a__ ( self , _a , _a ) -> None: self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) _A : str = weight def a__ ( self ) -> Graph: _A : Graph = Graph({min(self.vertices )} , {} ) _A : EdgeT _A : int _A : EdgeT _A : int while len(subgraph.vertices ) < len(self.vertices ): _A : List[Any] = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: _A : Dict = edge _A : Optional[Any] = weight subgraph.add_edge(_a , _a ) return subgraph def lowerCAmelCase_ ( snake_case_ = "p107_network.txt" ): _A : str = os.path.abspath(os.path.dirname(snake_case_ ) ) _A : str = os.path.join(snake_case_,snake_case_ ) _A : dict[EdgeT, int] = {} _A : list[str] _A : int _A : int with open(snake_case_ ) as f: _A : Dict = f.read().strip().split("""\n""" ) _A : Union[str, Any] = [line.split(""",""" ) for line in data] for edgea in range(1,len(snake_case_ ) ): for edgea in range(snake_case_ ): if adjaceny_matrix[edgea][edgea] != "-": _A : int = int(adjaceny_matrix[edgea][edgea] ) _A : Graph = Graph(set(range(len(snake_case_ ) ) ),snake_case_ ) _A : Graph = graph.prims_algorithm() _A : int = sum(graph.edges.values() ) _A : int = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(f"""{solution() = }""")
343
from __future__ import annotations from collections.abc import Callable _snake_case = list[list[float | int]] def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : int = len(snake_case_ ) _A : Matrix = [[0 for _ in range(size + 1 )] for _ in range(snake_case_ )] _A : int _A : int _A : int _A : int _A : int _A : float for row in range(snake_case_ ): for col in range(snake_case_ ): _A : Dict = matrix[row][col] _A : List[Any] = vector[row][0] _A : List[Any] = 0 _A : Optional[Any] = 0 while row < size and col < size: # pivoting _A : Any = max((abs(augmented[rowa][col] ), rowa) for rowa in range(snake_case_,snake_case_ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: _A , _A : Optional[Any] = augmented[pivot_row], augmented[row] for rowa in range(row + 1,snake_case_ ): _A : str = augmented[rowa][col] / augmented[row][col] _A : List[Any] = 0 for cola in range(col + 1,size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1,snake_case_ ): for row in range(snake_case_ ): _A : int = augmented[row][col] / augmented[col][col] for cola in range(snake_case_,size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row],10 )] for row in range(snake_case_ ) ] def lowerCAmelCase_ ( snake_case_ ): _A : int = len(snake_case_ ) _A : Matrix = [[0 for _ in range(snake_case_ )] for _ in range(snake_case_ )] _A : Matrix = [[0] for _ in range(snake_case_ )] _A : Matrix _A : int _A : int _A : int for x_val, y_val in enumerate(snake_case_ ): for col in range(snake_case_ ): _A : str = (x_val + 1) ** (size - col - 1) _A : List[str] = y_val _A : Any = solve(snake_case_,snake_case_ ) def interpolated_func(snake_case_ ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(snake_case_ ) ) return interpolated_func def lowerCAmelCase_ ( snake_case_ ): return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def lowerCAmelCase_ ( snake_case_ = question_function,snake_case_ = 10 ): _A : list[int] = [func(snake_case_ ) for x_val in range(1,order + 1 )] _A : list[Callable[[int], int]] = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1,order + 1 ) ] _A : int = 0 _A : Callable[[int], int] _A : int for poly in polynomials: _A : Optional[int] = 1 while func(snake_case_ ) == poly(snake_case_ ): x_val += 1 ret += poly(snake_case_ ) return ret if __name__ == "__main__": print(f"""{solution() = }""")
343
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig _snake_case = logging.get_logger(__name__) _snake_case = { "Intel/dpt-large": "https://huggingface.co/Intel/dpt-large/resolve/main/config.json", # See all DPT models at https://huggingface.co/models?filter=dpt } class lowercase ( UpperCamelCase__ ): _a = "dpt" def __init__( self , _a=768 , _a=12 , _a=12 , _a=3072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1e-12 , _a=384 , _a=16 , _a=3 , _a=False , _a=True , _a=[2, 5, 8, 11] , _a="project" , _a=[4, 2, 1, 0.5] , _a=[96, 192, 384, 768] , _a=256 , _a=-1 , _a=False , _a=True , _a=0.4 , _a=255 , _a=0.1 , _a=[1, 1024, 24, 24] , _a=[0, 1] , _a=None , **_a , ) -> Dict: super().__init__(**_a ) _A : List[str] = hidden_size _A : Tuple = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("""Initializing the config with a `BiT` backbone.""" ) _A : List[Any] = { """global_padding""": """same""", """layer_type""": """bottleneck""", """depths""": [3, 4, 9], """out_features""": ["""stage1""", """stage2""", """stage3"""], """embedding_dynamic_padding""": True, } _A : str = BitConfig(**_a ) elif isinstance(_a , _a ): logger.info("""Initializing the config with a `BiT` backbone.""" ) _A : Union[str, Any] = BitConfig(**_a ) elif isinstance(_a , _a ): _A : Optional[Any] = backbone_config else: raise ValueError( F'''backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.''' ) _A : int = backbone_featmap_shape _A : List[Any] = neck_ignore_stages if readout_type != "project": raise ValueError("""Readout type must be 'project' when using `DPT-hybrid` mode.""" ) else: _A : Tuple = None _A : Optional[int] = None _A : Any = [] _A : Union[str, Any] = num_hidden_layers _A : Optional[int] = num_attention_heads _A : Optional[int] = intermediate_size _A : str = hidden_act _A : List[str] = hidden_dropout_prob _A : Union[str, Any] = attention_probs_dropout_prob _A : Any = initializer_range _A : Union[str, Any] = layer_norm_eps _A : Any = image_size _A : List[Any] = patch_size _A : Tuple = num_channels _A : int = qkv_bias _A : str = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("""Readout_type must be one of ['ignore', 'add', 'project']""" ) _A : str = readout_type _A : int = reassemble_factors _A : Optional[int] = neck_hidden_sizes _A : Tuple = fusion_hidden_size _A : Optional[int] = head_in_index _A : int = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) _A : str = use_auxiliary_head _A : Optional[int] = auxiliary_loss_weight _A : Optional[int] = semantic_loss_ignore_index _A : Dict = semantic_classifier_dropout def a__ ( self ) -> Optional[Any]: _A : str = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: _A : List[Any] = self.backbone_config.to_dict() _A : str = self.__class__.model_type return output
343
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup _snake_case = "https://www.indeed.co.in/jobs?q=mobile+app+development&l=" def lowerCAmelCase_ ( snake_case_ = "mumbai" ): _A : Optional[Any] = BeautifulSoup(requests.get(url + location ).content,"""html.parser""" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("""div""",attrs={"""data-tn-component""": """organicJob"""} ): _A : Tuple = job.find("""a""",attrs={"""data-tn-element""": """jobTitle"""} ).text.strip() _A : Optional[int] = job.find("""span""",{"""class""": """company"""} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs("Bangalore"), 1): print(f"""Job {i:>2} is {job[0]} at {job[1]}""")
343
1
import colorsys from PIL import Image # type: ignore def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : Dict = x _A : Optional[Any] = y for step in range(snake_case_ ): # noqa: B007 _A : List[Any] = a * a - b * b + x _A : str = 2 * a * b + y _A : int = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def lowerCAmelCase_ ( snake_case_ ): if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def lowerCAmelCase_ ( snake_case_ ): if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255 ) for i in colorsys.hsv_to_rgb(snake_case_,1,1 ) ) def lowerCAmelCase_ ( snake_case_ = 800,snake_case_ = 600,snake_case_ = -0.6,snake_case_ = 0,snake_case_ = 3.2,snake_case_ = 50,snake_case_ = True,): _A : Union[str, Any] = Image.new("""RGB""",(image_width, image_height) ) _A : List[str] = img.load() # loop through the image-coordinates for image_x in range(snake_case_ ): for image_y in range(snake_case_ ): # determine the figure-coordinates based on the image-coordinates _A : Dict = figure_width / image_width * image_height _A : Optional[int] = figure_center_x + (image_x / image_width - 0.5) * figure_width _A : Union[str, Any] = figure_center_y + (image_y / image_height - 0.5) * figure_height _A : Optional[int] = get_distance(snake_case_,snake_case_,snake_case_ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: _A : Optional[Any] = get_color_coded_rgb(snake_case_ ) else: _A : Any = get_black_and_white_rgb(snake_case_ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure _snake_case = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
343
from __future__ import annotations from decimal import Decimal from numpy import array def lowerCAmelCase_ ( snake_case_ ): _A : Tuple = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(snake_case_ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix _A : List[Any] = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creates a copy of the matrix with swapped positions of the elements _A : Tuple = [[0.0, 0.0], [0.0, 0.0]] _A , _A : List[str] = matrix[1][1], matrix[0][0] _A , _A : List[str] = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(snake_case_ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(snake_case_ ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule _A : List[str] = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creating cofactor matrix _A : List[Any] = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] _A : Union[str, Any] = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) _A : Optional[Any] = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) _A : Any = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) _A : List[Any] = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) _A : int = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) _A : Union[str, Any] = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) _A : Any = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) _A : List[str] = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) _A : Optional[int] = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) _A : List[Any] = array(snake_case_ ) for i in range(3 ): for j in range(3 ): _A : List[str] = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix _A : Union[str, Any] = array(snake_case_ ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(snake_case_ ) # Calculate the inverse of the matrix return [[float(d(snake_case_ ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError("""Please provide a matrix of size 2x2 or 3x3.""" )
343
1
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging _snake_case = logging.get_logger(__name__) class lowercase ( UpperCamelCase__ ): _a = ["pixel_values"] def __init__( self , _a = True , _a = 1 / 255 , _a = True , _a = 8 , **_a , ) -> None: super().__init__(**_a ) _A : Tuple = do_rescale _A : Optional[int] = rescale_factor _A : Tuple = do_pad _A : Tuple = pad_size def a__ ( self , _a , _a , _a = None , **_a ) -> np.ndarray: return rescale(_a , scale=_a , data_format=_a , **_a ) def a__ ( self , _a , _a , _a = None ) -> Optional[Any]: _A , _A : Dict = get_image_size(_a ) _A : List[str] = (old_height // size + 1) * size - old_height _A : Dict = (old_width // size + 1) * size - old_width return pad(_a , ((0, pad_height), (0, pad_width)) , mode="""symmetric""" , data_format=_a ) def a__ ( self , _a , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , **_a , ) -> Any: _A : List[str] = do_rescale if do_rescale is not None else self.do_rescale _A : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor _A : Optional[int] = do_pad if do_pad is not None else self.do_pad _A : Any = pad_size if pad_size is not None else self.pad_size _A : List[str] = 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_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) # All transformations expect numpy arrays. _A : str = [to_numpy_array(_a ) for image in images] if do_rescale: _A : Any = [self.rescale(image=_a , scale=_a ) for image in images] if do_pad: _A : Any = [self.pad(_a , size=_a ) for image in images] _A : Union[str, Any] = [to_channel_dimension_format(_a , _a ) for image in images] _A : Optional[Any] = {"""pixel_values""": images} return BatchFeature(data=_a , tensor_type=_a )
343
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class lowercase ( UpperCamelCase__ ): _a = 42 class lowercase ( UpperCamelCase__,UpperCamelCase__ ): @register_to_config def __init__( self , _a = 32 , _a = 64 , _a = 20 , _a = 768 , _a=77 , _a=4 , _a = 0.0 , _a = "silu" , _a = None , _a = None , _a = "linear" , _a = "prd" , _a = None , _a = None , _a = None , ) -> Any: super().__init__() _A : int = num_attention_heads _A : Union[str, Any] = attention_head_dim _A : Tuple = num_attention_heads * attention_head_dim _A : Any = additional_embeddings _A : Any = time_embed_dim or inner_dim _A : List[str] = embedding_proj_dim or embedding_dim _A : Optional[int] = clip_embed_dim or embedding_dim _A : Union[str, Any] = Timesteps(_a , _a , 0 ) _A : str = TimestepEmbedding(_a , _a , out_dim=_a , act_fn=_a ) _A : Dict = nn.Linear(_a , _a ) if embedding_proj_norm_type is None: _A : int = None elif embedding_proj_norm_type == "layer": _A : Optional[Any] = nn.LayerNorm(_a ) else: raise ValueError(F'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}''' ) _A : Optional[Any] = nn.Linear(_a , _a ) if encoder_hid_proj_type is None: _A : Union[str, Any] = None elif encoder_hid_proj_type == "linear": _A : Tuple = nn.Linear(_a , _a ) else: raise ValueError(F'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}''' ) _A : List[str] = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , _a ) ) if added_emb_type == "prd": _A : str = nn.Parameter(torch.zeros(1 , 1 , _a ) ) elif added_emb_type is None: _A : Union[str, Any] = None else: raise ValueError( F'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.''' ) _A : int = nn.ModuleList( [ BasicTransformerBlock( _a , _a , _a , dropout=_a , activation_fn="""gelu""" , attention_bias=_a , ) for d in range(_a ) ] ) if norm_in_type == "layer": _A : Union[str, Any] = nn.LayerNorm(_a ) elif norm_in_type is None: _A : Tuple = None else: raise ValueError(F'''Unsupported norm_in_type: {norm_in_type}.''' ) _A : int = nn.LayerNorm(_a ) _A : str = nn.Linear(_a , _a ) _A : Any = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -10000.0 ) causal_attention_mask.triu_(1 ) _A : Optional[int] = causal_attention_mask[None, ...] self.register_buffer("""causal_attention_mask""" , _a , persistent=_a ) _A : Tuple = nn.Parameter(torch.zeros(1 , _a ) ) _A : Dict = nn.Parameter(torch.zeros(1 , _a ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def a__ ( self ) -> Dict[str, AttentionProcessor]: _A : List[str] = {} def fn_recursive_add_processors(_a , _a , _a ): if hasattr(_a , """set_processor""" ): _A : Tuple = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F'''{name}.{sub_name}''' , _a , _a ) return processors for name, module in self.named_children(): fn_recursive_add_processors(_a , _a , _a ) return processors def a__ ( self , _a ) -> List[str]: _A : Optional[int] = len(self.attn_processors.keys() ) if isinstance(_a , _a ) and len(_a ) != count: raise ValueError( F'''A dict of processors was passed, but the number of processors {len(_a )} does not match the''' F''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''' ) def fn_recursive_attn_processor(_a , _a , _a ): if hasattr(_a , """set_processor""" ): if not isinstance(_a , _a ): module.set_processor(_a ) else: module.set_processor(processor.pop(F'''{name}.processor''' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F'''{name}.{sub_name}''' , _a , _a ) for name, module in self.named_children(): fn_recursive_attn_processor(_a , _a , _a ) def a__ ( self ) -> Union[str, Any]: self.set_attn_processor(AttnProcessor() ) def a__ ( self , _a , _a , _a , _a = None , _a = None , _a = True , ) -> Optional[Any]: _A : Tuple = hidden_states.shape[0] _A : List[Any] = timestep if not torch.is_tensor(_a ): _A : Dict = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(_a ) and len(timesteps.shape ) == 0: _A : Tuple = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML _A : Optional[int] = timesteps * torch.ones(_a , dtype=timesteps.dtype , device=timesteps.device ) _A : Dict = self.time_proj(_a ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. _A : Tuple = timesteps_projected.to(dtype=self.dtype ) _A : List[Any] = self.time_embedding(_a ) if self.embedding_proj_norm is not None: _A : Dict = self.embedding_proj_norm(_a ) _A : List[Any] = self.embedding_proj(_a ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: _A : List[Any] = self.encoder_hidden_states_proj(_a ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""" ) _A : Optional[int] = self.proj_in(_a ) _A : Optional[int] = self.positional_embedding.to(hidden_states.dtype ) _A : Union[str, Any] = [] _A : List[str] = 0 if encoder_hidden_states is not None: additional_embeds.append(_a ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: _A : List[str] = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: _A : List[str] = hidden_states[:, None, :] _A : Dict = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: _A : Optional[int] = self.prd_embedding.to(hidden_states.dtype ).expand(_a , -1 , -1 ) additional_embeds.append(_a ) _A : str = torch.cat( _a , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens _A : Dict = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: _A : Union[str, Any] = F.pad( _a , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) _A : Optional[Any] = hidden_states + positional_embeddings if attention_mask is not None: _A : Optional[Any] = (1 - attention_mask.to(hidden_states.dtype )) * -10000.0 _A : List[Any] = F.pad(_a , (0, self.additional_embeddings) , value=0.0 ) _A : Optional[Any] = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) _A : int = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: _A : str = self.norm_in(_a ) for block in self.transformer_blocks: _A : List[Any] = block(_a , attention_mask=_a ) _A : Any = self.norm_out(_a ) if self.prd_embedding is not None: _A : int = hidden_states[:, -1] else: _A : Any = hidden_states[:, additional_embeddings_len:] _A : Union[str, Any] = self.proj_to_clip_embeddings(_a ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=_a ) def a__ ( self , _a ) -> Tuple: _A : List[Any] = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
343
1
import inspect import unittest from transformers import BitConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class lowercase : def __init__( self , _a , _a=3 , _a=32 , _a=3 , _a=10 , _a=[8, 16, 32, 64] , _a=[1, 1, 2, 1] , _a=True , _a=True , _a="relu" , _a=3 , _a=None , _a=["stage2", "stage3", "stage4"] , _a=[2, 3, 4] , _a=1 , ) -> Tuple: _A : Dict = parent _A : int = batch_size _A : str = image_size _A : Optional[Any] = num_channels _A : Optional[Any] = embeddings_size _A : List[str] = hidden_sizes _A : Any = depths _A : Dict = is_training _A : List[str] = use_labels _A : Any = hidden_act _A : Dict = num_labels _A : Tuple = scope _A : List[Any] = len(_a ) _A : List[str] = out_features _A : Tuple = out_indices _A : int = num_groups def a__ ( self ) -> int: _A : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A : Tuple = None if self.use_labels: _A : int = ids_tensor([self.batch_size] , self.num_labels ) _A : Union[str, Any] = self.get_config() return config, pixel_values, labels def a__ ( self ) -> str: return BitConfig( 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 , out_features=self.out_features , out_indices=self.out_indices , num_groups=self.num_groups , ) def a__ ( self , _a , _a , _a ) -> Union[str, Any]: _A : Tuple = BitModel(config=_a ) model.to(_a ) model.eval() _A : str = model(_a ) 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 , _a ) -> Dict: _A : str = self.num_labels _A : List[Any] = BitForImageClassification(_a ) model.to(_a ) model.eval() _A : Union[str, Any] = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a__ ( self , _a , _a , _a ) -> List[Any]: _A : Optional[int] = BitBackbone(config=_a ) model.to(_a ) model.eval() _A : int = model(_a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None _A : Optional[int] = None _A : Tuple = BitBackbone(config=_a ) model.to(_a ) model.eval() _A : Union[str, Any] = model(_a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def a__ ( self ) -> Union[str, Any]: _A : List[Any] = self.prepare_config_and_inputs() _A , _A , _A : List[Any] = config_and_inputs _A : int = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowercase ( UpperCamelCase__,UpperCamelCase__,unittest.TestCase ): _a = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () _a = ( {"feature-extraction": BitModel, "image-classification": BitForImageClassification} if is_torch_available() else {} ) _a = False _a = False _a = False _a = False _a = False def a__ ( self ) -> Optional[Any]: _A : Optional[int] = BitModelTester(self ) _A : Optional[int] = ConfigTester(self , config_class=_a , has_text_modality=_a ) def a__ ( self ) -> int: 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 ) -> Tuple: return @unittest.skip(reason="""Bit does not output attentions""" ) def a__ ( self ) -> int: pass @unittest.skip(reason="""Bit does not use inputs_embeds""" ) def a__ ( self ) -> List[str]: pass @unittest.skip(reason="""Bit does not support input and output embeddings""" ) def a__ ( self ) -> Dict: pass def a__ ( self ) -> Tuple: _A , _A : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : Union[str, Any] = model_class(_a ) _A : Union[str, Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A : str = [*signature.parameters.keys()] _A : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def a__ ( self ) -> Tuple: _A : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def a__ ( self ) -> Optional[int]: _A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_a ) def a__ ( self ) -> Any: _A , _A : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : Union[str, Any] = model_class(config=_a ) for name, module in model.named_modules(): if isinstance(_a , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) def a__ ( self ) -> Tuple: def check_hidden_states_output(_a , _a , _a ): _A : Optional[Any] = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): _A : List[str] = model(**self._prepare_for_class(_a , _a ) ) _A : Optional[int] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _A : Union[str, Any] = self.model_tester.num_stages self.assertEqual(len(_a ) , expected_num_stages + 1 ) # Bit's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) _A , _A : str = self.model_tester.prepare_config_and_inputs_for_common() _A : Union[str, Any] = ["""preactivation""", """bottleneck"""] for model_class in self.all_model_classes: for layer_type in layers_type: _A : Optional[Any] = layer_type _A : Dict = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _A : Any = True check_hidden_states_output(_a , _a , _a ) @unittest.skip(reason="""Bit does not use feedforward chunking""" ) def a__ ( self ) -> str: pass def a__ ( self ) -> Optional[int]: _A : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @slow def a__ ( self ) -> Dict: for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _A : Tuple = BitModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowerCAmelCase_ ( ): _A : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class lowercase ( unittest.TestCase ): @cached_property def a__ ( self ) -> Optional[Any]: return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def a__ ( self ) -> str: _A : Optional[int] = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(_a ) _A : Tuple = self.default_image_processor _A : Optional[int] = prepare_img() _A : Union[str, Any] = image_processor(images=_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): _A : int = model(**_a ) # verify the logits _A : Union[str, Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _a ) _A : str = torch.tensor([[-0.6526, -0.5263, -1.4398]] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) ) @require_torch class lowercase ( UpperCamelCase__,unittest.TestCase ): _a = (BitBackbone,) if is_torch_available() else () _a = BitConfig _a = False def a__ ( self ) -> int: _A : Tuple = BitModelTester(self )
343
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : Any = None if token is not None: _A : int = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} _A : Any = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' _A : Union[str, Any] = requests.get(snake_case_,headers=snake_case_ ).json() _A : str = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) _A : int = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(snake_case_ ): _A : List[str] = requests.get(url + f'''&page={i + 2}''',headers=snake_case_ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : int = None if token is not None: _A : List[str] = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} _A : str = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100''' _A : Optional[Any] = requests.get(snake_case_,headers=snake_case_ ).json() _A : Any = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) _A : Tuple = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(snake_case_ ): _A : List[Any] = requests.get(url + f'''&page={i + 2}''',headers=snake_case_ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_ ): _A : Dict = None if token is not None: _A : int = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} _A : Tuple = requests.get(snake_case_,headers=snake_case_,allow_redirects=snake_case_ ) _A : Tuple = result.headers["""Location"""] _A : Union[str, Any] = requests.get(snake_case_,allow_redirects=snake_case_ ) _A : Dict = os.path.join(snake_case_,f'''{artifact_name}.zip''' ) with open(snake_case_,"""wb""" ) as fp: fp.write(response.content ) def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : List[str] = [] _A : int = [] _A : Tuple = None with zipfile.ZipFile(snake_case_ ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case_ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(snake_case_ ) as f: for line in f: _A : Any = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs _A : Dict = line[: line.index(""": """ )] _A : Dict = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed _A : List[str] = line[len("""FAILED """ ) :] failed_tests.append(snake_case_ ) elif filename == "job_name.txt": _A : Optional[int] = line if len(snake_case_ ) != len(snake_case_ ): raise ValueError( f'''`errors` and `failed_tests` should have the same number of elements. Got {len(snake_case_ )} for `errors` ''' f'''and {len(snake_case_ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some''' """ problem.""" ) _A : Any = None if job_name and job_links: _A : Dict = job_links.get(snake_case_,snake_case_ ) # A list with elements of the form (line of error, error, failed test) _A : Optional[int] = [x + [y] + [job_link] for x, y in zip(snake_case_,snake_case_ )] return result def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : Dict = [] _A : Optional[int] = [os.path.join(snake_case_,snake_case_ ) for p in os.listdir(snake_case_ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(snake_case_,job_links=snake_case_ ) ) return errors def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : Dict = Counter() counter.update([x[1] for x in logs] ) _A : Tuple = counter.most_common() _A : Tuple = {} for error, count in counts: if error_filter is None or error not in error_filter: _A : str = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} _A : Union[str, Any] = dict(sorted(r.items(),key=lambda snake_case_ : item[1]["count"],reverse=snake_case_ ) ) return r def lowerCAmelCase_ ( snake_case_ ): _A : Union[str, Any] = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): _A : Dict = test.split("""/""" )[2] else: _A : str = None return test def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : str = [(x[0], x[1], get_model(x[2] )) for x in logs] _A : Union[str, Any] = [x for x in logs if x[2] is not None] _A : Optional[Any] = {x[2] for x in logs} _A : List[Any] = {} for test in tests: _A : Any = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) _A : Union[str, Any] = counter.most_common() _A : Any = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} _A : str = sum(error_counts.values() ) if n_errors > 0: _A : Optional[int] = {"""count""": n_errors, """errors""": error_counts} _A : Union[str, Any] = dict(sorted(r.items(),key=lambda snake_case_ : item[1]["count"],reverse=snake_case_ ) ) return r def lowerCAmelCase_ ( snake_case_ ): _A : Optional[int] = """| no. | error | status |""" _A : List[Any] = """|-:|:-|:-|""" _A : List[Any] = [header, sep] for error in reduced_by_error: _A : List[str] = reduced_by_error[error]["""count"""] _A : List[Any] = f'''| {count} | {error[:100]} | |''' lines.append(snake_case_ ) return "\n".join(snake_case_ ) def lowerCAmelCase_ ( snake_case_ ): _A : List[Any] = """| model | no. of errors | major error | count |""" _A : Optional[Any] = """|-:|-:|-:|-:|""" _A : Union[str, Any] = [header, sep] for model in reduced_by_model: _A : Dict = reduced_by_model[model]["""count"""] _A , _A : str = list(reduced_by_model[model]["""errors"""].items() )[0] _A : Union[str, Any] = f'''| {model} | {count} | {error[:60]} | {_count} |''' lines.append(snake_case_ ) return "\n".join(snake_case_ ) if __name__ == "__main__": _snake_case = 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.") _snake_case = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) _snake_case = get_job_links(args.workflow_run_id, token=args.token) _snake_case = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: _snake_case = k.find(" / ") _snake_case = k[index + len(" / ") :] _snake_case = v with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) _snake_case = 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) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) _snake_case = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error _snake_case = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors _snake_case = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) _snake_case = reduce_by_error(errors) _snake_case = reduce_by_model(errors) _snake_case = make_github_table(reduced_by_error) _snake_case = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: fp.write(sa) with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: fp.write(sa)
343
1
import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() _snake_case = logging.get_logger(__name__) def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : int = RobertaPreLayerNormConfig.from_pretrained( snake_case_,architectures=["""RobertaPreLayerNormForMaskedLM"""] ) # convert state_dict _A : int = torch.load(hf_hub_download(repo_id=snake_case_,filename="""pytorch_model.bin""" ) ) _A : Dict = {} for tensor_key, tensor_value in original_state_dict.items(): # The transformer implementation gives the model a unique name, rather than overwiriting 'roberta' if tensor_key.startswith("""roberta.""" ): _A : List[str] = """roberta_prelayernorm.""" + tensor_key[len("""roberta.""" ) :] # The original implementation contains weights which are not used, remove them from the state_dict if tensor_key.endswith(""".self.LayerNorm.weight""" ) or tensor_key.endswith(""".self.LayerNorm.bias""" ): continue _A : int = tensor_value _A : int = RobertaPreLayerNormForMaskedLM.from_pretrained( pretrained_model_name_or_path=snake_case_,config=snake_case_,state_dict=snake_case_ ) model.save_pretrained(snake_case_ ) # convert tokenizer _A : Optional[Any] = AutoTokenizer.from_pretrained(snake_case_ ) tokenizer.save_pretrained(snake_case_ ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint-repo", default=None, type=str, required=True, help="Path the official PyTorch dump, e.g. 'andreasmadsen/efficient_mlm_m0.40'.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) _snake_case = parser.parse_args() convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)
343
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class lowercase ( unittest.TestCase ): def a__ ( self ) -> List[str]: debug_launcher(test_script.main ) def a__ ( self ) -> Any: debug_launcher(test_ops.main )
343
1
import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def lowerCAmelCase_ ( *snake_case_ ): if not isinstance(_UpperCAmelCase,_UpperCAmelCase ): _A : str = list(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): _A : Tuple = None gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() return objects def lowerCAmelCase_ ( snake_case_ ): _A : Optional[Any] = [ 'CUDA out of memory.', # CUDA OOM 'cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.', # CUDNN SNAFU 'DefaultCPUAllocator: can\'t allocate memory', # CPU OOM ] if isinstance(_UpperCAmelCase,_UpperCAmelCase ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def lowerCAmelCase_ ( snake_case_ = None,snake_case_ = 128 ): if function is None: return functools.partial(_UpperCAmelCase,starting_batch_size=_UpperCAmelCase ) _A : Optional[Any] = starting_batch_size def decorator(*snake_case_,**snake_case_ ): nonlocal batch_size gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() _A : str = list(inspect.signature(_UpperCAmelCase ).parameters.keys() ) # Guard against user error if len(_UpperCAmelCase ) < (len(_UpperCAmelCase ) + 1): _A : Dict = ', '.join([f'''{arg}={value}''' for arg, value in zip(params[1:],args[1:] )] ) raise TypeError( f'''Batch size was passed into `{function.__name__}` as the first argument when called.''' f'''Remove this as the decorator already does so: `{function.__name__}({arg_str})`''' ) while True: if batch_size == 0: raise RuntimeError("""No executable batch size found, reached zero.""" ) try: return function(_UpperCAmelCase,*_UpperCAmelCase,**_UpperCAmelCase ) except Exception as e: if should_reduce_batch_size(_UpperCAmelCase ): gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() batch_size //= 2 else: raise return decorator
350
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _snake_case = logging.get_logger(__name__) _snake_case = { "microsoft/resnet-50": "https://huggingface.co/microsoft/resnet-50/blob/main/config.json", } class lowercase ( UpperCamelCase__,UpperCamelCase__ ): _a = "resnet" _a = ["basic", "bottleneck"] def __init__( self , _a=3 , _a=64 , _a=[256, 512, 1024, 2048] , _a=[3, 4, 6, 3] , _a="bottleneck" , _a="relu" , _a=False , _a=None , _a=None , **_a , ) -> int: super().__init__(**_a ) if layer_type not in self.layer_types: raise ValueError(F'''layer_type={layer_type} is not one of {",".join(self.layer_types )}''' ) _A : Optional[Any] = num_channels _A : List[Any] = embedding_size _A : int = hidden_sizes _A : Union[str, Any] = depths _A : Optional[int] = layer_type _A : Any = hidden_act _A : List[Any] = downsample_in_first_stage _A : int = ["""stem"""] + [F'''stage{idx}''' for idx in range(1 , len(_a ) + 1 )] _A , _A : str = get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names ) class lowercase ( UpperCamelCase__ ): _a = version.parse("1.11" ) @property def a__ ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def a__ ( self ) -> float: return 1e-3
343
0
import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} _snake_case = { "vocab_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json" ), }, "merges_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt" ), }, } _snake_case = { "allenai/longformer-base-4096": 4096, "allenai/longformer-large-4096": 4096, "allenai/longformer-large-4096-finetuned-triviaqa": 4096, "allenai/longformer-base-4096-extra.pos.embd.only": 4096, "allenai/longformer-large-4096-extra.pos.embd.only": 4096, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowerCAmelCase_ ( ): _A : int = ( list(range(ord("""!""" ),ord("""~""" ) + 1 ) ) + list(range(ord("""¡""" ),ord("""¬""" ) + 1 ) ) + list(range(ord("""®""" ),ord("""ÿ""" ) + 1 ) ) ) _A : Optional[int] = bs[:] _A : int = 0 for b in range(2**8 ): if b not in bs: bs.append(lowercase__ ) cs.append(2**8 + n ) n += 1 _A : Any = [chr(lowercase__ ) for n in cs] return dict(zip(lowercase__,lowercase__ ) ) def lowerCAmelCase_ ( snake_case_ ): _A : str = set() _A : List[Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _A : str = char return pairs class lowercase ( A__ ): _a = VOCAB_FILES_NAMES _a = PRETRAINED_VOCAB_FILES_MAP _a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = ["input_ids", "attention_mask"] def __init__( self , _a , _a , _a="replace" , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=False , **_a , ) -> int: _A : List[Any] = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else bos_token _A : Optional[Any] = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else eos_token _A : List[str] = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else sep_token _A : List[str] = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else cls_token _A : str = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else unk_token _A : List[Any] = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else pad_token # Mask token behave like a normal word, i.e. include the space before it _A : List[Any] = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token super().__init__( errors=__A , bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , add_prefix_space=__A , **__A , ) with open(__A , encoding="""utf-8""" ) as vocab_handle: _A : Optional[Any] = json.load(__A ) _A : Optional[int] = {v: k for k, v in self.encoder.items()} _A : List[str] = errors # how to handle errors in decoding _A : Optional[Any] = bytes_to_unicode() _A : List[str] = {v: k for k, v in self.byte_encoder.items()} with open(__A , encoding="""utf-8""" ) as merges_handle: _A : Dict = merges_handle.read().split("""\n""" )[1:-1] _A : Optional[int] = [tuple(merge.split() ) for merge in bpe_merges] _A : Optional[int] = dict(zip(__A , range(len(__A ) ) ) ) _A : Dict = {} _A : Optional[Any] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions _A : Optional[int] = re.compile(R"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""" ) @property def a__ ( self ) -> Optional[int]: return len(self.encoder ) def a__ ( self ) -> Tuple: return dict(self.encoder , **self.added_tokens_encoder ) def a__ ( self , _a ) -> Union[str, Any]: if token in self.cache: return self.cache[token] _A : Dict = tuple(__A ) _A : Any = get_pairs(__A ) if not pairs: return token while True: _A : Tuple = min(__A , key=lambda _a : self.bpe_ranks.get(__A , float("""inf""" ) ) ) if bigram not in self.bpe_ranks: break _A : Dict = bigram _A : Tuple = [] _A : str = 0 while i < len(__A ): try: _A : Optional[Any] = word.index(__A , __A ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _A : List[Any] = j if word[i] == first and i < len(__A ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _A : Union[str, Any] = tuple(__A ) _A : Optional[int] = new_word if len(__A ) == 1: break else: _A : int = get_pairs(__A ) _A : Any = """ """.join(__A ) _A : Dict = word return word def a__ ( self , _a ) -> Optional[Any]: _A : Optional[Any] = [] for token in re.findall(self.pat , __A ): _A : List[Any] = """""".join( self.byte_encoder[b] for b in token.encode("""utf-8""" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__A ).split(""" """ ) ) return bpe_tokens def a__ ( self , _a ) -> Any: return self.encoder.get(__A , self.encoder.get(self.unk_token ) ) def a__ ( self , _a ) -> Tuple: return self.decoder.get(__A ) def a__ ( self , _a ) -> Optional[Any]: _A : List[Any] = """""".join(__A ) _A : Tuple = bytearray([self.byte_decoder[c] for c in text] ).decode("""utf-8""" , errors=self.errors ) return text def a__ ( self , _a , _a = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return _A : Dict = os.path.join( __A , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) _A : Optional[Any] = os.path.join( __A , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] ) with open(__A , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__A , ensure_ascii=__A ) + """\n""" ) _A : List[Any] = 0 with open(__A , """w""" , encoding="""utf-8""" ) as writer: writer.write("""#version: 0.2\n""" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _a : kv[1] ): if index != token_index: logger.warning( F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' """ Please check that the tokenizer is not corrupted!""" ) _A : Tuple = token_index writer.write(""" """.join(__A ) + """\n""" ) index += 1 return vocab_file, merge_file def a__ ( self , _a , _a = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _A : Optional[Any] = [self.cls_token_id] _A : Optional[int] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def a__ ( self , _a , _a = None , _a = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def a__ ( self , _a , _a = None ) -> List[int]: _A : List[str] = [self.sep_token_id] _A : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def a__ ( self , _a , _a=False , **_a ) -> List[Any]: _A : str = kwargs.pop("""add_prefix_space""" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__A ) > 0 and not text[0].isspace()): _A : int = """ """ + text return (text, kwargs)
351
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowerCAmelCase_ ( snake_case_,snake_case_ ): # Load checkpoint _A : Optional[int] = torch.load(snake_case_,map_location="""cpu""" ) _A : Any = chkpt["""model"""] # We have the base model one level deeper than the original XLM repository _A : Any = {} for k, v in state_dict.items(): if "pred_layer" in k: _A : Tuple = v else: _A : Dict = v _A : Optional[Any] = chkpt["""params"""] _A : Union[str, Any] = {n: v for n, v in config.items() if not isinstance(snake_case_,(torch.FloatTensor, numpy.ndarray) )} _A : str = chkpt["""dico_word2id"""] _A : Optional[Any] = {s + """</w>""" if s.find("""@@""" ) == -1 and i > 13 else s.replace("""@@""","""""" ): i for s, i in vocab.items()} # Save pytorch-model _A : Dict = pytorch_dump_folder_path + """/""" + WEIGHTS_NAME _A : Any = pytorch_dump_folder_path + """/""" + CONFIG_NAME _A : Optional[int] = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""vocab_file"""] print(f'''Save PyTorch model to {pytorch_weights_dump_path}''' ) torch.save(snake_case_,snake_case_ ) print(f'''Save configuration file to {pytorch_config_dump_path}''' ) with open(snake_case_,"""w""",encoding="""utf-8""" ) as f: f.write(json.dumps(snake_case_,indent=2 ) + """\n""" ) print(f'''Save vocab file to {pytorch_config_dump_path}''' ) with open(snake_case_,"""w""",encoding="""utf-8""" ) as f: f.write(json.dumps(snake_case_,indent=2 ) + """\n""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( "--xlm_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) _snake_case = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
343
0
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class lowercase ( _UpperCAmelCase ): _a = 42 _a = 42 class lowercase ( nn.Module ): _a = 42 _a = (1_6, 3_2, 9_6, 2_5_6) _a = jnp.floataa def a__ ( self ): _A : List[str] = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) _A : Dict = [] for i in range(len(self.block_out_channels ) - 1 ): _A : Dict = self.block_out_channels[i] _A : Tuple = self.block_out_channels[i + 1] _A : Union[str, Any] = nn.Conv( _UpperCAmelCase , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(_UpperCAmelCase ) _A : Union[str, Any] = nn.Conv( _UpperCAmelCase , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(_UpperCAmelCase ) _A : Optional[Any] = blocks _A : Tuple = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , _a ): _A : List[str] = self.conv_in(_UpperCAmelCase ) _A : Any = nn.silu(_UpperCAmelCase ) for block in self.blocks: _A : int = block(_UpperCAmelCase ) _A : str = nn.silu(_UpperCAmelCase ) _A : int = self.conv_out(_UpperCAmelCase ) return embedding @flax_register_to_config class lowercase ( nn.Module,_UpperCAmelCase,_UpperCAmelCase ): _a = 3_2 _a = 4 _a = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) _a = False _a = (3_2_0, 6_4_0, 1_2_8_0, 1_2_8_0) _a = 2 _a = 8 _a = None _a = 1_2_8_0 _a = 0.0 _a = False _a = jnp.floataa _a = True _a = 0 _a = "rgb" _a = (1_6, 3_2, 9_6, 2_5_6) def a__ ( self , _a ): # init input tensors _A : Union[str, Any] = (1, self.in_channels, self.sample_size, self.sample_size) _A : List[str] = jnp.zeros(_UpperCAmelCase , dtype=jnp.floataa ) _A : Optional[Any] = jnp.ones((1,) , dtype=jnp.intaa ) _A : str = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) _A : Optional[Any] = (1, 3, self.sample_size * 8, self.sample_size * 8) _A : int = jnp.zeros(_UpperCAmelCase , dtype=jnp.floataa ) _A : Any = jax.random.split(_UpperCAmelCase ) _A : str = {'''params''': params_rng, '''dropout''': dropout_rng} return self.init(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )["params"] def a__ ( self ): _A : int = self.block_out_channels _A : str = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. _A : int = self.num_attention_heads or self.attention_head_dim # input _A : Dict = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time _A : str = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) _A : int = FlaxTimestepEmbedding(_UpperCAmelCase , dtype=self.dtype ) _A : Optional[Any] = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) _A : int = self.only_cross_attention if isinstance(_UpperCAmelCase , _UpperCAmelCase ): _A : Dict = (only_cross_attention,) * len(self.down_block_types ) if isinstance(_UpperCAmelCase , _UpperCAmelCase ): _A : Dict = (num_attention_heads,) * len(self.down_block_types ) # down _A : str = [] _A : Optional[int] = [] _A : Tuple = block_out_channels[0] _A : Union[str, Any] = nn.Conv( _UpperCAmelCase , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(_UpperCAmelCase ) for i, down_block_type in enumerate(self.down_block_types ): _A : Optional[int] = output_channel _A : Any = block_out_channels[i] _A : Optional[Any] = i == len(_UpperCAmelCase ) - 1 if down_block_type == "CrossAttnDownBlock2D": _A : List[str] = FlaxCrossAttnDownBlockaD( in_channels=_UpperCAmelCase , out_channels=_UpperCAmelCase , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: _A : str = FlaxDownBlockaD( in_channels=_UpperCAmelCase , out_channels=_UpperCAmelCase , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(_UpperCAmelCase ) for _ in range(self.layers_per_block ): _A : Optional[int] = nn.Conv( _UpperCAmelCase , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(_UpperCAmelCase ) if not is_final_block: _A : Optional[int] = nn.Conv( _UpperCAmelCase , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(_UpperCAmelCase ) _A : str = down_blocks _A : Dict = controlnet_down_blocks # mid _A : Optional[Any] = block_out_channels[-1] _A : Dict = FlaxUNetMidBlockaDCrossAttn( in_channels=_UpperCAmelCase , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) _A : Any = nn.Conv( _UpperCAmelCase , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , _a , _a , _a , _a , _a = 1.0 , _a = True , _a = False , ): _A : Any = self.controlnet_conditioning_channel_order if channel_order == "bgr": _A : int = jnp.flip(_UpperCAmelCase , axis=1 ) # 1. time if not isinstance(_UpperCAmelCase , jnp.ndarray ): _A : str = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(_UpperCAmelCase , jnp.ndarray ) and len(timesteps.shape ) == 0: _A : Optional[int] = timesteps.astype(dtype=jnp.floataa ) _A : List[str] = jnp.expand_dims(_UpperCAmelCase , 0 ) _A : List[str] = self.time_proj(_UpperCAmelCase ) _A : List[Any] = self.time_embedding(_UpperCAmelCase ) # 2. pre-process _A : int = jnp.transpose(_UpperCAmelCase , (0, 2, 3, 1) ) _A : int = self.conv_in(_UpperCAmelCase ) _A : Any = jnp.transpose(_UpperCAmelCase , (0, 2, 3, 1) ) _A : Dict = self.controlnet_cond_embedding(_UpperCAmelCase ) sample += controlnet_cond # 3. down _A : Dict = (sample,) for down_block in self.down_blocks: if isinstance(_UpperCAmelCase , _UpperCAmelCase ): _A : List[str] = down_block(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , deterministic=not train ) else: _A : List[Any] = down_block(_UpperCAmelCase , _UpperCAmelCase , deterministic=not train ) down_block_res_samples += res_samples # 4. mid _A : int = self.mid_block(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , deterministic=not train ) # 5. contronet blocks _A : List[Any] = () for down_block_res_sample, controlnet_block in zip(_UpperCAmelCase , self.controlnet_down_blocks ): _A : Tuple = controlnet_block(_UpperCAmelCase ) controlnet_down_block_res_samples += (down_block_res_sample,) _A : Tuple = controlnet_down_block_res_samples _A : Optional[int] = self.controlnet_mid_block(_UpperCAmelCase ) # 6. scaling _A : List[Any] = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=_UpperCAmelCase , mid_block_res_sample=_UpperCAmelCase )
352
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowercase ( UpperCamelCase__ ): _a = ["image_processor", "tokenizer"] _a = "BlipImageProcessor" _a = ("BertTokenizer", "BertTokenizerFast") def __init__( self , _a , _a ) -> Any: _A : List[Any] = False super().__init__(_a , _a ) _A : Optional[int] = self.image_processor def __call__( self , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ) -> BatchEncoding: if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None: _A : Dict = self.tokenizer _A : Dict = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) return text_encoding # add pixel_values _A : int = self.image_processor(_a , return_tensors=_a ) if text is not None: _A : List[Any] = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) else: _A : int = None if text_encoding is not None: encoding_image_processor.update(_a ) return encoding_image_processor def a__ ( self , *_a , **_a ) -> Any: return self.tokenizer.batch_decode(*_a , **_a ) def a__ ( self , *_a , **_a ) -> List[str]: return self.tokenizer.decode(*_a , **_a ) @property def a__ ( self ) -> Optional[Any]: _A : Any = self.tokenizer.model_input_names _A : List[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
343
0
import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) _snake_case = logging.getLogger() def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : Any = """\n""".join(__lowerCAmelCase ) Path(__lowerCAmelCase ).open("""w""" ).writelines(__lowerCAmelCase ) _snake_case = "patrickvonplaten/t5-tiny-random" _snake_case = "sshleifer/bart-tiny-random" _snake_case = "sshleifer/tiny-mbart" _snake_case = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class lowercase ( A__ ): def a__ ( self , _a ) -> Any: _A : Optional[Any] = Path(self.get_auto_remove_tmp_dir() ) / """utest_input.source""" _A : List[str] = input_file_name.parent / """utest_output.txt""" assert not output_file_name.exists() _A : List[str] = [""" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."""] _dump_articles(__snake_case , __snake_case ) _A : Union[str, Any] = str(Path(self.get_auto_remove_tmp_dir() ) / """scores.json""" ) _A : Optional[int] = """translation_en_to_de""" if model == T5_TINY else """summarization""" _A : Optional[int] = F''' run_eval_search.py {model} {input_file_name} {output_file_name} --score_path {score_path} --task {task} --num_beams 2 --length_penalty 2.0 '''.split() with patch.object(__snake_case , """argv""" , __snake_case ): run_generate() assert Path(__snake_case ).exists() # os.remove(Path(output_file_name)) def a__ ( self ) -> Union[str, Any]: self.run_eval_tester(__snake_case ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def a__ ( self , _a ) -> Dict: self.run_eval_tester(__snake_case ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def a__ ( self , _a ) -> Any: _A : List[str] = Path(self.get_auto_remove_tmp_dir() ) / """utest_input.source""" _A : Optional[int] = input_file_name.parent / """utest_output.txt""" assert not output_file_name.exists() _A : Dict = { """en""": ["""Machine learning is great, isn't it?""", """I like to eat bananas""", """Tomorrow is another great day!"""], """de""": [ """Maschinelles Lernen ist großartig, oder?""", """Ich esse gerne Bananen""", """Morgen ist wieder ein toller Tag!""", ], } _A : str = Path(self.get_auto_remove_tmp_dir() ) _A : str = str(tmp_dir / """scores.json""" ) _A : Any = str(tmp_dir / """val.target""" ) _dump_articles(__snake_case , text["""en"""] ) _dump_articles(__snake_case , text["""de"""] ) _A : Union[str, Any] = """translation_en_to_de""" if model == T5_TINY else """summarization""" _A : Optional[Any] = F''' run_eval_search.py {model} {str(__snake_case )} {str(__snake_case )} --score_path {score_path} --reference_path {reference_path} --task {task} '''.split() testargs.extend(["""--search""", """num_beams=1:2 length_penalty=0.9:1.0"""] ) with patch.object(__snake_case , """argv""" , __snake_case ): with CaptureStdout() as cs: run_search() _A : Dict = [""" num_beams | length_penalty""", model, """Best score args"""] _A : List[str] = ["""Info"""] if "translation" in task: expected_strings.append("""bleu""" ) else: expected_strings.extend(__snake_case ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(__snake_case ).exists() os.remove(Path(__snake_case ) )
353
from random import randint from tempfile import TemporaryFile import numpy as np def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : Tuple = 0 if start < end: _A : Tuple = randint(snake_case_,snake_case_ ) _A : Any = a[end] _A : int = a[pivot] _A : int = temp _A , _A : List[Any] = _in_place_partition(snake_case_,snake_case_,snake_case_ ) count += _in_place_quick_sort(snake_case_,snake_case_,p - 1 ) count += _in_place_quick_sort(snake_case_,p + 1,snake_case_ ) return count def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : str = 0 _A : List[str] = randint(snake_case_,snake_case_ ) _A : Union[str, Any] = a[end] _A : List[str] = a[pivot] _A : List[Any] = temp _A : List[str] = start - 1 for index in range(snake_case_,snake_case_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value _A : Union[str, Any] = new_pivot_index + 1 _A : List[Any] = a[new_pivot_index] _A : Optional[int] = a[index] _A : List[Any] = temp _A : Optional[Any] = a[new_pivot_index + 1] _A : Any = a[end] _A : Dict = temp return new_pivot_index + 1, count _snake_case = TemporaryFile() _snake_case = 100 # 1000 elements are to be sorted _snake_case , _snake_case = 0, 1 # mean and standard deviation _snake_case = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array _snake_case = np.load(outfile) _snake_case = len(M) - 1 _snake_case = _in_place_quick_sort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
343
0
from __future__ import annotations import unittest from transformers import LEDConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class lowercase : _a = LEDConfig _a = {} _a = "gelu" def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=False , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a=0.1 , _a=0.1 , _a=20 , _a=2 , _a=1 , _a=0 , _a=4 , ) -> Any: _A : List[Any] = parent _A : Tuple = batch_size _A : List[Any] = seq_length _A : List[Any] = is_training _A : str = use_labels _A : List[str] = vocab_size _A : Union[str, Any] = hidden_size _A : List[str] = num_hidden_layers _A : List[Any] = num_attention_heads _A : Optional[Any] = intermediate_size _A : str = hidden_dropout_prob _A : Any = attention_probs_dropout_prob _A : Optional[Any] = max_position_embeddings _A : List[Any] = eos_token_id _A : str = pad_token_id _A : Tuple = bos_token_id _A : List[Any] = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after _A : Optional[Any] = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests _A : Optional[int] = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def a__ ( self ) -> List[str]: _A : List[str] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _A : Any = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _A : Union[str, Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) _A : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _A : 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 , attention_window=self.attention_window , **self.config_updates , ) _A : Dict = prepare_led_inputs_dict(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) _A : Optional[Any] = tf.concat( [tf.zeros_like(_lowerCamelCase )[:, :-1], tf.ones_like(_lowerCamelCase )[:, -1:]] , axis=-1 , ) _A : Optional[int] = global_attention_mask return config, inputs_dict def a__ ( self , _a , _a ) -> Union[str, Any]: _A : Optional[int] = TFLEDModel(config=_lowerCamelCase ).get_decoder() _A : str = inputs_dict['''input_ids'''] _A : Optional[Any] = input_ids[:1, :] _A : Optional[Any] = inputs_dict['''attention_mask'''][:1, :] _A : List[Any] = 1 # first forward pass _A : Optional[int] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , use_cache=_lowerCamelCase ) _A : List[str] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _A : List[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) _A : Any = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _A : List[Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) _A : Tuple = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _A : Optional[int] = model(_lowerCamelCase , attention_mask=_lowerCamelCase )[0] _A : Dict = model(_lowerCamelCase , attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _A : List[str] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _A : List[str] = output_from_no_past[:, -3:, random_slice_idx] _A : List[str] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_lowerCamelCase , _lowerCamelCase , rtol=1e-3 ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_=None,snake_case_=None,snake_case_=None,snake_case_=None,): if attention_mask is None: _A : List[str] = tf.cast(tf.math.not_equal(lowerCamelCase__,config.pad_token_id ),tf.inta ) if decoder_attention_mask is None: _A : List[str] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:],config.pad_token_id ),tf.inta ), ],axis=-1,) if head_mask is None: _A : Union[str, Any] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _A : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class lowercase ( a__,a__,unittest.TestCase ): _a = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () _a = (TFLEDForConditionalGeneration,) if is_tf_available() else () _a = ( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) _a = True _a = False _a = False _a = False def a__ ( self ) -> List[str]: _A : Tuple = TFLEDModelTester(self ) _A : Tuple = ConfigTester(self , config_class=_lowerCamelCase ) def a__ ( self ) -> Any: self.config_tester.run_common_tests() def a__ ( self ) -> int: _A : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_lowerCamelCase ) def a__ ( self ) -> Optional[int]: _A : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _A : str = tf.zeros_like(inputs_dict["""attention_mask"""] ) _A : str = 2 _A : Dict = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict["""global_attention_mask"""] , ) _A : str = True _A : Dict = self.model_tester.seq_length _A : Dict = self.model_tester.encoder_seq_length def check_decoder_attentions_output(_a ): _A : str = outputs.decoder_attentions self.assertEqual(len(_lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(_a ): _A : Optional[int] = [t.numpy() for t in outputs.encoder_attentions] _A : Any = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(_lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(_lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: _A : Optional[int] = True _A : str = False _A : Optional[Any] = False _A : List[Any] = model_class(_lowerCamelCase ) _A : str = model(self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) _A : int = len(_lowerCamelCase ) self.assertEqual(config.output_hidden_states , _lowerCamelCase ) check_encoder_attentions_output(_lowerCamelCase ) if self.is_encoder_decoder: _A : str = model_class(_lowerCamelCase ) _A : Dict = model(self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , _lowerCamelCase ) check_decoder_attentions_output(_lowerCamelCase ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _A : List[Any] = True _A : Optional[int] = model_class(_lowerCamelCase ) _A : Dict = model(self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , _lowerCamelCase ) check_encoder_attentions_output(_lowerCamelCase ) # Check attention is always last and order is fine _A : Tuple = True _A : Dict = True _A : Union[str, Any] = model_class(_lowerCamelCase ) _A : List[str] = model(self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_lowerCamelCase ) ) self.assertEqual(model.config.output_hidden_states , _lowerCamelCase ) check_encoder_attentions_output(_lowerCamelCase ) @unittest.skip("""LED keeps using potentially symbolic tensors in conditionals and breaks tracing.""" ) def a__ ( self ) -> List[Any]: pass def a__ ( self ) -> str: pass def lowerCAmelCase_ ( snake_case_ ): return tf.constant(lowerCamelCase__,dtype=tf.intaa ) _snake_case = 1e-4 @slow @require_tf class lowercase ( unittest.TestCase ): def a__ ( self ) -> Optional[int]: _A : List[Any] = TFLEDForConditionalGeneration.from_pretrained("""allenai/led-base-16384""" ).led # change to intended input here _A : Any = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _A : List[Any] = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _A : List[Any] = prepare_led_inputs_dict(model.config , _lowerCamelCase , _lowerCamelCase ) _A : Tuple = model(**_lowerCamelCase )[0] _A : Dict = (1, 1024, 768) self.assertEqual(output.shape , _lowerCamelCase ) # change to expected output here _A : Optional[Any] = tf.convert_to_tensor( [[2.3050, 2.8279, 0.6531], [-1.8457, -0.1455, -3.5661], [-1.0186, 0.4586, -2.2043]] , ) tf.debugging.assert_near(output[:, :3, :3] , _lowerCamelCase , atol=1e-3 ) def a__ ( self ) -> Union[str, Any]: _A : Tuple = TFLEDForConditionalGeneration.from_pretrained("""allenai/led-base-16384""" ) # change to intended input here _A : Optional[Any] = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _A : List[Any] = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _A : Union[str, Any] = prepare_led_inputs_dict(model.config , _lowerCamelCase , _lowerCamelCase ) _A : Any = model(**_lowerCamelCase )[0] _A : Optional[int] = (1, 1024, model.config.vocab_size) self.assertEqual(output.shape , _lowerCamelCase ) # change to expected output here _A : int = tf.convert_to_tensor( [[33.6507, 6.4572, 16.8089], [5.8739, -2.4238, 11.2902], [-3.2139, -4.3149, 4.2783]] , ) tf.debugging.assert_near(output[:, :3, :3] , _lowerCamelCase , atol=1e-3 , rtol=1e-3 )
354
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { "MIT/ast-finetuned-audioset-10-10-0.4593": ( "https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json" ), } class lowercase ( UpperCamelCase__ ): _a = "audio-spectrogram-transformer" def __init__( self , _a=768 , _a=12 , _a=12 , _a=3072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1e-12 , _a=16 , _a=True , _a=10 , _a=10 , _a=1024 , _a=128 , **_a , ) -> List[Any]: super().__init__(**_a ) _A : Any = hidden_size _A : Tuple = num_hidden_layers _A : List[str] = num_attention_heads _A : Any = intermediate_size _A : Optional[Any] = hidden_act _A : Optional[Any] = hidden_dropout_prob _A : Any = attention_probs_dropout_prob _A : Optional[Any] = initializer_range _A : Optional[Any] = layer_norm_eps _A : str = patch_size _A : Tuple = qkv_bias _A : Dict = frequency_stride _A : Union[str, Any] = time_stride _A : Any = max_length _A : Tuple = num_mel_bins
343
0
import argparse from collections import defaultdict import yaml _snake_case = "docs/source/en/_toctree.yml" def lowerCAmelCase_ ( snake_case_ ): _A : Any = defaultdict(__a ) for doc in model_doc: counts[doc["local"]] += 1 _A : List[str] = [key for key, value in counts.items() if value > 1] _A : str = [] for duplicate_key in duplicates: _A : Union[str, Any] = list({doc["""title"""] for doc in model_doc if doc["""local"""] == duplicate_key} ) if len(__a ) > 1: raise ValueError( f'''{duplicate_key} is present several times in the documentation table of content at ''' """`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the """ """others.""" ) # Only add this once new_doc.append({"""local""": duplicate_key, """title""": titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc["""local"""]] == 1] ) # Sort return sorted(__a,key=lambda snake_case_ : s["title"].lower() ) def lowerCAmelCase_ ( snake_case_=False ): with open(__a,encoding="""utf-8""" ) as f: _A : Tuple = yaml.safe_load(f.read() ) # Get to the API doc _A : Union[str, Any] = 0 while content[api_idx]["title"] != "API": api_idx += 1 _A : Union[str, Any] = content[api_idx]['sections'] # Then to the model doc _A : List[str] = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 _A : List[str] = api_doc[model_idx]['sections'] _A : List[Any] = [(idx, section) for idx, section in enumerate(__a ) if 'sections' in section] _A : Tuple = False for idx, modality_doc in modalities_docs: _A : List[Any] = modality_doc['sections'] _A : Any = clean_model_doc_toc(__a ) if old_modality_doc != new_modality_doc: _A : Union[str, Any] = True if overwrite: _A : str = new_modality_doc if diff: if overwrite: _A : Dict = model_doc _A : Dict = api_doc with open(__a,"""w""",encoding="""utf-8""" ) as f: f.write(yaml.dump(__a,allow_unicode=__a ) ) else: raise ValueError( """The model doc part of the table of content is not properly sorted, run `make style` to fix this.""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") _snake_case = parser.parse_args() check_model_doc(args.fix_and_overwrite)
355
import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) _snake_case = logging.getLogger() def lowerCAmelCase_ ( ): _A : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""-f""" ) _A : Optional[Any] = parser.parse_args() return args.f class lowercase ( UpperCamelCase__ ): def a__ ( self ) -> None: _A : List[Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(_a ) def a__ ( self , _a ) -> Dict: _A : Tuple = get_gpu_count() if n_gpu > 1: pass # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560 # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py" # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split() # cmd = [sys.executable] + distributed_args + args # execute_subprocess_async(cmd, env=self.get_env()) # XXX: test the results - need to save them first into .json file else: args.insert(0 , """run_glue_deebert.py""" ) with patch.object(_a , """argv""" , _a ): _A : Optional[Any] = run_glue_deebert.main() for value in result.values(): self.assertGreaterEqual(_a , 0.666 ) @slow @require_torch_non_multi_gpu def a__ ( self ) -> Optional[int]: _A : Tuple = """ --model_type roberta --model_name_or_path roberta-base --task_name MRPC --do_train --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --max_seq_length 128 --per_gpu_eval_batch_size=1 --per_gpu_train_batch_size=8 --learning_rate 2e-4 --num_train_epochs 3 --overwrite_output_dir --seed 42 --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --save_steps 0 --overwrite_cache --eval_after_first_stage """.split() self.run_and_check(_a ) _A : Optional[Any] = """ --model_type roberta --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --task_name MRPC --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --max_seq_length 128 --eval_each_highway --eval_highway --overwrite_cache --per_gpu_eval_batch_size=1 """.split() self.run_and_check(_a ) _A : List[str] = """ --model_type roberta --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --task_name MRPC --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --max_seq_length 128 --early_exit_entropy 0.1 --eval_highway --overwrite_cache --per_gpu_eval_batch_size=1 """.split() self.run_and_check(_a )
343
0
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class lowercase ( unittest.TestCase ): def a__ ( self ) -> Dict: _A : Union[str, Any] = tempfile.mkdtemp() _A : Any = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """的""", """价""", """格""", """是""", """15""", """便""", """alex""", """##andra""", """,""", """。""", """-""", """t""", """shirt""", ] _A : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) _A : List[Any] = { """do_resize""": True, """size""": {"""height""": 224, """width""": 224}, """do_center_crop""": True, """crop_size""": {"""height""": 18, """width""": 18}, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], """do_convert_rgb""": True, } _A : Union[str, Any] = os.path.join(self.tmpdirname , _a ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(_a , _a ) def a__ ( self , **_a ) -> List[str]: return BertTokenizer.from_pretrained(self.tmpdirname , **_a ) def a__ ( self , **_a ) -> Union[str, Any]: return BertTokenizerFast.from_pretrained(self.tmpdirname , **_a ) def a__ ( self , **_a ) -> Optional[int]: return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **_a ) def a__ ( self ) -> List[str]: shutil.rmtree(self.tmpdirname ) def a__ ( self ) -> List[str]: _A : List[str] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _A : Dict = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def a__ ( self ) -> List[Any]: _A : Any = self.get_tokenizer() _A : Optional[int] = self.get_rust_tokenizer() _A : List[str] = self.get_image_processor() _A : Optional[Any] = ChineseCLIPProcessor(tokenizer=_a , image_processor=_a ) processor_slow.save_pretrained(self.tmpdirname ) _A : Dict = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=_a ) _A : Tuple = ChineseCLIPProcessor(tokenizer=_a , image_processor=_a ) processor_fast.save_pretrained(self.tmpdirname ) _A : int = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _a ) self.assertIsInstance(processor_fast.tokenizer , _a ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _a ) self.assertIsInstance(processor_fast.image_processor , _a ) def a__ ( self ) -> str: _A : Optional[int] = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _A : List[str] = self.get_tokenizer(cls_token="""(CLS)""" , sep_token="""(SEP)""" ) _A : List[Any] = self.get_image_processor(do_normalize=_a ) _A : Tuple = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token="""(CLS)""" , sep_token="""(SEP)""" , do_normalize=_a ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def a__ ( self ) -> List[Any]: _A : str = self.get_image_processor() _A : int = self.get_tokenizer() _A : int = ChineseCLIPProcessor(tokenizer=_a , image_processor=_a ) _A : Dict = self.prepare_image_inputs() _A : Optional[Any] = image_processor(_a , return_tensors="""np""" ) _A : str = processor(images=_a , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a__ ( self ) -> Tuple: _A : Any = self.get_image_processor() _A : List[str] = self.get_tokenizer() _A : str = ChineseCLIPProcessor(tokenizer=_a , image_processor=_a ) _A : Tuple = """Alexandra,T-shirt的价格是15便士。""" _A : Dict = processor(text=_a ) _A : Optional[Any] = tokenizer(_a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def a__ ( self ) -> List[Any]: _A : Union[str, Any] = self.get_image_processor() _A : str = self.get_tokenizer() _A : List[Any] = ChineseCLIPProcessor(tokenizer=_a , image_processor=_a ) _A : Dict = """Alexandra,T-shirt的价格是15便士。""" _A : int = self.prepare_image_inputs() _A : Union[str, Any] = processor(text=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(_a ): processor() def a__ ( self ) -> List[str]: _A : int = self.get_image_processor() _A : Optional[Any] = self.get_tokenizer() _A : str = ChineseCLIPProcessor(tokenizer=_a , image_processor=_a ) _A : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _A : Union[str, Any] = processor.batch_decode(_a ) _A : List[str] = tokenizer.batch_decode(_a ) self.assertListEqual(_a , _a ) def a__ ( self ) -> Tuple: _A : str = self.get_image_processor() _A : str = self.get_tokenizer() _A : List[Any] = ChineseCLIPProcessor(tokenizer=_a , image_processor=_a ) _A : Optional[int] = """Alexandra,T-shirt的价格是15便士。""" _A : str = self.prepare_image_inputs() _A : Optional[int] = processor(text=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
356
import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowercase : def __init__( self , _a , _a=13 , _a=30 , _a=2 , _a=3 , _a=True , _a=True , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=10 , _a=0.02 , _a=None , ) -> Union[str, Any]: _A : Optional[int] = parent _A : Dict = batch_size _A : Any = image_size _A : Optional[int] = patch_size _A : Optional[int] = num_channels _A : List[Any] = is_training _A : Optional[Any] = use_labels _A : Any = hidden_size _A : Any = num_hidden_layers _A : List[Any] = num_attention_heads _A : int = intermediate_size _A : Dict = hidden_act _A : Optional[int] = hidden_dropout_prob _A : str = attention_probs_dropout_prob _A : Any = type_sequence_label_size _A : str = initializer_range _A : Tuple = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) _A : List[Any] = (image_size // patch_size) ** 2 _A : str = num_patches + 1 def a__ ( self ) -> Dict: _A : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A : List[str] = None if self.use_labels: _A : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _A : List[Any] = self.get_config() return config, pixel_values, labels def a__ ( self ) -> Union[str, Any]: return ViTMSNConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , ) def a__ ( self , _a , _a , _a ) -> Dict: _A : List[str] = ViTMSNModel(config=_a ) model.to(_a ) model.eval() _A : List[str] = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a__ ( self , _a , _a , _a ) -> List[str]: _A : Union[str, Any] = self.type_sequence_label_size _A : Tuple = ViTMSNForImageClassification(_a ) model.to(_a ) model.eval() _A : Optional[int] = model(_a , labels=_a ) print("""Pixel and labels shape: {pixel_values.shape}, {labels.shape}""" ) print("""Labels: {labels}""" ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images _A : Dict = 1 _A : str = ViTMSNForImageClassification(_a ) model.to(_a ) model.eval() _A : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _A : int = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a__ ( self ) -> Any: _A : Optional[int] = self.prepare_config_and_inputs() _A , _A , _A : Dict = config_and_inputs _A : List[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowercase ( UpperCamelCase__,UpperCamelCase__,unittest.TestCase ): _a = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () _a = ( {"feature-extraction": ViTMSNModel, "image-classification": ViTMSNForImageClassification} if is_torch_available() else {} ) _a = False _a = False _a = False _a = False def a__ ( self ) -> Tuple: _A : Tuple = ViTMSNModelTester(self ) _A : List[Any] = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def a__ ( self ) -> Optional[int]: self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMSN does not use inputs_embeds""" ) def a__ ( self ) -> int: pass def a__ ( self ) -> Any: _A , _A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : Tuple = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _A : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , nn.Linear ) ) def a__ ( self ) -> str: _A , _A : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : int = model_class(_a ) _A : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A : str = [*signature.parameters.keys()] _A : Optional[int] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def a__ ( self ) -> List[Any]: _A : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def a__ ( self ) -> Any: _A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @slow def a__ ( self ) -> int: for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _A : int = ViTMSNModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowerCAmelCase_ ( ): _A : Dict = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class lowercase ( unittest.TestCase ): @cached_property def a__ ( self ) -> int: return ViTImageProcessor.from_pretrained("""facebook/vit-msn-small""" ) if is_vision_available() else None @slow def a__ ( self ) -> Optional[int]: torch.manual_seed(2 ) _A : Tuple = ViTMSNForImageClassification.from_pretrained("""facebook/vit-msn-small""" ).to(_a ) _A : Tuple = self.default_image_processor _A : Dict = prepare_img() _A : Optional[Any] = image_processor(images=_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): _A : int = model(**_a ) # verify the logits _A : Union[str, Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _a ) _A : Optional[int] = torch.tensor([-0.0803, -0.4454, -0.2375] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) )
343
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/config.json", "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/config.json" # See all FNet models at https://huggingface.co/models?filter=fnet } class lowercase ( UpperCamelCase__ ): _a = '''fnet''' def __init__( self , _a=3_2000 , _a=768 , _a=12 , _a=3072 , _a="gelu_new" , _a=0.1 , _a=512 , _a=4 , _a=0.02 , _a=1e-12 , _a=False , _a=512 , _a=3 , _a=1 , _a=2 , **_a , ) -> int: super().__init__(pad_token_id=_snake_case , bos_token_id=_snake_case , eos_token_id=_snake_case , **_snake_case ) _A : str = vocab_size _A : Tuple = max_position_embeddings _A : Tuple = hidden_size _A : List[Any] = num_hidden_layers _A : Union[str, Any] = intermediate_size _A : Union[str, Any] = hidden_act _A : List[str] = hidden_dropout_prob _A : Union[str, Any] = initializer_range _A : Optional[Any] = type_vocab_size _A : List[Any] = layer_norm_eps _A : Union[str, Any] = use_tpu_fourier_optimizations _A : List[Any] = tpu_short_seq_length
357
def lowerCAmelCase_ ( snake_case_ = 1000 ): _A : List[Any] = 3 _A : Tuple = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f"""{solution() = }""")
343
0
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) class lowercase ( lowercase__ ): _a = 'encoder-decoder' _a = True def __init__( self , **_a ) -> List[Any]: super().__init__(**_UpperCamelCase ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" _A : Optional[Any] = kwargs.pop("""encoder""" ) _A : str = encoder_config.pop("""model_type""" ) _A : Optional[Any] = kwargs.pop("""decoder""" ) _A : Dict = decoder_config.pop("""model_type""" ) from ..auto.configuration_auto import AutoConfig _A : Tuple = AutoConfig.for_model(_UpperCamelCase , **_UpperCamelCase ) _A : Union[str, Any] = AutoConfig.for_model(_UpperCamelCase , **_UpperCamelCase ) _A : int = True @classmethod def a__ ( cls , _a , _a , **_a ) -> Optional[Any]: logger.info("""Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config""" ) _A : Optional[Any] = True _A : Optional[int] = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **_UpperCamelCase ) def a__ ( self ) -> str: _A : List[str] = copy.deepcopy(self.__dict__ ) _A : int = self.encoder.to_dict() _A : List[str] = self.decoder.to_dict() _A : int = self.__class__.model_type return output
358
import inspect import unittest from transformers import ConvNextConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase : def __init__( self , _a , _a=13 , _a=32 , _a=3 , _a=4 , _a=[10, 20, 30, 40] , _a=[2, 2, 3, 2] , _a=True , _a=True , _a=37 , _a="gelu" , _a=10 , _a=0.02 , _a=["stage2", "stage3", "stage4"] , _a=[2, 3, 4] , _a=None , ) -> List[Any]: _A : Tuple = parent _A : Any = batch_size _A : int = image_size _A : Tuple = num_channels _A : List[Any] = num_stages _A : Any = hidden_sizes _A : Union[str, Any] = depths _A : Union[str, Any] = is_training _A : Tuple = use_labels _A : Optional[Any] = intermediate_size _A : Union[str, Any] = hidden_act _A : Any = num_labels _A : List[str] = initializer_range _A : str = out_features _A : int = out_indices _A : List[Any] = scope def a__ ( self ) -> str: _A : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A : str = None if self.use_labels: _A : int = ids_tensor([self.batch_size] , self.num_labels ) _A : str = self.get_config() return config, pixel_values, labels def a__ ( self ) -> List[str]: return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=_a , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def a__ ( self , _a , _a , _a ) -> int: _A : int = ConvNextModel(config=_a ) model.to(_a ) model.eval() _A : int = model(_a ) # expected last hidden states: B, C, H // 32, W // 32 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 , _a ) -> List[Any]: _A : Union[str, Any] = ConvNextForImageClassification(_a ) model.to(_a ) model.eval() _A : List[Any] = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a__ ( self , _a , _a , _a ) -> str: _A : List[str] = ConvNextBackbone(config=_a ) model.to(_a ) model.eval() _A : Optional[int] = model(_a ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None _A : Optional[Any] = None _A : str = ConvNextBackbone(config=_a ) model.to(_a ) model.eval() _A : int = model(_a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def a__ ( self ) -> int: _A : int = self.prepare_config_and_inputs() _A , _A , _A : List[Any] = config_and_inputs _A : Any = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowercase ( UpperCamelCase__,UpperCamelCase__,unittest.TestCase ): _a = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) _a = ( {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification} if is_torch_available() else {} ) _a = True _a = False _a = False _a = False _a = False def a__ ( self ) -> Dict: _A : int = ConvNextModelTester(self ) _A : List[Any] = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def a__ ( self ) -> Any: 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 ) -> str: return @unittest.skip(reason="""ConvNext does not use inputs_embeds""" ) def a__ ( self ) -> Tuple: pass @unittest.skip(reason="""ConvNext does not support input and output embeddings""" ) def a__ ( self ) -> Optional[Any]: pass @unittest.skip(reason="""ConvNext does not use feedforward chunking""" ) def a__ ( self ) -> List[Any]: pass def a__ ( self ) -> Optional[Any]: _A , _A : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : Optional[Any] = model_class(_a ) _A : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A : List[Any] = [*signature.parameters.keys()] _A : int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def a__ ( self ) -> Union[str, Any]: _A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def a__ ( self ) -> Tuple: _A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_a ) def a__ ( self ) -> Tuple: def check_hidden_states_output(_a , _a , _a ): _A : Tuple = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): _A : Dict = model(**self._prepare_for_class(_a , _a ) ) _A : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _A : Dict = self.model_tester.num_stages self.assertEqual(len(_a ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) _A , _A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : List[Any] = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _A : Union[str, Any] = True check_hidden_states_output(_a , _a , _a ) def a__ ( self ) -> int: _A : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @slow def a__ ( self ) -> Optional[int]: for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _A : Optional[Any] = ConvNextModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowerCAmelCase_ ( ): _A : Optional[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class lowercase ( unittest.TestCase ): @cached_property def a__ ( self ) -> str: return AutoImageProcessor.from_pretrained("""facebook/convnext-tiny-224""" ) if is_vision_available() else None @slow def a__ ( self ) -> Optional[Any]: _A : Any = ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224""" ).to(_a ) _A : List[str] = self.default_image_processor _A : int = prepare_img() _A : Union[str, Any] = image_processor(images=_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): _A : Dict = model(**_a ) # verify the logits _A : Optional[Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _a ) _A : Any = torch.tensor([-0.0260, -0.4739, 0.1911] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) ) @require_torch class lowercase ( unittest.TestCase,UpperCamelCase__ ): _a = (ConvNextBackbone,) if is_torch_available() else () _a = ConvNextConfig _a = False def a__ ( self ) -> List[str]: _A : Optional[int] = ConvNextModelTester(self )
343
0
import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py _snake_case = """.""" # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) _snake_case = [ """Assert""", """AssignVariableOp""", """EmptyTensorList""", """MergeV2Checkpoints""", """ReadVariableOp""", """ResourceGather""", """RestoreV2""", """SaveV2""", """ShardedFilename""", """StatefulPartitionedCall""", """StaticRegexFullMatch""", """VarHandleOp""", ] def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : Any = SavedModel() _A : Optional[int] = [] with open(os.path.join(snake_case_,"""utils""","""tf_ops""","""onnx.json""" ) ) as f: _A : List[Any] = json.load(snake_case_ )["""opsets"""] for i in range(1,opset + 1 ): onnx_ops.extend(onnx_opsets[str(snake_case_ )] ) with open(snake_case_,"""rb""" ) as f: saved_model.ParseFromString(f.read() ) _A : Tuple = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want _A : List[Any] = sorted(snake_case_ ) _A : str = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(snake_case_ ) if strict and len(snake_case_ ) > 0: raise Exception(f'''Found the following incompatible ops for the opset {opset}:\n''' + incompatible_ops ) elif len(snake_case_ ) > 0: print(f'''Found the following incompatible ops for the opset {opset}:''' ) print(*snake_case_,sep="""\n""" ) else: print(f'''The saved model {saved_model_path} can properly be converted with ONNX.''' ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument("--saved_model_path", help="Path of the saved model to check (the .pb file).") parser.add_argument( "--opset", default=12, type=int, help="The ONNX opset against which the model has to be tested." ) parser.add_argument( "--framework", choices=["onnx"], default="onnx", help="Frameworks against which to test the saved model." ) parser.add_argument( "--strict", action="store_true", help="Whether make the checking strict (raise errors) or not (raise warnings)" ) _snake_case = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
359
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _snake_case = { "configuration_roc_bert": ["ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoCBertConfig"], "tokenization_roc_bert": ["RoCBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ "ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "RoCBertForCausalLM", "RoCBertForMaskedLM", "RoCBertForMultipleChoice", "RoCBertForPreTraining", "RoCBertForQuestionAnswering", "RoCBertForSequenceClassification", "RoCBertForTokenClassification", "RoCBertLayer", "RoCBertModel", "RoCBertPreTrainedModel", "load_tf_weights_in_roc_bert", ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys _snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
343
0
"""simple docstring""" import string import numpy def lowerCAmelCase_ ( snake_case_,snake_case_ ): return b if a == 0 else greatest_common_divisor(b % a,__lowerCamelCase ) class lowercase : _a = string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) _a = numpy.vectorize(lambda UpperCamelCase__ : x % 3_6 ) _a = numpy.vectorize(A_ ) def __init__( self , _a ) -> None: _A : Optional[int] = self.modulus(snake_case__ ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key _A : Optional[int] = encrypt_key.shape[0] def a__ ( self , _a ) -> int: return self.key_string.index(snake_case__ ) def a__ ( self , _a ) -> str: return self.key_string[round(snake_case__ )] def a__ ( self ) -> None: _A : Optional[int] = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: _A : int = det % len(self.key_string ) _A : Optional[int] = len(self.key_string ) if greatest_common_divisor(snake_case__ , len(self.key_string ) ) != 1: _A : str = ( F'''determinant modular {req_l} of encryption key({det}) ''' F'''is not co prime w.r.t {req_l}.\nTry another key.''' ) raise ValueError(snake_case__ ) def a__ ( self , _a ) -> str: _A : List[str] = [char for char in text.upper() if char in self.key_string] _A : Tuple = chars[-1] while len(snake_case__ ) % self.break_key != 0: chars.append(snake_case__ ) return "".join(snake_case__ ) def a__ ( self , _a ) -> str: _A : Any = self.process_text(text.upper() ) _A : Optional[int] = "" for i in range(0 , len(snake_case__ ) - self.break_key + 1 , self.break_key ): _A : List[Any] = text[i : i + self.break_key] _A : Union[str, Any] = [self.replace_letters(snake_case__ ) for char in batch] _A : Tuple = numpy.array([vec] ).T _A : Optional[Any] = self.modulus(self.encrypt_key.dot(snake_case__ ) ).T.tolist()[ 0 ] _A : List[Any] = "".join( self.replace_digits(snake_case__ ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def a__ ( self ) -> numpy.ndarray: _A : Tuple = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: _A : int = det % len(self.key_string ) _A : Any = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: _A : str = i break _A : int = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(snake_case__ ) ) def a__ ( self , _a ) -> str: _A : str = self.make_decrypt_key() _A : Dict = self.process_text(text.upper() ) _A : Optional[Any] = "" for i in range(0 , len(snake_case__ ) - self.break_key + 1 , self.break_key ): _A : str = text[i : i + self.break_key] _A : List[Any] = [self.replace_letters(snake_case__ ) for char in batch] _A : List[str] = numpy.array([vec] ).T _A : Optional[int] = self.modulus(decrypt_key.dot(snake_case__ ) ).T.tolist()[0] _A : int = "".join( self.replace_digits(snake_case__ ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def lowerCAmelCase_ ( ): _A : Optional[int] = int(input("""Enter the order of the encryption key: """ ) ) _A : Union[str, Any] = [] print("""Enter each row of the encryption key with space separated integers""" ) for _ in range(__lowerCamelCase ): _A : Union[str, Any] = [int(__lowerCamelCase ) for x in input().split()] hill_matrix.append(__lowerCamelCase ) _A : Any = HillCipher(numpy.array(__lowerCamelCase ) ) print("""Would you like to encrypt or decrypt some text? (1 or 2)""" ) _A : Tuple = input("""\n1. Encrypt\n2. Decrypt\n""" ) if option == "1": _A : Any = input("""What text would you like to encrypt?: """ ) print("""Your encrypted text is:""" ) print(hc.encrypt(__lowerCamelCase ) ) elif option == "2": _A : Optional[int] = input("""What text would you like to decrypt?: """ ) print("""Your decrypted text is:""" ) print(hc.decrypt(__lowerCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
360
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowercase : _a = 42 # setable values _a = 42 _a = 42 _a = None @classmethod def a__ ( cls , _a , _a , _a ) -> Tuple: return cls(common=_a , init_noise_sigma=_a , timesteps=_a ) @dataclass class lowercase ( UpperCamelCase__ ): _a = 42 class lowercase ( UpperCamelCase__,UpperCamelCase__ ): _a = [e.name for e in FlaxKarrasDiffusionSchedulers] _a = 42 @property def a__ ( self ) -> Dict: return True @register_to_config def __init__( self , _a = 1000 , _a = 0.0001 , _a = 0.02 , _a = "linear" , _a = None , _a = "fixed_small" , _a = True , _a = "epsilon" , _a = jnp.floataa , ) -> Tuple: _A : Tuple = dtype def a__ ( self , _a = None ) -> DDPMSchedulerState: if common is None: _A : Dict = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution _A : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) _A : Tuple = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=_a , init_noise_sigma=_a , timesteps=_a , ) def a__ ( self , _a , _a , _a = None ) -> jnp.ndarray: return sample def a__ ( self , _a , _a , _a = () ) -> DDPMSchedulerState: _A : Any = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 _A : Dict = (jnp.arange(0 , _a ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=_a , timesteps=_a , ) def a__ ( self , _a , _a , _a=None , _a=None ) -> Optional[int]: _A : Optional[Any] = state.common.alphas_cumprod[t] _A : int = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample _A : List[str] = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: _A : Optional[Any] = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": _A : Optional[Any] = jnp.clip(_a , a_min=1e-20 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": _A : Any = jnp.log(jnp.clip(_a , a_min=1e-20 ) ) elif variance_type == "fixed_large": _A : Optional[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log _A : Tuple = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": _A : str = variance _A : Union[str, Any] = state.common.betas[t] _A : Tuple = (predicted_variance + 1) / 2 _A : List[str] = frac * max_log + (1 - frac) * min_log return variance def a__ ( self , _a , _a , _a , _a , _a = None , _a = True , ) -> Union[FlaxDDPMSchedulerOutput, Tuple]: _A : Dict = timestep if key is None: _A : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: _A , _A : List[str] = jnp.split(_a , sample.shape[1] , axis=1 ) else: _A : int = None # 1. compute alphas, betas _A : int = state.common.alphas_cumprod[t] _A : List[str] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) _A : Union[str, Any] = 1 - alpha_prod_t _A : Optional[int] = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": _A : Dict = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": _A : Optional[int] = model_output elif self.config.prediction_type == "v_prediction": _A : Any = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' """ for the FlaxDDPMScheduler.""" ) # 3. Clip "predicted x_0" if self.config.clip_sample: _A : Union[str, Any] = jnp.clip(_a , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _A : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t _A : Dict = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _A : int = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): _A : Tuple = jax.random.split(_a , num=1 ) _A : Dict = jax.random.normal(_a , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(_a , _a , predicted_variance=_a ) ** 0.5) * noise _A : int = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) _A : Union[str, Any] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=_a , state=_a ) def a__ ( self , _a , _a , _a , _a , ) -> jnp.ndarray: return add_noise_common(state.common , _a , _a , _a ) def a__ ( self , _a , _a , _a , _a , ) -> jnp.ndarray: return get_velocity_common(state.common , _a , _a , _a ) def __len__( self ) -> List[Any]: return self.config.num_train_timesteps
343
0
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin _snake_case = "\nHugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]\n" class lowercase ( unittest.TestCase,__SCREAMING_SNAKE_CASE ): def a__ ( self ) -> List[Any]: _A : Any = load_tool("""text-question-answering""" ) self.tool.setup() _A : List[Any] = load_tool("""text-question-answering""" , remote=_a ) def a__ ( self ) -> List[str]: _A : int = self.tool(_a , """What did Hugging Face do in April 2021?""" ) self.assertEqual(_a , """launched the BigScience Research Workshop""" ) def a__ ( self ) -> Dict: _A : Optional[Any] = self.remote_tool(_a , """What did Hugging Face do in April 2021?""" ) self.assertEqual(_a , """launched the BigScience Research Workshop""" ) def a__ ( self ) -> Tuple: _A : Dict = self.tool(text=_a , question="""What did Hugging Face do in April 2021?""" ) self.assertEqual(_a , """launched the BigScience Research Workshop""" ) def a__ ( self ) -> Optional[Any]: _A : str = self.remote_tool(text=_a , question="""What did Hugging Face do in April 2021?""" ) self.assertEqual(_a , """launched the BigScience Research Workshop""" )
361
# Copyright (c) 2021-, NVIDIA CORPORATION. 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. #################################################################################################### # # Note: If when running this conversion script you're getting an exception: # ModuleNotFoundError: No module named 'megatron.model.enums' # you need to tell python where to find the clone of Megatron-LM, e.g.: # # cd /tmp # git clone https://github.com/NVIDIA/Megatron-LM # PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ... # # if you already have it cloned elsewhere, simply adjust the path to the existing path # # If the training was done using a Megatron-LM fork, e.g., # https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one # in your path, i.e., /path/to/Megatron-DeepSpeed/ # import argparse import os import re import zipfile import torch from transformers import AutoTokenizer, GPTaConfig def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_=0 ): # Format the message. if name is None: _A : Union[str, Any] = None else: _A : Dict = """.""" * max(0,spaces - 2 ) + """# {:""" + str(50 - spaces ) + """s}""" _A : Tuple = fmt.format(snake_case_ ) # Print and recurse (if needed). if isinstance(snake_case_,snake_case_ ): if msg is not None: print(snake_case_ ) for k in val.keys(): recursive_print(snake_case_,val[k],spaces + 2 ) elif isinstance(snake_case_,torch.Tensor ): print(snake_case_,""":""",val.size() ) else: print(snake_case_,""":""",snake_case_ ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_ ): # Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :] # for compatibility with later versions of NVIDIA Megatron-LM. # The inverse operation is performed inside Megatron-LM to read checkpoints: # https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209 # If param is the weight tensor of the self-attention block, the returned tensor # will have to be transposed one more time to be read by HuggingFace GPT2. _A : str = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] _A : Union[str, Any] = (num_heads, hidden_size, num_splits) + input_shape[1:] _A : Tuple = param.view(*snake_case_ ) _A : Any = param.transpose(0,2 ) _A : int = param.transpose(1,2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] _A : Optional[Any] = (num_heads, num_splits, hidden_size) + input_shape[1:] _A : int = param.view(*snake_case_ ) _A : Any = param.transpose(0,1 ).contiguous() _A : Optional[int] = param.view(*snake_case_ ) return param def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): # The converted output model. _A : Any = {} # old versions did not store training args _A : str = input_state_dict.get("""args""",snake_case_ ) if ds_args is not None: # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint # from pprint import pprint # pprint(vars(ds_args)) _A : Union[str, Any] = ds_args.padded_vocab_size _A : List[Any] = ds_args.max_position_embeddings _A : Optional[int] = ds_args.hidden_size _A : List[Any] = ds_args.num_layers _A : List[str] = ds_args.num_attention_heads _A : int = ds_args.ffn_hidden_size # pprint(config) # The number of heads. _A : Union[str, Any] = config.n_head # The hidden_size per head. _A : List[Any] = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): _A : Tuple = input_state_dict["""checkpoint_version"""] else: _A : Any = 0.0 # The model. _A : Any = input_state_dict["""model"""] # The language model. _A : Tuple = model["""language_model"""] # The embeddings. _A : Any = lm["""embedding"""] # The word embeddings. _A : Dict = embeddings["""word_embeddings"""]["""weight"""] # Truncate the embedding table to vocab_size rows. _A : Union[str, Any] = word_embeddings[: config.vocab_size, :] _A : Tuple = word_embeddings # The position embeddings. _A : Tuple = embeddings["""position_embeddings"""]["""weight"""] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] _A : Any = pos_embeddings.size(0 ) if n_positions != config.n_positions: raise ValueError( f'''pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don\'t match''' ) # Store the position embeddings. _A : Optional[int] = pos_embeddings # The transformer. _A : Any = lm["""transformer"""] if """transformer""" in lm.keys() else lm["""encoder"""] # The regex to extract layer names. _A : Optional[int] = re.compile(r"""layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)""" ) # The simple map of names for "automated" rules. _A : Union[str, Any] = { """attention.dense""": """.attn.c_proj.""", """self_attention.dense""": """.attn.c_proj.""", """mlp.dense_h_to_4h""": """.mlp.c_fc.""", """mlp.dense_4h_to_h""": """.mlp.c_proj.""", } # Extract the layers. for key, val in transformer.items(): # Match the name. _A : List[str] = layer_re.match(snake_case_ ) # Stop if that's not a layer if m is None: break # The index of the layer. _A : Tuple = int(m.group(1 ) ) # The name of the operation. _A : Optional[Any] = m.group(2 ) # Is it a weight or a bias? _A : Dict = m.group(3 ) # The name of the layer. _A : Optional[Any] = f'''transformer.h.{layer_idx}''' # For layernorm(s), simply store the layer norm. if op_name.endswith("""layernorm""" ): _A : Union[str, Any] = """ln_1""" if op_name.startswith("""input""" ) else """ln_2""" _A : List[str] = val # Transpose the QKV matrix. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "weight": # Insert a tensor of 1x1xDxD bias. _A : List[str] = torch.tril(torch.ones((n_positions, n_positions),dtype=torch.floataa ) ).view( 1,1,snake_case_,snake_case_ ) _A : Any = causal_mask # Insert a "dummy" tensor for masked_bias. _A : List[str] = torch.tensor(-1e4,dtype=torch.floataa ) _A : Tuple = masked_bias _A : Tuple = fix_query_key_value_ordering(snake_case_,snake_case_,3,snake_case_,snake_case_ ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. _A : Tuple = out_val.transpose(0,1 ).contiguous() # Store. _A : Any = out_val # Transpose the bias. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "bias": _A : List[str] = fix_query_key_value_ordering(snake_case_,snake_case_,3,snake_case_,snake_case_ ) # Store. No change of shape. _A : Tuple = out_val # Transpose the weights. elif weight_or_bias == "weight": _A : List[str] = megatron_to_transformers[op_name] _A : Any = val.transpose(0,1 ) # Copy the bias. elif weight_or_bias == "bias": _A : Dict = megatron_to_transformers[op_name] _A : List[Any] = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. _A : Optional[Any] = transformer["""final_layernorm.weight"""] _A : Dict = transformer["""final_layernorm.bias"""] # For LM head, transformers' wants the matrix to weight embeddings. _A : List[str] = word_embeddings # It should be done! return output_state_dict def lowerCAmelCase_ ( ): # Create the argument parser. _A : Any = argparse.ArgumentParser() parser.add_argument("""--print-checkpoint-structure""",action="""store_true""" ) parser.add_argument( """path_to_checkpoint""",type=snake_case_,help="""Path to the checkpoint file (.zip archive or direct .pt file)""",) parser.add_argument( """--config_file""",default="""""",type=snake_case_,help="""An optional config json file describing the pre-trained model.""",) _A : Optional[int] = parser.parse_args() # Extract the basename. _A : Any = os.path.dirname(args.path_to_checkpoint ) # Load the model. # the .zip is very optional, let's keep it for backward compatibility print(f'''Extracting PyTorch state dictionary from {args.path_to_checkpoint}''' ) if args.path_to_checkpoint.endswith(""".zip""" ): with zipfile.ZipFile(args.path_to_checkpoint,"""r""" ) as checkpoint: with checkpoint.open("""release/mp_rank_00/model_optim_rng.pt""" ) as pytorch_dict: _A : Tuple = torch.load(snake_case_,map_location="""cpu""" ) else: _A : Tuple = torch.load(args.path_to_checkpoint,map_location="""cpu""" ) _A : Optional[Any] = input_state_dict.get("""args""",snake_case_ ) # Read the config, or default to the model released by NVIDIA. if args.config_file == "": if ds_args is not None: if ds_args.bias_gelu_fusion: _A : Union[str, Any] = """gelu_fast""" elif ds_args.openai_gelu: _A : int = """gelu_new""" else: _A : Optional[Any] = """gelu""" else: # in the very early days this used to be "gelu_new" _A : Any = """gelu_new""" # Spell out all parameters in case the defaults change. _A : Any = GPTaConfig( vocab_size=50257,n_positions=1024,n_embd=1024,n_layer=24,n_head=16,n_inner=4096,activation_function=snake_case_,resid_pdrop=0.1,embd_pdrop=0.1,attn_pdrop=0.1,layer_norm_epsilon=1e-5,initializer_range=0.02,summary_type="""cls_index""",summary_use_proj=snake_case_,summary_activation=snake_case_,summary_proj_to_labels=snake_case_,summary_first_dropout=0.1,scale_attn_weights=snake_case_,use_cache=snake_case_,bos_token_id=50256,eos_token_id=50256,) else: _A : Union[str, Any] = GPTaConfig.from_json_file(args.config_file ) _A : List[str] = ["""GPT2LMHeadModel"""] # Convert. print("""Converting""" ) _A : Optional[Any] = convert_megatron_checkpoint(snake_case_,snake_case_,snake_case_ ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(snake_case_,snake_case_ ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: _A : int = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": _A : Any = """gpt2""" elif tokenizer_type == "PretrainedFromHF": _A : List[Any] = ds_args.tokenizer_name_or_path else: raise ValueError(f'''Unrecognized tokenizer_type {tokenizer_type}''' ) else: _A : Optional[Any] = """gpt2""" _A : List[str] = AutoTokenizer.from_pretrained(snake_case_ ) _A : Tuple = type(snake_case_ ).__name__ _A : Union[str, Any] = tokenizer_class # Store the config to file. print("""Saving config""" ) config.save_pretrained(snake_case_ ) # Save tokenizer based on args print(f'''Adding {tokenizer_class} tokenizer files''' ) tokenizer.save_pretrained(snake_case_ ) # Store the state_dict to file. _A : Union[str, Any] = os.path.join(snake_case_,"""pytorch_model.bin""" ) print(f'''Saving checkpoint to "{output_checkpoint_file}"''' ) torch.save(snake_case_,snake_case_ ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
343
0
import json import os from typing import Optional import numpy as np from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessorMixin from ...utils import logging from ...utils.hub import get_file_from_repo from ..auto import AutoTokenizer _snake_case = logging.get_logger(__name__) class lowercase ( UpperCamelCase__ ): _a = "AutoTokenizer" _a = ["tokenizer"] _a = { "semantic_prompt": 1, "coarse_prompt": 2, "fine_prompt": 2, } def __init__( self , _a , _a=None ) -> List[str]: super().__init__(_a ) _A : Optional[int] = speaker_embeddings @classmethod def a__ ( cls , _a , _a="speaker_embeddings_path.json" , **_a ) -> Union[str, Any]: if speaker_embeddings_dict_path is not None: _A : Optional[Any] = get_file_from_repo( _a , _a , subfolder=kwargs.pop("""subfolder""" , _a ) , cache_dir=kwargs.pop("""cache_dir""" , _a ) , force_download=kwargs.pop("""force_download""" , _a ) , proxies=kwargs.pop("""proxies""" , _a ) , resume_download=kwargs.pop("""resume_download""" , _a ) , local_files_only=kwargs.pop("""local_files_only""" , _a ) , use_auth_token=kwargs.pop("""use_auth_token""" , _a ) , revision=kwargs.pop("""revision""" , _a ) , ) if speaker_embeddings_path is None: logger.warning( F'''`{os.path.join(_a , _a )}` does not exists , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`.''' ) _A : List[Any] = None else: with open(_a ) as speaker_embeddings_json: _A : Union[str, Any] = json.load(_a ) else: _A : Tuple = None _A : Union[str, Any] = AutoTokenizer.from_pretrained(_a , **_a ) return cls(tokenizer=_a , speaker_embeddings=_a ) def a__ ( self , _a , _a="speaker_embeddings_path.json" , _a="speaker_embeddings" , _a = False , **_a , ) -> Any: if self.speaker_embeddings is not None: os.makedirs(os.path.join(_a , _a , """v2""" ) , exist_ok=_a ) _A : int = {} _A : List[Any] = save_directory for prompt_key in self.speaker_embeddings: if prompt_key != "repo_or_path": _A : Optional[Any] = self._load_voice_preset(_a ) _A : Any = {} for key in self.speaker_embeddings[prompt_key]: np.save( os.path.join( embeddings_dict["""repo_or_path"""] , _a , F'''{prompt_key}_{key}''' ) , voice_preset[key] , allow_pickle=_a , ) _A : List[str] = os.path.join(_a , F'''{prompt_key}_{key}.npy''' ) _A : Optional[Any] = tmp_dict with open(os.path.join(_a , _a ) , """w""" ) as fp: json.dump(_a , _a ) super().save_pretrained(_a , _a , **_a ) def a__ ( self , _a = None , **_a ) -> Tuple: _A : Tuple = self.speaker_embeddings[voice_preset] _A : Any = {} for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset_paths: raise ValueError( F'''Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}].''' ) _A : Union[str, Any] = get_file_from_repo( self.speaker_embeddings.get("""repo_or_path""" , """/""" ) , voice_preset_paths[key] , subfolder=kwargs.pop("""subfolder""" , _a ) , cache_dir=kwargs.pop("""cache_dir""" , _a ) , force_download=kwargs.pop("""force_download""" , _a ) , proxies=kwargs.pop("""proxies""" , _a ) , resume_download=kwargs.pop("""resume_download""" , _a ) , local_files_only=kwargs.pop("""local_files_only""" , _a ) , use_auth_token=kwargs.pop("""use_auth_token""" , _a ) , revision=kwargs.pop("""revision""" , _a ) , ) if path is None: raise ValueError( F'''`{os.path.join(self.speaker_embeddings.get("repo_or_path" , "/" ) , voice_preset_paths[key] )}` does not exists , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset} embeddings.''' ) _A : List[str] = np.load(_a ) return voice_preset_dict def a__ ( self , _a = None ) -> Optional[int]: for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset: raise ValueError(F'''Voice preset unrecognized, missing {key} as a key.''' ) if not isinstance(voice_preset[key] , np.ndarray ): raise ValueError(F'''{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.''' ) if len(voice_preset[key].shape ) != self.preset_shape[key]: raise ValueError(F'''{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.''' ) def __call__( self , _a=None , _a=None , _a="pt" , _a=256 , _a=False , _a=True , _a=False , **_a , ) -> Tuple: if voice_preset is not None and not isinstance(_a , _a ): if ( isinstance(_a , _a ) and self.speaker_embeddings is not None and voice_preset in self.speaker_embeddings ): _A : Any = self._load_voice_preset(_a ) else: if isinstance(_a , _a ) and not voice_preset.endswith(""".npz""" ): _A : Optional[Any] = voice_preset + '.npz' _A : Union[str, Any] = np.load(_a ) if voice_preset is not None: self._validate_voice_preset_dict(_a , **_a ) _A : Tuple = BatchFeature(data=_a , tensor_type=_a ) _A : Any = self.tokenizer( _a , return_tensors=_a , padding="""max_length""" , max_length=_a , return_attention_mask=_a , return_token_type_ids=_a , add_special_tokens=_a , **_a , ) if voice_preset is not None: _A : Optional[int] = voice_preset return encoded_text
362
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer _snake_case = logging.get_logger(__name__) _snake_case = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _snake_case = { "vocab_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } _snake_case = { "vocab_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } _snake_case = { "vocab_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json" ), }, } _snake_case = { "facebook/dpr-ctx_encoder-single-nq-base": 512, "facebook/dpr-ctx_encoder-multiset-base": 512, } _snake_case = { "facebook/dpr-question_encoder-single-nq-base": 512, "facebook/dpr-question_encoder-multiset-base": 512, } _snake_case = { "facebook/dpr-reader-single-nq-base": 512, "facebook/dpr-reader-multiset-base": 512, } _snake_case = { "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True}, } _snake_case = { "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True}, } _snake_case = { "facebook/dpr-reader-single-nq-base": {"do_lower_case": True}, "facebook/dpr-reader-multiset-base": {"do_lower_case": True}, } class lowercase ( UpperCamelCase__ ): _a = VOCAB_FILES_NAMES _a = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _a = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION class lowercase ( UpperCamelCase__ ): _a = VOCAB_FILES_NAMES _a = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _a = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION _snake_case = collections.namedtuple( "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"] ) _snake_case = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"]) _snake_case = r"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n ```\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n ```\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Returns:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n " @add_start_docstrings(UpperCamelCase__ ) class lowercase : def __call__( self , _a , _a = None , _a = None , _a = False , _a = False , _a = None , _a = None , _a = None , **_a , ) -> BatchEncoding: if titles is None and texts is None: return super().__call__( _a , padding=_a , truncation=_a , max_length=_a , return_tensors=_a , return_attention_mask=_a , **_a , ) elif titles is None or texts is None: _A : Optional[Any] = titles if texts is None else texts return super().__call__( _a , _a , padding=_a , truncation=_a , max_length=_a , return_tensors=_a , return_attention_mask=_a , **_a , ) _A : Dict = titles if not isinstance(_a , _a ) else [titles] _A : Tuple = texts if not isinstance(_a , _a ) else [texts] _A : Any = len(_a ) _A : Optional[Any] = questions if not isinstance(_a , _a ) else [questions] * n_passages if len(_a ) != len(_a ): raise ValueError( F'''There should be as many titles than texts but got {len(_a )} titles and {len(_a )} texts.''' ) _A : str = super().__call__(_a , _a , padding=_a , truncation=_a )["""input_ids"""] _A : Optional[int] = super().__call__(_a , add_special_tokens=_a , padding=_a , truncation=_a )["""input_ids"""] _A : Optional[int] = { """input_ids""": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_a , _a ) ] } if return_attention_mask is not False: _A : Any = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) _A : str = attention_mask return self.pad(_a , padding=_a , max_length=_a , return_tensors=_a ) def a__ ( self , _a , _a , _a = 16 , _a = 64 , _a = 4 , ) -> List[DPRSpanPrediction]: _A : Dict = reader_input["""input_ids"""] _A , _A , _A : Tuple = reader_output[:3] _A : List[str] = len(_a ) _A : Tuple = sorted(range(_a ) , reverse=_a , key=relevance_logits.__getitem__ ) _A : List[DPRReaderOutput] = [] for doc_id in sorted_docs: _A : Tuple = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence _A : int = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: _A : Tuple = sequence_ids.index(self.pad_token_id ) else: _A : Tuple = len(_a ) _A : Union[str, Any] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_a , top_spans=_a , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_a , start_index=_a , end_index=_a , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_a ) >= num_spans: break return nbest_spans_predictions[:num_spans] def a__ ( self , _a , _a , _a , _a , ) -> List[DPRSpanPrediction]: _A : Tuple = [] for start_index, start_score in enumerate(_a ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) _A : Tuple = sorted(_a , key=lambda _a : x[1] , reverse=_a ) _A : Union[str, Any] = [] for (start_index, end_index), score in scores: if start_index > end_index: raise ValueError(F'''Wrong span indices: [{start_index}:{end_index}]''' ) _A : Dict = end_index - start_index + 1 if length > max_answer_length: raise ValueError(F'''Span is too long: {length} > {max_answer_length}''' ) if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_a ) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCamelCase__ ) class lowercase ( UpperCamelCase__,UpperCamelCase__ ): _a = VOCAB_FILES_NAMES _a = READER_PRETRAINED_VOCAB_FILES_MAP _a = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = READER_PRETRAINED_INIT_CONFIGURATION _a = ["input_ids", "attention_mask"]
343
0
from __future__ import annotations def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_ ): # noqa: E741 while r - l > 1: _A : List[str] = (l + r) // 2 if v[m] >= key: _A : Any = m else: _A : Tuple = m # noqa: E741 return r def lowerCAmelCase_ ( snake_case_ ): if len(_lowerCamelCase ) == 0: return 0 _A : int = [0] * len(_lowerCamelCase ) _A : Dict = 1 _A : Optional[Any] = v[0] for i in range(1,len(_lowerCamelCase ) ): if v[i] < tail[0]: _A : Optional[Any] = v[i] elif v[i] > tail[length - 1]: _A : Tuple = v[i] length += 1 else: _A : int = v[i] return length if __name__ == "__main__": import doctest doctest.testmod()
363
import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class lowercase ( unittest.TestCase ): @property def a__ ( self ) -> Dict: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def a__ ( self ) -> List[Any]: _A : int = ort.SessionOptions() _A : Any = False return options def a__ ( self ) -> Union[str, Any]: _A : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) _A : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) _A : List[str] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy""" ) # using the PNDM scheduler by default _A : str = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=_a , feature_extractor=_a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_a ) _A : Optional[Any] = """A red cat sitting on a park bench""" _A : Optional[Any] = np.random.RandomState(0 ) _A : Dict = pipe( prompt=_a , image=_a , mask_image=_a , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=_a , output_type="""np""" , ) _A : Optional[int] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1e-2
343
0
import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCriteria, MaxNewTokensCriteria, MaxTimeCriteria, StoppingCriteriaList, validate_stopping_criteria, ) @require_torch class lowercase ( unittest.TestCase ): def a__ ( self , _a ) -> List[str]: _A : str = 3 _A : Optional[int] = 250 _A : Tuple = ids_tensor((batch_size, length) , lowercase_ ) _A : int = torch.ones((batch_size, length) , device=lowercase_ , dtype=torch.float ) / length return input_ids, scores def a__ ( self ) -> Union[str, Any]: _A , _A : Dict = self._get_tensors(5 ) _A : str = StoppingCriteriaList( [ MaxLengthCriteria(max_length=10 ), MaxTimeCriteria(max_time=0.1 ), ] ) self.assertFalse(criteria(lowercase_ , lowercase_ ) ) _A , _A : Optional[int] = self._get_tensors(9 ) self.assertFalse(criteria(lowercase_ , lowercase_ ) ) _A , _A : int = self._get_tensors(10 ) self.assertTrue(criteria(lowercase_ , lowercase_ ) ) def a__ ( self ) -> Tuple: _A : Any = MaxLengthCriteria(max_length=10 ) _A , _A : Tuple = self._get_tensors(5 ) self.assertFalse(criteria(lowercase_ , lowercase_ ) ) _A , _A : Dict = self._get_tensors(9 ) self.assertFalse(criteria(lowercase_ , lowercase_ ) ) _A , _A : Union[str, Any] = self._get_tensors(10 ) self.assertTrue(criteria(lowercase_ , lowercase_ ) ) def a__ ( self ) -> str: _A : Tuple = MaxNewTokensCriteria(start_length=5 , max_new_tokens=5 ) _A , _A : Any = self._get_tensors(5 ) self.assertFalse(criteria(lowercase_ , lowercase_ ) ) _A , _A : Union[str, Any] = self._get_tensors(9 ) self.assertFalse(criteria(lowercase_ , lowercase_ ) ) _A , _A : Dict = self._get_tensors(10 ) self.assertTrue(criteria(lowercase_ , lowercase_ ) ) _A : List[Any] = StoppingCriteriaList([criteria] ) self.assertEqual(criteria_list.max_length , 10 ) def a__ ( self ) -> Any: _A , _A : List[Any] = self._get_tensors(5 ) _A : Union[str, Any] = MaxTimeCriteria(max_time=0.1 ) self.assertFalse(criteria(lowercase_ , lowercase_ ) ) _A : Dict = MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2 ) self.assertTrue(criteria(lowercase_ , lowercase_ ) ) def a__ ( self ) -> Tuple: validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 10 ) with self.assertWarns(lowercase_ ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 11 ) _A : List[str] = validate_stopping_criteria(StoppingCriteriaList() , 11 ) self.assertEqual(len(lowercase_ ) , 1 )
364
from __future__ import annotations def lowerCAmelCase_ ( snake_case_ ): create_state_space_tree(snake_case_,[],0,[0 for i in range(len(snake_case_ ) )] ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,): if index == len(snake_case_ ): print(snake_case_ ) return for i in range(len(snake_case_ ) ): if not index_used[i]: current_sequence.append(sequence[i] ) _A : Optional[Any] = True create_state_space_tree(snake_case_,snake_case_,index + 1,snake_case_ ) current_sequence.pop() _A : str = False _snake_case = [3, 1, 2, 4] generate_all_permutations(sequence) _snake_case = ["A", "B", "C"] generate_all_permutations(sequence_a)
343
0
"""simple docstring""" class lowercase : def __init__( self ) -> None: _A : dict[str, TrieNode] = {} # Mapping from char to TrieNode _A : Optional[int] = False def a__ ( self , _a ) -> None: for word in words: self.insert(_a ) def a__ ( self , _a ) -> None: _A : Tuple = self for char in word: if char not in curr.nodes: _A : Union[str, Any] = TrieNode() _A : str = curr.nodes[char] _A : Any = True def a__ ( self , _a ) -> bool: _A : Tuple = self for char in word: if char not in curr.nodes: return False _A : Dict = curr.nodes[char] return curr.is_leaf def a__ ( self , _a ) -> None: def _delete(_a , _a , _a ) -> bool: if index == len(_a ): # If word does not exist if not curr.is_leaf: return False _A : List[str] = False return len(curr.nodes ) == 0 _A : Union[str, Any] = word[index] _A : Dict = curr.nodes.get(_a ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted _A : Tuple = _delete(_a , _a , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , _a , 0 ) def lowerCAmelCase_ ( snake_case_,snake_case_ ): if node.is_leaf: print(__a,end=""" """ ) for key, value in node.nodes.items(): print_words(__a,word + key ) def lowerCAmelCase_ ( ): _A : int = '''banana bananas bandana band apple all beast'''.split() _A : Union[str, Any] = TrieNode() root.insert_many(__a ) # print_words(root, "") assert all(root.find(__a ) for word in words ) assert root.find("""banana""" ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) assert root.find("""apple""" ) assert root.find("""all""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def lowerCAmelCase_ ( snake_case_,snake_case_ ): print(str(__a ),"""works!""" if passes else """doesn\'t work :(""" ) def lowerCAmelCase_ ( ): assert test_trie() def lowerCAmelCase_ ( ): print_results("""Testing trie functionality""",test_trie() ) if __name__ == "__main__": main()
365
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def lowerCAmelCase_ ( snake_case_ ): _A : Tuple = filter(lambda snake_case_ : p.requires_grad,model.parameters() ) _A : str = sum([np.prod(p.size() ) for p in model_parameters] ) return params _snake_case = logging.getLogger(__name__) def lowerCAmelCase_ ( snake_case_,snake_case_ ): if metric == "rouge2": _A : Optional[int] = """{val_avg_rouge2:.4f}-{step_count}""" elif metric == "bleu": _A : Dict = """{val_avg_bleu:.4f}-{step_count}""" elif metric == "em": _A : List[str] = """{val_avg_em:.4f}-{step_count}""" else: raise NotImplementedError( f'''seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this''' """ function.""" ) _A : Optional[int] = ModelCheckpoint( dirpath=snake_case_,filename=snake_case_,monitor=f'''val_{metric}''',mode="""max""",save_top_k=3,every_n_epochs=1,) return checkpoint_callback def lowerCAmelCase_ ( snake_case_,snake_case_ ): return EarlyStopping( monitor=f'''val_{metric}''',mode="""min""" if """loss""" in metric else """max""",patience=snake_case_,verbose=snake_case_,) class lowercase ( pl.Callback ): def a__ ( self , _a , _a ) -> Optional[Any]: _A : List[Any] = {F'''lr_group_{i}''': param["""lr"""] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(_a ) @rank_zero_only def a__ ( self , _a , _a , _a , _a=True ) -> None: logger.info(F'''***** {type_path} results at step {trainer.global_step:05d} *****''' ) _A : int = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["""log""", """progress_bar""", """preds"""]} ) # Log results _A : Dict = Path(pl_module.hparams.output_dir ) if type_path == "test": _A : List[Any] = od / """test_results.txt""" _A : List[Any] = od / """test_generations.txt""" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _A : Optional[int] = od / F'''{type_path}_results/{trainer.global_step:05d}.txt''' _A : int = od / F'''{type_path}_generations/{trainer.global_step:05d}.txt''' results_file.parent.mkdir(exist_ok=_a ) generations_file.parent.mkdir(exist_ok=_a ) with open(_a , """a+""" ) as writer: for key in sorted(_a ): if key in ["log", "progress_bar", "preds"]: continue _A : List[Any] = metrics[key] if isinstance(_a , torch.Tensor ): _A : str = val.item() _A : str = F'''{key}: {val:.6f}\n''' writer.write(_a ) if not save_generations: return if "preds" in metrics: _A : List[Any] = """\n""".join(metrics["""preds"""] ) generations_file.open("""w+""" ).write(_a ) @rank_zero_only def a__ ( self , _a , _a ) -> str: try: _A : int = pl_module.model.model.num_parameters() except AttributeError: _A : str = pl_module.model.num_parameters() _A : Optional[int] = count_trainable_parameters(_a ) # mp stands for million parameters trainer.logger.log_metrics({"""n_params""": npars, """mp""": npars / 1e6, """grad_mp""": n_trainable_pars / 1e6} ) @rank_zero_only def a__ ( self , _a , _a ) -> Optional[int]: save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_a , _a , """test""" ) @rank_zero_only def a__ ( self , _a , _a ) -> Tuple: save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
343
0
import datasets _snake_case = "\\n@InProceedings{conneau2018xnli,\n author = \"Conneau, Alexis\n and Rinott, Ruty\n and Lample, Guillaume\n and Williams, Adina\n and Bowman, Samuel R.\n and Schwenk, Holger\n and Stoyanov, Veselin\",\n title = \"XNLI: Evaluating Cross-lingual Sentence Representations\",\n booktitle = \"Proceedings of the 2018 Conference on Empirical Methods\n in Natural Language Processing\",\n year = \"2018\",\n publisher = \"Association for Computational Linguistics\",\n location = \"Brussels, Belgium\",\n}\n" _snake_case = "\\nXNLI is a subset of a few thousand examples from MNLI which has been translated\ninto a 14 different languages (some low-ish resource). As with MNLI, the goal is\nto predict textual entailment (does sentence A imply/contradict/neither sentence\nB) and is a classification task (given two sentences, predict one of three\nlabels).\n" _snake_case = "\nComputes XNLI score which is just simple accuracy.\nArgs:\n predictions: Predicted labels.\n references: Ground truth labels.\nReturns:\n \'accuracy\': accuracy\nExamples:\n\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> xnli_metric = datasets.load_metric(\"xnli\")\n >>> results = xnli_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n" def lowerCAmelCase_ ( snake_case_,snake_case_ ): return (preds == labels).mean() @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,_KWARGS_DESCRIPTION ) class lowercase ( datasets.Metric ): def a__ ( self ) -> Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), """references""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), } ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" , ) def a__ ( self , _a , _a ) -> Optional[Any]: return {"accuracy": simple_accuracy(__UpperCAmelCase , __UpperCAmelCase )}
366
from __future__ import annotations from collections.abc import Callable _snake_case = list[list[float | int]] def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : int = len(snake_case_ ) _A : Matrix = [[0 for _ in range(size + 1 )] for _ in range(snake_case_ )] _A : int _A : int _A : int _A : int _A : int _A : float for row in range(snake_case_ ): for col in range(snake_case_ ): _A : Dict = matrix[row][col] _A : List[Any] = vector[row][0] _A : List[Any] = 0 _A : Optional[Any] = 0 while row < size and col < size: # pivoting _A : Any = max((abs(augmented[rowa][col] ), rowa) for rowa in range(snake_case_,snake_case_ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: _A , _A : Optional[Any] = augmented[pivot_row], augmented[row] for rowa in range(row + 1,snake_case_ ): _A : str = augmented[rowa][col] / augmented[row][col] _A : List[Any] = 0 for cola in range(col + 1,size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1,snake_case_ ): for row in range(snake_case_ ): _A : int = augmented[row][col] / augmented[col][col] for cola in range(snake_case_,size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row],10 )] for row in range(snake_case_ ) ] def lowerCAmelCase_ ( snake_case_ ): _A : int = len(snake_case_ ) _A : Matrix = [[0 for _ in range(snake_case_ )] for _ in range(snake_case_ )] _A : Matrix = [[0] for _ in range(snake_case_ )] _A : Matrix _A : int _A : int _A : int for x_val, y_val in enumerate(snake_case_ ): for col in range(snake_case_ ): _A : str = (x_val + 1) ** (size - col - 1) _A : List[str] = y_val _A : Any = solve(snake_case_,snake_case_ ) def interpolated_func(snake_case_ ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(snake_case_ ) ) return interpolated_func def lowerCAmelCase_ ( snake_case_ ): return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def lowerCAmelCase_ ( snake_case_ = question_function,snake_case_ = 10 ): _A : list[int] = [func(snake_case_ ) for x_val in range(1,order + 1 )] _A : list[Callable[[int], int]] = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1,order + 1 ) ] _A : int = 0 _A : Callable[[int], int] _A : int for poly in polynomials: _A : Optional[int] = 1 while func(snake_case_ ) == poly(snake_case_ ): x_val += 1 ret += poly(snake_case_ ) return ret if __name__ == "__main__": print(f"""{solution() = }""")
343
0
from ..utils import DummyObject, requires_backends class lowercase ( metaclass=UpperCamelCase__ ): _a = ['''keras_nlp'''] def __init__( self , *_a , **_a ) -> List[str]: requires_backends(self , ["""keras_nlp"""] )
367
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup _snake_case = "https://www.indeed.co.in/jobs?q=mobile+app+development&l=" def lowerCAmelCase_ ( snake_case_ = "mumbai" ): _A : Optional[Any] = BeautifulSoup(requests.get(url + location ).content,"""html.parser""" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("""div""",attrs={"""data-tn-component""": """organicJob"""} ): _A : Tuple = job.find("""a""",attrs={"""data-tn-element""": """jobTitle"""} ).text.strip() _A : Optional[int] = job.find("""span""",{"""class""": """company"""} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs("Bangalore"), 1): print(f"""Job {i:>2} is {job[0]} at {job[1]}""")
343
0
import argparse import glob import logging import os import sys import time from collections import defaultdict from pathlib import Path from typing import Dict, List, Tuple import numpy as np import pytorch_lightning as pl import torch from callbacks import SeqaSeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback from torch import nn from torch.utils.data import DataLoader from transformers import MBartTokenizer, TaForConditionalGeneration from transformers.models.bart.modeling_bart import shift_tokens_right from utils import ( ROUGE_KEYS, LegacySeqaSeqDataset, SeqaSeqDataset, assert_all_frozen, calculate_bleu, calculate_rouge, check_output_dir, flatten_list, freeze_embeds, freeze_params, get_git_info, label_smoothed_nll_loss, lmap, pickle_save, save_git_info, save_json, use_task_specific_params, ) # need the parent dir module sys.path.insert(2, str(Path(__file__).resolve().parents[1])) from lightning_base import BaseTransformer, add_generic_args, generic_train # noqa _snake_case = logging.getLogger(__name__) class lowercase ( _UpperCamelCase ): _a = 'summarization' _a = ['loss'] _a = ROUGE_KEYS _a = 'rouge2' def __init__( self , _a , **_a ) -> Union[str, Any]: if hparams.sortish_sampler and hparams.gpus > 1: _A : int = False elif hparams.max_tokens_per_batch is not None: if hparams.gpus > 1: raise NotImplementedError("""Dynamic Batch size does not work for multi-gpu training""" ) if hparams.sortish_sampler: raise ValueError("""--sortish_sampler and --max_tokens_per_batch may not be used simultaneously""" ) super().__init__(_SCREAMING_SNAKE_CASE , num_labels=_SCREAMING_SNAKE_CASE , mode=self.mode , **_SCREAMING_SNAKE_CASE ) use_task_specific_params(self.model , """summarization""" ) save_git_info(self.hparams.output_dir ) _A : Union[str, Any] = Path(self.output_dir ) / """metrics.json""" _A : Optional[int] = Path(self.output_dir ) / """hparams.pkl""" pickle_save(self.hparams , self.hparams_save_path ) _A : Optional[Any] = 0 _A : Optional[int] = defaultdict(_SCREAMING_SNAKE_CASE ) _A : Optional[Any] = self.config.model_type _A : Tuple = self.config.tgt_vocab_size if self.model_type == """fsmt""" else self.config.vocab_size _A : Union[str, Any] = { """data_dir""": self.hparams.data_dir, """max_source_length""": self.hparams.max_source_length, """prefix""": self.model.config.prefix or """""", } _A : Tuple = { """train""": self.hparams.n_train, """val""": self.hparams.n_val, """test""": self.hparams.n_test, } _A : Dict = {k: v if v >= 0 else None for k, v in n_observations_per_split.items()} _A : List[Any] = { """train""": self.hparams.max_target_length, """val""": self.hparams.val_max_target_length, """test""": self.hparams.test_max_target_length, } assert self.target_lens["train"] <= self.target_lens["val"], F'''target_lens: {self.target_lens}''' assert self.target_lens["train"] <= self.target_lens["test"], F'''target_lens: {self.target_lens}''' if self.hparams.freeze_embeds: freeze_embeds(self.model ) if self.hparams.freeze_encoder: freeze_params(self.model.get_encoder() ) assert_all_frozen(self.model.get_encoder() ) _A : Dict = get_git_info()["""repo_sha"""] _A : int = hparams.num_workers _A : List[str] = None # default to config if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer , _SCREAMING_SNAKE_CASE ): _A : Optional[int] = self.tokenizer.lang_code_to_id[hparams.tgt_lang] _A : Union[str, Any] = self.decoder_start_token_id _A : Tuple = ( SeqaSeqDataset if hasattr(self.tokenizer , """prepare_seq2seq_batch""" ) else LegacySeqaSeqDataset ) _A : Optional[Any] = False _A : str = self.model.config.num_beams if self.hparams.eval_beams is None else self.hparams.eval_beams if self.hparams.eval_max_gen_length is not None: _A : Optional[int] = self.hparams.eval_max_gen_length else: _A : int = self.model.config.max_length _A : Tuple = self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric def a__ ( self , _a ) -> Dict[str, List[str]]: _A : Tuple = { k: self.tokenizer.batch_decode(v.tolist() ) if """mask""" not in k else v.shape for k, v in batch.items() } save_json(_SCREAMING_SNAKE_CASE , Path(self.output_dir ) / """text_batch.json""" ) save_json({k: v.tolist() for k, v in batch.items()} , Path(self.output_dir ) / """tok_batch.json""" ) _A : Any = True return readable_batch def a__ ( self , _a , **_a ) -> Dict: return self.model(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def a__ ( self , _a ) -> Optional[int]: _A : Tuple = self.tokenizer.batch_decode( _SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE ) return lmap(str.strip , _SCREAMING_SNAKE_CASE ) def a__ ( self , _a ) -> Tuple: _A : Union[str, Any] = self.tokenizer.pad_token_id _A , _A : Optional[int] = batch["""input_ids"""], batch["""attention_mask"""] _A : Dict = batch["""labels"""] if isinstance(self.model , _SCREAMING_SNAKE_CASE ): _A : str = self.model._shift_right(_SCREAMING_SNAKE_CASE ) else: _A : Union[str, Any] = shift_tokens_right(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not self.already_saved_batch: # This would be slightly better if it only happened on rank zero _A : int = decoder_input_ids self.save_readable_batch(_SCREAMING_SNAKE_CASE ) _A : Optional[Any] = self(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , decoder_input_ids=_SCREAMING_SNAKE_CASE , use_cache=_SCREAMING_SNAKE_CASE ) _A : Tuple = outputs["""logits"""] if self.hparams.label_smoothing == 0: # Same behavior as modeling_bart.py, besides ignoring pad_token_id _A : List[str] = nn.CrossEntropyLoss(ignore_index=_SCREAMING_SNAKE_CASE ) assert lm_logits.shape[-1] == self.vocab_size _A : List[str] = ce_loss_fct(lm_logits.view(-1 , lm_logits.shape[-1] ) , tgt_ids.view(-1 ) ) else: _A : List[str] = nn.functional.log_softmax(_SCREAMING_SNAKE_CASE , dim=-1 ) _A , _A : int = label_smoothed_nll_loss( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.hparams.label_smoothing , ignore_index=_SCREAMING_SNAKE_CASE ) return (loss,) @property def a__ ( self ) -> int: return self.tokenizer.pad_token_id def a__ ( self , _a , _a ) -> Dict: _A : Dict = self._step(_SCREAMING_SNAKE_CASE ) _A : Tuple = dict(zip(self.loss_names , _SCREAMING_SNAKE_CASE ) ) # tokens per batch _A : int = batch["""input_ids"""].ne(self.pad ).sum() + batch["""labels"""].ne(self.pad ).sum() _A : List[str] = batch["""input_ids"""].shape[0] _A : Optional[int] = batch["""input_ids"""].eq(self.pad ).sum() _A : Tuple = batch["""input_ids"""].eq(self.pad ).float().mean() # TODO(SS): make a wandb summary metric for this return {"loss": loss_tensors[0], "log": logs} def a__ ( self , _a , _a ) -> Dict: return self._generative_step(_SCREAMING_SNAKE_CASE ) def a__ ( self , _a , _a="val" ) -> Dict: self.step_count += 1 _A : Tuple = {k: torch.stack([x[k] for x in outputs] ).mean() for k in self.loss_names} _A : Union[str, Any] = losses["""loss"""] _A : Tuple = { k: np.array([x[k] for x in outputs] ).mean() for k in self.metric_names + ["""gen_time""", """gen_len"""] } _A : str = ( generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric] ) _A : Optional[Any] = torch.tensor(_SCREAMING_SNAKE_CASE ).type_as(_SCREAMING_SNAKE_CASE ) generative_metrics.update({k: v.item() for k, v in losses.items()} ) losses.update(_SCREAMING_SNAKE_CASE ) _A : Union[str, Any] = {F'''{prefix}_avg_{k}''': x for k, x in losses.items()} _A : Optional[int] = self.step_count self.metrics[prefix].append(_SCREAMING_SNAKE_CASE ) # callback writes this to self.metrics_save_path _A : List[Any] = flatten_list([x["""preds"""] for x in outputs] ) return { "log": all_metrics, "preds": preds, F'''{prefix}_loss''': loss, F'''{prefix}_{self.val_metric}''': metric_tensor, } def a__ ( self , _a , _a ) -> Dict: return calculate_rouge(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def a__ ( self , _a ) -> dict: _A : List[Any] = time.time() # parser.add_argument('--eval_max_gen_length', type=int, default=None, help='never generate more than n tokens') _A : Any = self.model.generate( batch["""input_ids"""] , attention_mask=batch["""attention_mask"""] , use_cache=_SCREAMING_SNAKE_CASE , decoder_start_token_id=self.decoder_start_token_id , num_beams=self.eval_beams , max_length=self.eval_max_length , ) _A : str = (time.time() - ta) / batch["""input_ids"""].shape[0] _A : int = self.ids_to_clean_text(_SCREAMING_SNAKE_CASE ) _A : List[Any] = self.ids_to_clean_text(batch["""labels"""] ) _A : Tuple = self._step(_SCREAMING_SNAKE_CASE ) _A : Optional[Any] = dict(zip(self.loss_names , _SCREAMING_SNAKE_CASE ) ) _A : List[str] = self.calc_generative_metrics(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _A : Dict = np.mean(lmap(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) base_metrics.update(gen_time=_SCREAMING_SNAKE_CASE , gen_len=_SCREAMING_SNAKE_CASE , preds=_SCREAMING_SNAKE_CASE , target=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) return base_metrics def a__ ( self , _a , _a ) -> List[Any]: return self._generative_step(_SCREAMING_SNAKE_CASE ) def a__ ( self , _a ) -> Optional[int]: return self.validation_epoch_end(_SCREAMING_SNAKE_CASE , prefix="""test""" ) def a__ ( self , _a ) -> SeqaSeqDataset: _A : int = self.n_obs[type_path] _A : Optional[Any] = self.target_lens[type_path] _A : Optional[int] = self.dataset_class( self.tokenizer , type_path=_SCREAMING_SNAKE_CASE , n_obs=_SCREAMING_SNAKE_CASE , max_target_length=_SCREAMING_SNAKE_CASE , **self.dataset_kwargs , ) return dataset def a__ ( self , _a , _a , _a = False ) -> DataLoader: _A : Union[str, Any] = self.get_dataset(_SCREAMING_SNAKE_CASE ) if self.hparams.sortish_sampler and type_path != "test" and type_path != "val": _A : Optional[int] = dataset.make_sortish_sampler(_SCREAMING_SNAKE_CASE , distributed=self.hparams.gpus > 1 ) return DataLoader( _SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , collate_fn=dataset.collate_fn , shuffle=_SCREAMING_SNAKE_CASE , num_workers=self.num_workers , sampler=_SCREAMING_SNAKE_CASE , ) elif self.hparams.max_tokens_per_batch is not None and type_path != "test" and type_path != "val": _A : Optional[Any] = dataset.make_dynamic_sampler( self.hparams.max_tokens_per_batch , distributed=self.hparams.gpus > 1 ) return DataLoader( _SCREAMING_SNAKE_CASE , batch_sampler=_SCREAMING_SNAKE_CASE , collate_fn=dataset.collate_fn , num_workers=self.num_workers , ) else: return DataLoader( _SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , collate_fn=dataset.collate_fn , shuffle=_SCREAMING_SNAKE_CASE , num_workers=self.num_workers , sampler=_SCREAMING_SNAKE_CASE , ) def a__ ( self ) -> DataLoader: _A : int = self.get_dataloader("""train""" , batch_size=self.hparams.train_batch_size , shuffle=_SCREAMING_SNAKE_CASE ) return dataloader def a__ ( self ) -> DataLoader: return self.get_dataloader("""val""" , batch_size=self.hparams.eval_batch_size ) def a__ ( self ) -> DataLoader: return self.get_dataloader("""test""" , batch_size=self.hparams.eval_batch_size ) @staticmethod def a__ ( _a , _a ) -> Union[str, Any]: BaseTransformer.add_model_specific_args(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) add_generic_args(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) parser.add_argument( """--max_source_length""" , default=1024 , type=_SCREAMING_SNAKE_CASE , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--max_target_length""" , default=56 , type=_SCREAMING_SNAKE_CASE , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--val_max_target_length""" , default=142 , type=_SCREAMING_SNAKE_CASE , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--test_max_target_length""" , default=142 , type=_SCREAMING_SNAKE_CASE , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument("""--freeze_encoder""" , action="""store_true""" ) parser.add_argument("""--freeze_embeds""" , action="""store_true""" ) parser.add_argument("""--sortish_sampler""" , action="""store_true""" , default=_SCREAMING_SNAKE_CASE ) parser.add_argument("""--overwrite_output_dir""" , action="""store_true""" , default=_SCREAMING_SNAKE_CASE ) parser.add_argument("""--max_tokens_per_batch""" , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE ) parser.add_argument("""--logger_name""" , type=_SCREAMING_SNAKE_CASE , choices=["""default""", """wandb""", """wandb_shared"""] , default="""default""" ) parser.add_argument("""--n_train""" , type=_SCREAMING_SNAKE_CASE , default=-1 , required=_SCREAMING_SNAKE_CASE , help="""# examples. -1 means use all.""" ) parser.add_argument("""--n_val""" , type=_SCREAMING_SNAKE_CASE , default=500 , required=_SCREAMING_SNAKE_CASE , help="""# examples. -1 means use all.""" ) parser.add_argument("""--n_test""" , type=_SCREAMING_SNAKE_CASE , default=-1 , required=_SCREAMING_SNAKE_CASE , help="""# examples. -1 means use all.""" ) parser.add_argument( """--task""" , type=_SCREAMING_SNAKE_CASE , default="""summarization""" , required=_SCREAMING_SNAKE_CASE , help="""# examples. -1 means use all.""" ) parser.add_argument("""--label_smoothing""" , type=_SCREAMING_SNAKE_CASE , default=0.0 , required=_SCREAMING_SNAKE_CASE ) parser.add_argument("""--src_lang""" , type=_SCREAMING_SNAKE_CASE , default="""""" , required=_SCREAMING_SNAKE_CASE ) parser.add_argument("""--tgt_lang""" , type=_SCREAMING_SNAKE_CASE , default="""""" , required=_SCREAMING_SNAKE_CASE ) parser.add_argument("""--eval_beams""" , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE ) parser.add_argument( """--val_metric""" , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , choices=["""bleu""", """rouge2""", """loss""", None] ) parser.add_argument("""--eval_max_gen_length""" , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help="""never generate more than n tokens""" ) parser.add_argument("""--save_top_k""" , type=_SCREAMING_SNAKE_CASE , default=1 , required=_SCREAMING_SNAKE_CASE , help="""How many checkpoints to save""" ) parser.add_argument( """--early_stopping_patience""" , type=_SCREAMING_SNAKE_CASE , default=-1 , required=_SCREAMING_SNAKE_CASE , help=( """-1 means never early stop. early_stopping_patience is measured in validation checks, not epochs. So""" """ val_check_interval will effect it.""" ) , ) return parser class lowercase ( _UpperCamelCase ): _a = 'translation' _a = ['loss'] _a = ['bleu'] _a = 'bleu' def __init__( self , _a , **_a ) -> Tuple: super().__init__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) _A : Dict = hparams.src_lang _A : int = hparams.tgt_lang def a__ ( self , _a , _a ) -> dict: return calculate_bleu(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase_ ( snake_case_,snake_case_=None ): Path(args.output_dir ).mkdir(exist_ok=_UpperCamelCase ) check_output_dir(_UpperCamelCase,expected_items=3 ) if model is None: if "summarization" in args.task: _A : Union[str, Any] = SummarizationModule(_UpperCamelCase ) else: _A : Tuple = TranslationModule(_UpperCamelCase ) _A : int = Path(args.data_dir ).name if ( args.logger_name == "default" or args.fast_dev_run or str(args.output_dir ).startswith("""/tmp""" ) or str(args.output_dir ).startswith("""/var""" ) ): _A : Optional[Any] = True # don't pollute wandb logs unnecessarily elif args.logger_name == "wandb": from pytorch_lightning.loggers import WandbLogger _A : Dict = os.environ.get("""WANDB_PROJECT""",_UpperCamelCase ) _A : Optional[int] = WandbLogger(name=model.output_dir.name,project=_UpperCamelCase ) elif args.logger_name == "wandb_shared": from pytorch_lightning.loggers import WandbLogger _A : Any = WandbLogger(name=model.output_dir.name,project=f'''hf_{dataset}''' ) if args.early_stopping_patience >= 0: _A : int = get_early_stopping_callback(model.val_metric,args.early_stopping_patience ) else: _A : Optional[int] = False _A : List[str] = args.val_metric == """loss""" _A : List[str] = generic_train( _UpperCamelCase,_UpperCamelCase,logging_callback=SeqaSeqLoggingCallback(),checkpoint_callback=get_checkpoint_callback( args.output_dir,model.val_metric,args.save_top_k,_UpperCamelCase ),early_stopping_callback=_UpperCamelCase,logger=_UpperCamelCase,) pickle_save(model.hparams,model.output_dir / """hparams.pkl""" ) if not args.do_predict: return model _A : Tuple = """""" _A : Optional[int] = sorted(glob.glob(os.path.join(args.output_dir,"""*.ckpt""" ),recursive=_UpperCamelCase ) ) if checkpoints: _A : str = checkpoints[-1] _A : Dict = checkpoints[-1] trainer.logger.log_hyperparams(model.hparams ) # test() without a model tests using the best checkpoint automatically trainer.test() return model if __name__ == "__main__": _snake_case = argparse.ArgumentParser() _snake_case = pl.Trainer.add_argparse_args(parser) _snake_case = SummarizationModule.add_model_specific_args(parser, os.getcwd()) _snake_case = parser.parse_args() main(args)
368
from __future__ import annotations from decimal import Decimal from numpy import array def lowerCAmelCase_ ( snake_case_ ): _A : Tuple = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(snake_case_ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix _A : List[Any] = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creates a copy of the matrix with swapped positions of the elements _A : Tuple = [[0.0, 0.0], [0.0, 0.0]] _A , _A : List[str] = matrix[1][1], matrix[0][0] _A , _A : List[str] = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(snake_case_ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(snake_case_ ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule _A : List[str] = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creating cofactor matrix _A : List[Any] = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] _A : Union[str, Any] = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) _A : Optional[Any] = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) _A : Any = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) _A : List[Any] = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) _A : int = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) _A : Union[str, Any] = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) _A : Any = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) _A : List[str] = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) _A : Optional[int] = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) _A : List[Any] = array(snake_case_ ) for i in range(3 ): for j in range(3 ): _A : List[str] = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix _A : Union[str, Any] = array(snake_case_ ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(snake_case_ ) # Calculate the inverse of the matrix return [[float(d(snake_case_ ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError("""Please provide a matrix of size 2x2 or 3x3.""" )
343
0
"""simple docstring""" import copy import random from transformers import CLIPTokenizer class lowercase ( a__ ): def __init__( self , *_a , **_a ) -> List[Any]: super().__init__(*_lowerCamelCase , **_lowerCamelCase ) _A : Any = {} def a__ ( self , _a , *_a , **_a ) -> Optional[int]: _A : int = super().add_tokens(_lowerCamelCase , *_lowerCamelCase , **_lowerCamelCase ) if num_added_tokens == 0: raise ValueError( F'''The tokenizer already contains the token {placeholder_token}. Please pass a different''' """ `placeholder_token` that is not already in the tokenizer.""" ) def a__ ( self , _a , *_a , _a=1 , **_a ) -> int: _A : Dict = [] if num_vec_per_token == 1: self.try_adding_tokens(_lowerCamelCase , *_lowerCamelCase , **_lowerCamelCase ) output.append(_lowerCamelCase ) else: _A : Union[str, Any] = [] for i in range(_lowerCamelCase ): _A : Optional[int] = placeholder_token + F'''_{i}''' self.try_adding_tokens(_lowerCamelCase , *_lowerCamelCase , **_lowerCamelCase ) output.append(_lowerCamelCase ) # handle cases where there is a new placeholder token that contains the current placeholder token but is larger for token in self.token_map: if token in placeholder_token: raise ValueError( F'''The tokenizer already has placeholder token {token} that can get confused with''' F''' {placeholder_token}keep placeholder tokens independent''' ) _A : int = output def a__ ( self , _a , _a=False , _a=1.0 ) -> Any: if isinstance(_lowerCamelCase , _lowerCamelCase ): _A : List[Any] = [] for i in range(len(_lowerCamelCase ) ): output.append(self.replace_placeholder_tokens_in_text(text[i] , vector_shuffle=_lowerCamelCase ) ) return output for placeholder_token in self.token_map: if placeholder_token in text: _A : str = self.token_map[placeholder_token] _A : int = tokens[: 1 + int(len(_lowerCamelCase ) * prop_tokens_to_load )] if vector_shuffle: _A : Tuple = copy.copy(_lowerCamelCase ) random.shuffle(_lowerCamelCase ) _A : List[Any] = text.replace(_lowerCamelCase , """ """.join(_lowerCamelCase ) ) return text def __call__( self , _a , *_a , _a=False , _a=1.0 , **_a ) -> Optional[int]: return super().__call__( self.replace_placeholder_tokens_in_text( _lowerCamelCase , vector_shuffle=_lowerCamelCase , prop_tokens_to_load=_lowerCamelCase ) , *_lowerCamelCase , **_lowerCamelCase , ) def a__ ( self , _a , *_a , _a=False , _a=1.0 , **_a ) -> List[Any]: return super().encode( self.replace_placeholder_tokens_in_text( _lowerCamelCase , vector_shuffle=_lowerCamelCase , prop_tokens_to_load=_lowerCamelCase ) , *_lowerCamelCase , **_lowerCamelCase , )
369
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class lowercase ( UpperCamelCase__ ): _a = 42 class lowercase ( UpperCamelCase__,UpperCamelCase__ ): @register_to_config def __init__( self , _a = 32 , _a = 64 , _a = 20 , _a = 768 , _a=77 , _a=4 , _a = 0.0 , _a = "silu" , _a = None , _a = None , _a = "linear" , _a = "prd" , _a = None , _a = None , _a = None , ) -> Any: super().__init__() _A : int = num_attention_heads _A : Union[str, Any] = attention_head_dim _A : Tuple = num_attention_heads * attention_head_dim _A : Any = additional_embeddings _A : Any = time_embed_dim or inner_dim _A : List[str] = embedding_proj_dim or embedding_dim _A : Optional[int] = clip_embed_dim or embedding_dim _A : Union[str, Any] = Timesteps(_a , _a , 0 ) _A : str = TimestepEmbedding(_a , _a , out_dim=_a , act_fn=_a ) _A : Dict = nn.Linear(_a , _a ) if embedding_proj_norm_type is None: _A : int = None elif embedding_proj_norm_type == "layer": _A : Optional[Any] = nn.LayerNorm(_a ) else: raise ValueError(F'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}''' ) _A : Optional[Any] = nn.Linear(_a , _a ) if encoder_hid_proj_type is None: _A : Union[str, Any] = None elif encoder_hid_proj_type == "linear": _A : Tuple = nn.Linear(_a , _a ) else: raise ValueError(F'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}''' ) _A : List[str] = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , _a ) ) if added_emb_type == "prd": _A : str = nn.Parameter(torch.zeros(1 , 1 , _a ) ) elif added_emb_type is None: _A : Union[str, Any] = None else: raise ValueError( F'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.''' ) _A : int = nn.ModuleList( [ BasicTransformerBlock( _a , _a , _a , dropout=_a , activation_fn="""gelu""" , attention_bias=_a , ) for d in range(_a ) ] ) if norm_in_type == "layer": _A : Union[str, Any] = nn.LayerNorm(_a ) elif norm_in_type is None: _A : Tuple = None else: raise ValueError(F'''Unsupported norm_in_type: {norm_in_type}.''' ) _A : int = nn.LayerNorm(_a ) _A : str = nn.Linear(_a , _a ) _A : Any = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -10000.0 ) causal_attention_mask.triu_(1 ) _A : Optional[int] = causal_attention_mask[None, ...] self.register_buffer("""causal_attention_mask""" , _a , persistent=_a ) _A : Tuple = nn.Parameter(torch.zeros(1 , _a ) ) _A : Dict = nn.Parameter(torch.zeros(1 , _a ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def a__ ( self ) -> Dict[str, AttentionProcessor]: _A : List[str] = {} def fn_recursive_add_processors(_a , _a , _a ): if hasattr(_a , """set_processor""" ): _A : Tuple = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F'''{name}.{sub_name}''' , _a , _a ) return processors for name, module in self.named_children(): fn_recursive_add_processors(_a , _a , _a ) return processors def a__ ( self , _a ) -> List[str]: _A : Optional[int] = len(self.attn_processors.keys() ) if isinstance(_a , _a ) and len(_a ) != count: raise ValueError( F'''A dict of processors was passed, but the number of processors {len(_a )} does not match the''' F''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''' ) def fn_recursive_attn_processor(_a , _a , _a ): if hasattr(_a , """set_processor""" ): if not isinstance(_a , _a ): module.set_processor(_a ) else: module.set_processor(processor.pop(F'''{name}.processor''' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F'''{name}.{sub_name}''' , _a , _a ) for name, module in self.named_children(): fn_recursive_attn_processor(_a , _a , _a ) def a__ ( self ) -> Union[str, Any]: self.set_attn_processor(AttnProcessor() ) def a__ ( self , _a , _a , _a , _a = None , _a = None , _a = True , ) -> Optional[Any]: _A : Tuple = hidden_states.shape[0] _A : List[Any] = timestep if not torch.is_tensor(_a ): _A : Dict = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(_a ) and len(timesteps.shape ) == 0: _A : Tuple = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML _A : Optional[int] = timesteps * torch.ones(_a , dtype=timesteps.dtype , device=timesteps.device ) _A : Dict = self.time_proj(_a ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. _A : Tuple = timesteps_projected.to(dtype=self.dtype ) _A : List[Any] = self.time_embedding(_a ) if self.embedding_proj_norm is not None: _A : Dict = self.embedding_proj_norm(_a ) _A : List[Any] = self.embedding_proj(_a ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: _A : List[Any] = self.encoder_hidden_states_proj(_a ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""" ) _A : Optional[int] = self.proj_in(_a ) _A : Optional[int] = self.positional_embedding.to(hidden_states.dtype ) _A : Union[str, Any] = [] _A : List[str] = 0 if encoder_hidden_states is not None: additional_embeds.append(_a ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: _A : List[str] = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: _A : List[str] = hidden_states[:, None, :] _A : Dict = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: _A : Optional[int] = self.prd_embedding.to(hidden_states.dtype ).expand(_a , -1 , -1 ) additional_embeds.append(_a ) _A : str = torch.cat( _a , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens _A : Dict = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: _A : Union[str, Any] = F.pad( _a , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) _A : Optional[Any] = hidden_states + positional_embeddings if attention_mask is not None: _A : Optional[Any] = (1 - attention_mask.to(hidden_states.dtype )) * -10000.0 _A : List[Any] = F.pad(_a , (0, self.additional_embeddings) , value=0.0 ) _A : Optional[Any] = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) _A : int = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: _A : str = self.norm_in(_a ) for block in self.transformer_blocks: _A : List[Any] = block(_a , attention_mask=_a ) _A : Any = self.norm_out(_a ) if self.prd_embedding is not None: _A : int = hidden_states[:, -1] else: _A : Any = hidden_states[:, additional_embeddings_len:] _A : Union[str, Any] = self.proj_to_clip_embeddings(_a ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=_a ) def a__ ( self , _a ) -> Tuple: _A : List[Any] = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
343
0
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class lowercase ( unittest.TestCase ): def __init__( self , _a , _a=7 , _a=3 , _a=18 , _a=30 , _a=400 , _a=True , _a=None , _a=True , _a=None , ) -> Union[str, Any]: _A : Tuple = size if size is not None else {"""shortest_edge""": 20} _A : Union[str, Any] = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} _A : List[str] = parent _A : Union[str, Any] = batch_size _A : Dict = num_channels _A : Dict = image_size _A : Optional[Any] = min_resolution _A : Tuple = max_resolution _A : int = do_resize _A : int = size _A : List[str] = do_center_crop _A : Any = crop_size def a__ ( self ) -> int: return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, } @require_torch @require_vision class lowercase ( __UpperCamelCase,unittest.TestCase ): _a = MobileNetVaImageProcessor if is_vision_available() else None def a__ ( self ) -> List[Any]: _A : Optional[int] = MobileNetVaImageProcessingTester(self ) @property def a__ ( self ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def a__ ( self ) -> Optional[Any]: _A : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCAmelCase , """do_resize""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """size""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """do_center_crop""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """crop_size""" ) ) def a__ ( self ) -> Union[str, Any]: _A : str = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 20} ) self.assertEqual(image_processor.crop_size , {"""height""": 18, """width""": 18} ) _A : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) def a__ ( self ) -> int: pass def a__ ( self ) -> Any: # Initialize image_processing _A : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _A : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(_lowerCAmelCase , Image.Image ) # Test not batched input _A : List[str] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched _A : Optional[Any] = image_processing(_lowerCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def a__ ( self ) -> Tuple: # Initialize image_processing _A : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _A : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCAmelCase , numpify=_lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(_lowerCAmelCase , np.ndarray ) # Test not batched input _A : int = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched _A : int = image_processing(_lowerCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def a__ ( self ) -> Optional[Any]: # Initialize image_processing _A : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _A : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCAmelCase , torchify=_lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(_lowerCAmelCase , torch.Tensor ) # Test not batched input _A : int = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched _A : Tuple = image_processing(_lowerCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , )
370
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : Any = None if token is not None: _A : int = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} _A : Any = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' _A : Union[str, Any] = requests.get(snake_case_,headers=snake_case_ ).json() _A : str = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) _A : int = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(snake_case_ ): _A : List[str] = requests.get(url + f'''&page={i + 2}''',headers=snake_case_ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : int = None if token is not None: _A : List[str] = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} _A : str = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100''' _A : Optional[Any] = requests.get(snake_case_,headers=snake_case_ ).json() _A : Any = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) _A : Tuple = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(snake_case_ ): _A : List[Any] = requests.get(url + f'''&page={i + 2}''',headers=snake_case_ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_ ): _A : Dict = None if token is not None: _A : int = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} _A : Tuple = requests.get(snake_case_,headers=snake_case_,allow_redirects=snake_case_ ) _A : Tuple = result.headers["""Location"""] _A : Union[str, Any] = requests.get(snake_case_,allow_redirects=snake_case_ ) _A : Dict = os.path.join(snake_case_,f'''{artifact_name}.zip''' ) with open(snake_case_,"""wb""" ) as fp: fp.write(response.content ) def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : List[str] = [] _A : int = [] _A : Tuple = None with zipfile.ZipFile(snake_case_ ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case_ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(snake_case_ ) as f: for line in f: _A : Any = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs _A : Dict = line[: line.index(""": """ )] _A : Dict = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed _A : List[str] = line[len("""FAILED """ ) :] failed_tests.append(snake_case_ ) elif filename == "job_name.txt": _A : Optional[int] = line if len(snake_case_ ) != len(snake_case_ ): raise ValueError( f'''`errors` and `failed_tests` should have the same number of elements. Got {len(snake_case_ )} for `errors` ''' f'''and {len(snake_case_ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some''' """ problem.""" ) _A : Any = None if job_name and job_links: _A : Dict = job_links.get(snake_case_,snake_case_ ) # A list with elements of the form (line of error, error, failed test) _A : Optional[int] = [x + [y] + [job_link] for x, y in zip(snake_case_,snake_case_ )] return result def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : Dict = [] _A : Optional[int] = [os.path.join(snake_case_,snake_case_ ) for p in os.listdir(snake_case_ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(snake_case_,job_links=snake_case_ ) ) return errors def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : Dict = Counter() counter.update([x[1] for x in logs] ) _A : Tuple = counter.most_common() _A : Tuple = {} for error, count in counts: if error_filter is None or error not in error_filter: _A : str = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} _A : Union[str, Any] = dict(sorted(r.items(),key=lambda snake_case_ : item[1]["count"],reverse=snake_case_ ) ) return r def lowerCAmelCase_ ( snake_case_ ): _A : Union[str, Any] = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): _A : Dict = test.split("""/""" )[2] else: _A : str = None return test def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : str = [(x[0], x[1], get_model(x[2] )) for x in logs] _A : Union[str, Any] = [x for x in logs if x[2] is not None] _A : Optional[Any] = {x[2] for x in logs} _A : List[Any] = {} for test in tests: _A : Any = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) _A : Union[str, Any] = counter.most_common() _A : Any = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} _A : str = sum(error_counts.values() ) if n_errors > 0: _A : Optional[int] = {"""count""": n_errors, """errors""": error_counts} _A : Union[str, Any] = dict(sorted(r.items(),key=lambda snake_case_ : item[1]["count"],reverse=snake_case_ ) ) return r def lowerCAmelCase_ ( snake_case_ ): _A : Optional[int] = """| no. | error | status |""" _A : List[Any] = """|-:|:-|:-|""" _A : List[Any] = [header, sep] for error in reduced_by_error: _A : List[str] = reduced_by_error[error]["""count"""] _A : List[Any] = f'''| {count} | {error[:100]} | |''' lines.append(snake_case_ ) return "\n".join(snake_case_ ) def lowerCAmelCase_ ( snake_case_ ): _A : List[Any] = """| model | no. of errors | major error | count |""" _A : Optional[Any] = """|-:|-:|-:|-:|""" _A : Union[str, Any] = [header, sep] for model in reduced_by_model: _A : Dict = reduced_by_model[model]["""count"""] _A , _A : str = list(reduced_by_model[model]["""errors"""].items() )[0] _A : Union[str, Any] = f'''| {model} | {count} | {error[:60]} | {_count} |''' lines.append(snake_case_ ) return "\n".join(snake_case_ ) if __name__ == "__main__": _snake_case = 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.") _snake_case = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) _snake_case = get_job_links(args.workflow_run_id, token=args.token) _snake_case = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: _snake_case = k.find(" / ") _snake_case = k[index + len(" / ") :] _snake_case = v with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) _snake_case = 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) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) _snake_case = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error _snake_case = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors _snake_case = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) _snake_case = reduce_by_error(errors) _snake_case = reduce_by_model(errors) _snake_case = make_github_table(reduced_by_error) _snake_case = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: fp.write(sa) with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: fp.write(sa)
343
0
import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, SkipDataLoader, skip_first_batches, ) class lowercase ( _UpperCAmelCase ): """simple docstring""" def __init__( self , _a=0.01 , _a=1000 ) -> str: _A : List[Any] = p_stop _A : List[Any] = max_length def __iter__( self ) -> Optional[Any]: _A : List[str] = 0 _A : Union[str, Any] = False while not stop and count < self.max_length: yield count count += 1 _A : Optional[Any] = random.random() < self.p_stop class lowercase ( unittest.TestCase ): """simple docstring""" def a__ ( self , _a , _a , _a=False , _a=True ) -> str: _A : List[str] = [ BatchSamplerShard(lowercase_ , 2 , lowercase_ , split_batches=lowercase_ , even_batches=lowercase_ ) for i in range(2 ) ] _A : Dict = [list(lowercase_ ) for batch_sampler_shard in batch_sampler_shards] if not split_batches: self.assertListEqual([len(lowercase_ ) for shard in batch_sampler_shards] , [len(lowercase_ ) for e in expected] ) self.assertListEqual(lowercase_ , lowercase_ ) def a__ ( self ) -> List[str]: # Check the shards when the dataset is a round multiple of total batch size. _A : Optional[Any] = BatchSampler(range(24 ) , batch_size=3 , drop_last=lowercase_ ) _A : int = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ ) _A : Any = BatchSampler(range(24 ) , batch_size=3 , drop_last=lowercase_ ) # Expected shouldn't change self.check_batch_sampler_shards(lowercase_ , lowercase_ ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. _A : Union[str, Any] = BatchSampler(range(21 ) , batch_size=3 , drop_last=lowercase_ ) _A : Any = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [0, 1, 2]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ ) _A : int = BatchSampler(range(21 ) , batch_size=3 , drop_last=lowercase_ ) _A : Dict = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. _A : List[Any] = BatchSampler(range(22 ) , batch_size=3 , drop_last=lowercase_ ) _A : List[Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 0, 1]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ ) _A : Optional[int] = BatchSampler(range(22 ) , batch_size=3 , drop_last=lowercase_ ) _A : Optional[int] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. _A : Optional[Any] = BatchSampler(range(20 ) , batch_size=3 , drop_last=lowercase_ ) _A : List[str] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 0]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [1, 2, 3]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ ) _A : Union[str, Any] = BatchSampler(range(20 ) , batch_size=3 , drop_last=lowercase_ ) _A : List[str] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ ) # Check the shards when the dataset is very small. _A : int = BatchSampler(range(2 ) , batch_size=3 , drop_last=lowercase_ ) _A : Optional[Any] = [[[0, 1, 0]], [[1, 0, 1]]] self.check_batch_sampler_shards(lowercase_ , lowercase_ ) _A : Optional[int] = BatchSampler(range(2 ) , batch_size=3 , drop_last=lowercase_ ) _A : Any = [[], []] self.check_batch_sampler_shards(lowercase_ , lowercase_ ) def a__ ( self ) -> str: # Check the shards when the dataset is a round multiple of batch size. _A : Optional[Any] = BatchSampler(range(24 ) , batch_size=4 , drop_last=lowercase_ ) _A : Union[str, Any] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ ) _A : Union[str, Any] = BatchSampler(range(24 ) , batch_size=4 , drop_last=lowercase_ ) # Expected shouldn't change self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ ) # Check the shards when the dataset is not a round multiple of batch size. _A : Union[str, Any] = BatchSampler(range(22 ) , batch_size=4 , drop_last=lowercase_ ) _A : Any = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [0, 1]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ ) _A : Dict = BatchSampler(range(22 ) , batch_size=4 , drop_last=lowercase_ ) _A : List[Any] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. _A : str = BatchSampler(range(21 ) , batch_size=4 , drop_last=lowercase_ ) _A : List[str] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 0]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [1, 2]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ ) _A : str = BatchSampler(range(21 ) , batch_size=4 , drop_last=lowercase_ ) _A : str = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ ) # Check the shards when the dataset is very small. _A : int = BatchSampler(range(2 ) , batch_size=4 , drop_last=lowercase_ ) _A : Tuple = [[[0, 1]], [[0, 1]]] self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ ) _A : List[str] = BatchSampler(range(2 ) , batch_size=4 , drop_last=lowercase_ ) _A : List[str] = [[], []] self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ ) def a__ ( self ) -> List[Any]: # Check the shards when the dataset is a round multiple of total batch size. _A : List[str] = BatchSampler(range(24 ) , batch_size=3 , drop_last=lowercase_ ) _A : Optional[Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , even_batches=lowercase_ ) _A : Tuple = BatchSampler(range(24 ) , batch_size=3 , drop_last=lowercase_ ) # Expected shouldn't change self.check_batch_sampler_shards(lowercase_ , lowercase_ , even_batches=lowercase_ ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. _A : Optional[Any] = BatchSampler(range(21 ) , batch_size=3 , drop_last=lowercase_ ) _A : List[Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , even_batches=lowercase_ ) _A : Tuple = BatchSampler(range(21 ) , batch_size=3 , drop_last=lowercase_ ) _A : Any = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , even_batches=lowercase_ ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. _A : Dict = BatchSampler(range(22 ) , batch_size=3 , drop_last=lowercase_ ) _A : List[str] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , even_batches=lowercase_ ) _A : Union[str, Any] = BatchSampler(range(22 ) , batch_size=3 , drop_last=lowercase_ ) _A : List[Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , even_batches=lowercase_ ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. _A : Optional[int] = BatchSampler(range(20 ) , batch_size=3 , drop_last=lowercase_ ) _A : int = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , even_batches=lowercase_ ) _A : Dict = BatchSampler(range(20 ) , batch_size=3 , drop_last=lowercase_ ) _A : Optional[Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , even_batches=lowercase_ ) # Check the shards when the dataset is very small. _A : Tuple = BatchSampler(range(2 ) , batch_size=3 , drop_last=lowercase_ ) _A : List[str] = [[[0, 1]], []] self.check_batch_sampler_shards(lowercase_ , lowercase_ , even_batches=lowercase_ ) _A : Optional[int] = BatchSampler(range(2 ) , batch_size=3 , drop_last=lowercase_ ) _A : Any = [[], []] self.check_batch_sampler_shards(lowercase_ , lowercase_ , even_batches=lowercase_ ) def a__ ( self ) -> str: # Check the shards when the dataset is a round multiple of batch size. _A : Tuple = BatchSampler(range(24 ) , batch_size=4 , drop_last=lowercase_ ) _A : Union[str, Any] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ , even_batches=lowercase_ ) _A : int = BatchSampler(range(24 ) , batch_size=4 , drop_last=lowercase_ ) # Expected shouldn't change self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ , even_batches=lowercase_ ) # Check the shards when the dataset is not a round multiple of batch size. _A : Dict = BatchSampler(range(22 ) , batch_size=4 , drop_last=lowercase_ ) _A : Any = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ , even_batches=lowercase_ ) _A : Optional[int] = BatchSampler(range(22 ) , batch_size=4 , drop_last=lowercase_ ) _A : Optional[int] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ , even_batches=lowercase_ ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. _A : Any = BatchSampler(range(21 ) , batch_size=4 , drop_last=lowercase_ ) _A : int = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ , even_batches=lowercase_ ) _A : Union[str, Any] = BatchSampler(range(21 ) , batch_size=4 , drop_last=lowercase_ ) _A : int = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ , even_batches=lowercase_ ) # Check the shards when the dataset is very small. _A : Optional[Any] = BatchSampler(range(2 ) , batch_size=4 , drop_last=lowercase_ ) _A : int = [[[0, 1]], []] self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ , even_batches=lowercase_ ) _A : str = BatchSampler(range(2 ) , batch_size=4 , drop_last=lowercase_ ) _A : str = [[], []] self.check_batch_sampler_shards(lowercase_ , lowercase_ , split_batches=lowercase_ , even_batches=lowercase_ ) def a__ ( self ) -> Optional[Any]: _A : List[str] = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 10, 11], [12, 13]] _A : str = [BatchSamplerShard(lowercase_ , 2 , lowercase_ , even_batches=lowercase_ ) for i in range(2 )] self.assertEqual(len(batch_sampler_shards[0] ) , 3 ) self.assertEqual(len(batch_sampler_shards[1] ) , 2 ) self.assertListEqual(list(batch_sampler_shards[0] ) , [[0, 1, 2], [5, 6, 7, 8], [12, 13]] ) self.assertListEqual(list(batch_sampler_shards[1] ) , [[3, 4], [9, 10, 11]] ) def a__ ( self , _a , _a , _a , _a=False , _a=2 , _a=False ) -> str: random.seed(lowercase_ ) _A : List[str] = list(lowercase_ ) _A : Optional[Any] = [ IterableDatasetShard( lowercase_ , batch_size=lowercase_ , drop_last=lowercase_ , num_processes=lowercase_ , process_index=lowercase_ , split_batches=lowercase_ , ) for i in range(lowercase_ ) ] _A : List[str] = [] for iterable_dataset_shard in iterable_dataset_shards: # Since our random iterable dataset will be... random... we need to use a seed to get reproducible results. random.seed(lowercase_ ) iterable_dataset_lists.append(list(lowercase_ ) ) _A : Dict = batch_size // num_processes if split_batches else batch_size # All iterable dataset shard should have the same length, a round multiple of shard_batch_size _A : str = iterable_dataset_lists[0] for l in iterable_dataset_lists[1:]: self.assertEqual(len(lowercase_ ) , len(lowercase_ ) ) self.assertTrue(len(lowercase_ ) % shard_batch_size == 0 ) _A : int = [] for idx in range(0 , len(lowercase_ ) , lowercase_ ): for l in iterable_dataset_lists: observed += l[idx : idx + shard_batch_size] if not drop_last: while len(lowercase_ ) < len(lowercase_ ): reference += reference self.assertListEqual(lowercase_ , reference[: len(lowercase_ )] ) def a__ ( self ) -> Optional[int]: _A : Tuple = 42 _A : Dict = RandomIterableDataset() self.check_iterable_dataset_shards(lowercase_ , lowercase_ , batch_size=4 , drop_last=lowercase_ , split_batches=lowercase_ ) self.check_iterable_dataset_shards(lowercase_ , lowercase_ , batch_size=4 , drop_last=lowercase_ , split_batches=lowercase_ ) self.check_iterable_dataset_shards(lowercase_ , lowercase_ , batch_size=4 , drop_last=lowercase_ , split_batches=lowercase_ ) self.check_iterable_dataset_shards(lowercase_ , lowercase_ , batch_size=4 , drop_last=lowercase_ , split_batches=lowercase_ ) # Edge case with a very small dataset _A : Tuple = RandomIterableDataset(max_length=2 ) self.check_iterable_dataset_shards(lowercase_ , lowercase_ , batch_size=4 , drop_last=lowercase_ , split_batches=lowercase_ ) self.check_iterable_dataset_shards(lowercase_ , lowercase_ , batch_size=4 , drop_last=lowercase_ , split_batches=lowercase_ ) self.check_iterable_dataset_shards(lowercase_ , lowercase_ , batch_size=4 , drop_last=lowercase_ , split_batches=lowercase_ ) self.check_iterable_dataset_shards(lowercase_ , lowercase_ , batch_size=4 , drop_last=lowercase_ , split_batches=lowercase_ ) def a__ ( self ) -> List[Any]: _A : List[Any] = BatchSampler(range(16 ) , batch_size=4 , drop_last=lowercase_ ) _A : int = SkipBatchSampler(lowercase_ , 2 ) self.assertListEqual(list(lowercase_ ) , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def a__ ( self ) -> Dict: _A : int = SkipDataLoader(list(range(16 ) ) , batch_size=4 , skip_batches=2 ) self.assertListEqual([t.tolist() for t in dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def a__ ( self ) -> Tuple: _A : Optional[Any] = DataLoader(list(range(16 ) ) , batch_size=4 ) _A : int = skip_first_batches(lowercase_ , num_batches=2 ) self.assertListEqual([t.tolist() for t in new_dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def a__ ( self ) -> Any: _A : int = DataLoaderShard(list(range(16 ) ) , batch_size=4 ) for idx, _ in enumerate(lowercase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(lowercase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) def a__ ( self ) -> Any: Accelerator() _A : Tuple = DataLoaderDispatcher(range(16 ) , batch_size=4 ) for idx, _ in enumerate(lowercase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(lowercase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 )
371
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class lowercase ( unittest.TestCase ): def a__ ( self ) -> List[str]: debug_launcher(test_script.main ) def a__ ( self ) -> Any: debug_launcher(test_ops.main )
343
0
def lowerCAmelCase_ ( snake_case_ = 100 ): _A : Optional[Any] = set() _A : int = 0 _A : str = n + 1 # maximum limit for a in range(2,__a ): for b in range(2,__a ): _A : int = a**b # calculates the current power collect_powers.add(__a ) # adds the result to the set return len(__a ) if __name__ == "__main__": print("Number of terms ", solution(int(str(input()).strip())))
350
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _snake_case = logging.get_logger(__name__) _snake_case = { "microsoft/resnet-50": "https://huggingface.co/microsoft/resnet-50/blob/main/config.json", } class lowercase ( UpperCamelCase__,UpperCamelCase__ ): _a = "resnet" _a = ["basic", "bottleneck"] def __init__( self , _a=3 , _a=64 , _a=[256, 512, 1024, 2048] , _a=[3, 4, 6, 3] , _a="bottleneck" , _a="relu" , _a=False , _a=None , _a=None , **_a , ) -> int: super().__init__(**_a ) if layer_type not in self.layer_types: raise ValueError(F'''layer_type={layer_type} is not one of {",".join(self.layer_types )}''' ) _A : Optional[Any] = num_channels _A : List[Any] = embedding_size _A : int = hidden_sizes _A : Union[str, Any] = depths _A : Optional[int] = layer_type _A : Any = hidden_act _A : List[Any] = downsample_in_first_stage _A : int = ["""stem"""] + [F'''stage{idx}''' for idx in range(1 , len(_a ) + 1 )] _A , _A : str = get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names ) class lowercase ( UpperCamelCase__ ): _a = version.parse("1.11" ) @property def a__ ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def a__ ( self ) -> float: return 1e-3
343
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { "microsoft/trocr-base-handwritten": ( "https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json" ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class lowercase ( lowercase__ ): _a = """trocr""" _a = ["""past_key_values"""] _a = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self , _a=5_0265 , _a=1024 , _a=12 , _a=16 , _a=4096 , _a="gelu" , _a=512 , _a=0.1 , _a=0.0 , _a=0.0 , _a=2 , _a=0.02 , _a=0.0 , _a=True , _a=False , _a=True , _a=True , _a=1 , _a=0 , _a=2 , **_a , ) -> List[Any]: _A : Optional[Any] = vocab_size _A : Optional[Any] = d_model _A : Optional[int] = decoder_layers _A : Any = decoder_attention_heads _A : Optional[int] = decoder_ffn_dim _A : Any = activation_function _A : int = max_position_embeddings _A : Union[str, Any] = dropout _A : List[Any] = attention_dropout _A : List[Any] = activation_dropout _A : List[str] = init_std _A : Tuple = decoder_layerdrop _A : Any = use_cache _A : Union[str, Any] = scale_embedding _A : Dict = use_learned_position_embeddings _A : List[str] = layernorm_embedding super().__init__( pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , decoder_start_token_id=lowercase_ , **lowercase_ , )
351
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowerCAmelCase_ ( snake_case_,snake_case_ ): # Load checkpoint _A : Optional[int] = torch.load(snake_case_,map_location="""cpu""" ) _A : Any = chkpt["""model"""] # We have the base model one level deeper than the original XLM repository _A : Any = {} for k, v in state_dict.items(): if "pred_layer" in k: _A : Tuple = v else: _A : Dict = v _A : Optional[Any] = chkpt["""params"""] _A : Union[str, Any] = {n: v for n, v in config.items() if not isinstance(snake_case_,(torch.FloatTensor, numpy.ndarray) )} _A : str = chkpt["""dico_word2id"""] _A : Optional[Any] = {s + """</w>""" if s.find("""@@""" ) == -1 and i > 13 else s.replace("""@@""","""""" ): i for s, i in vocab.items()} # Save pytorch-model _A : Dict = pytorch_dump_folder_path + """/""" + WEIGHTS_NAME _A : Any = pytorch_dump_folder_path + """/""" + CONFIG_NAME _A : Optional[int] = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""vocab_file"""] print(f'''Save PyTorch model to {pytorch_weights_dump_path}''' ) torch.save(snake_case_,snake_case_ ) print(f'''Save configuration file to {pytorch_config_dump_path}''' ) with open(snake_case_,"""w""",encoding="""utf-8""" ) as f: f.write(json.dumps(snake_case_,indent=2 ) + """\n""" ) print(f'''Save vocab file to {pytorch_config_dump_path}''' ) with open(snake_case_,"""w""",encoding="""utf-8""" ) as f: f.write(json.dumps(snake_case_,indent=2 ) + """\n""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( "--xlm_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) _snake_case = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
343
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) _snake_case = {"""configuration_beit""": ["""BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BeitConfig""", """BeitOnnxConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ["""BeitFeatureExtractor"""] _snake_case = ["""BeitImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ """BEIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """BeitForImageClassification""", """BeitForMaskedImageModeling""", """BeitForSemanticSegmentation""", """BeitModel""", """BeitPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ """FlaxBeitForImageClassification""", """FlaxBeitForMaskedImageModeling""", """FlaxBeitModel""", """FlaxBeitPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys _snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
352
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowercase ( UpperCamelCase__ ): _a = ["image_processor", "tokenizer"] _a = "BlipImageProcessor" _a = ("BertTokenizer", "BertTokenizerFast") def __init__( self , _a , _a ) -> Any: _A : List[Any] = False super().__init__(_a , _a ) _A : Optional[int] = self.image_processor def __call__( self , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ) -> BatchEncoding: if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None: _A : Dict = self.tokenizer _A : Dict = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) return text_encoding # add pixel_values _A : int = self.image_processor(_a , return_tensors=_a ) if text is not None: _A : List[Any] = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) else: _A : int = None if text_encoding is not None: encoding_image_processor.update(_a ) return encoding_image_processor def a__ ( self , *_a , **_a ) -> Any: return self.tokenizer.batch_decode(*_a , **_a ) def a__ ( self , *_a , **_a ) -> List[str]: return self.tokenizer.decode(*_a , **_a ) @property def a__ ( self ) -> Optional[Any]: _A : Any = self.tokenizer.model_input_names _A : List[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
343
0
import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging _snake_case = logging.get_logger(__name__) # pylint: disable=invalid-name class lowercase ( SCREAMING_SNAKE_CASE_ ): def __init__( self , _a , _a , _a , _a , _a , _a , _a , ) -> Dict: super().__init__() self.register_modules( vae=snake_case__ , text_encoder=snake_case__ , tokenizer=snake_case__ , unet=snake_case__ , scheduler=snake_case__ , safety_checker=snake_case__ , feature_extractor=snake_case__ , ) def a__ ( self , _a = "auto" ) -> Optional[int]: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory _A : Optional[Any] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(snake_case__ ) def a__ ( self ) -> Optional[int]: self.enable_attention_slicing(snake_case__ ) @torch.no_grad() def __call__( self , _a , _a = 512 , _a = 512 , _a = 50 , _a = 7.5 , _a = None , _a = 1 , _a = 0.0 , _a = None , _a = None , _a = "pil" , _a = True , _a = None , _a = 1 , _a = None , **_a , ) -> Any: if isinstance(snake_case__ , snake_case__ ): _A : Tuple = 1 elif isinstance(snake_case__ , snake_case__ ): _A : List[str] = len(snake_case__ ) else: raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(snake_case__ )}''' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(snake_case__ , snake_case__ ) or callback_steps <= 0) ): raise ValueError( F'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' F''' {type(snake_case__ )}.''' ) # get prompt text embeddings _A : Union[str, Any] = self.tokenizer( snake_case__ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) _A : List[Any] = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: _A : Union[str, Any] = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) _A : List[str] = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: _A : Optional[Any] = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method _A : Any = text_embeddings.shape _A : int = text_embeddings.repeat(1 , snake_case__ , 1 ) _A : Union[str, Any] = text_embeddings.view(bs_embed * num_images_per_prompt , snake_case__ , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. _A : Tuple = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: _A : List[str] if negative_prompt is None: _A : Dict = [''] elif type(snake_case__ ) is not type(snake_case__ ): raise TypeError( F'''`negative_prompt` should be the same type to `prompt`, but got {type(snake_case__ )} !=''' F''' {type(snake_case__ )}.''' ) elif isinstance(snake_case__ , snake_case__ ): _A : List[str] = [negative_prompt] elif batch_size != len(snake_case__ ): raise ValueError( F'''`negative_prompt`: {negative_prompt} has batch size {len(snake_case__ )}, but `prompt`:''' F''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches''' """ the batch size of `prompt`.""" ) else: _A : Optional[Any] = negative_prompt _A : Tuple = text_input_ids.shape[-1] _A : Optional[Any] = self.tokenizer( snake_case__ , padding="""max_length""" , max_length=snake_case__ , truncation=snake_case__ , return_tensors="""pt""" , ) _A : Optional[int] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method _A : Dict = uncond_embeddings.shape[1] _A : Any = uncond_embeddings.repeat(snake_case__ , snake_case__ , 1 ) _A : List[Any] = uncond_embeddings.view(batch_size * num_images_per_prompt , snake_case__ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes _A : List[str] = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. _A : Tuple = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) _A : Any = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) _A : Optional[int] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps _A : Tuple = torch.randn( snake_case__ , generator=snake_case__ , device="""cpu""" , dtype=snake_case__ ).to(self.device ) _A : Optional[Any] = torch.randn(snake_case__ , generator=snake_case__ , device="""cpu""" , dtype=snake_case__ ).to( self.device ) else: _A : List[str] = torch.randn( snake_case__ , generator=snake_case__ , device=self.device , dtype=snake_case__ ) _A : List[str] = torch.randn(snake_case__ , generator=snake_case__ , device=self.device , dtype=snake_case__ ) else: if latents_reference.shape != latents_shape: raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) _A : str = latents_reference.to(self.device ) _A : Dict = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images _A : Dict = (latents_shape[3] - latents_shape_reference[3]) // 2 _A : Tuple = (latents_shape[2] - latents_shape_reference[2]) // 2 _A : Union[str, Any] = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx _A : Tuple = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy _A : int = 0 if dx < 0 else dx _A : str = 0 if dy < 0 else dy _A : Tuple = max(-dx , 0 ) _A : str = max(-dy , 0 ) # import pdb # pdb.set_trace() _A : Union[str, Any] = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(snake_case__ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand _A : Dict = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler _A : Dict = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] _A : Optional[int] = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) _A : Optional[int] = {} if accepts_eta: _A : Optional[Any] = eta for i, t in enumerate(self.progress_bar(snake_case__ ) ): # expand the latents if we are doing classifier free guidance _A : List[str] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _A : List[str] = self.scheduler.scale_model_input(snake_case__ , snake_case__ ) # predict the noise residual _A : Union[str, Any] = self.unet(snake_case__ , snake_case__ , encoder_hidden_states=snake_case__ ).sample # perform guidance if do_classifier_free_guidance: _A : List[Any] = noise_pred.chunk(2 ) _A : Any = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 _A : List[Any] = self.scheduler.step(snake_case__ , snake_case__ , snake_case__ , **snake_case__ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(snake_case__ , snake_case__ , snake_case__ ) _A : Any = 1 / 0.18215 * latents _A : Optional[int] = self.vae.decode(snake_case__ ).sample _A : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 _A : Any = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: _A : Union[str, Any] = self.feature_extractor(self.numpy_to_pil(snake_case__ ) , return_tensors="""pt""" ).to( self.device ) _A : Dict = self.safety_checker( images=snake_case__ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: _A : Dict = None if output_type == "pil": _A : str = self.numpy_to_pil(snake_case__ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=snake_case__ , nsfw_content_detected=snake_case__ )
353
from random import randint from tempfile import TemporaryFile import numpy as np def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : Tuple = 0 if start < end: _A : Tuple = randint(snake_case_,snake_case_ ) _A : Any = a[end] _A : int = a[pivot] _A : int = temp _A , _A : List[Any] = _in_place_partition(snake_case_,snake_case_,snake_case_ ) count += _in_place_quick_sort(snake_case_,snake_case_,p - 1 ) count += _in_place_quick_sort(snake_case_,p + 1,snake_case_ ) return count def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : str = 0 _A : List[str] = randint(snake_case_,snake_case_ ) _A : Union[str, Any] = a[end] _A : List[str] = a[pivot] _A : List[Any] = temp _A : List[str] = start - 1 for index in range(snake_case_,snake_case_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value _A : Union[str, Any] = new_pivot_index + 1 _A : List[Any] = a[new_pivot_index] _A : Optional[int] = a[index] _A : List[Any] = temp _A : Optional[Any] = a[new_pivot_index + 1] _A : Any = a[end] _A : Dict = temp return new_pivot_index + 1, count _snake_case = TemporaryFile() _snake_case = 100 # 1000 elements are to be sorted _snake_case , _snake_case = 0, 1 # mean and standard deviation _snake_case = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array _snake_case = np.load(outfile) _snake_case = len(M) - 1 _snake_case = _in_place_quick_sort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
343
0
def lowerCAmelCase_ ( snake_case_ ): _A : Any = [] _A : Any = [] _A : List[str] = { """^""": 3, """*""": 2, """/""": 2, """%""": 2, """+""": 1, """-""": 1, } # Priority of each operator _A : Any = len(snake_case_ ) if (len(snake_case_ ) > 7) else 7 # Print table header for output print( """Symbol""".center(8 ),"""Stack""".center(snake_case_ ),"""Postfix""".center(snake_case_ ),sep=""" | """,) print("""-""" * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(snake_case_ ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(snake_case_ ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(snake_case_ ) == 0: stack.append(snake_case_ ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(snake_case_ ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(snake_case_ ) # push x to stack print( x.center(8 ),("""""".join(snake_case_ )).ljust(snake_case_ ),("""""".join(snake_case_ )).ljust(snake_case_ ),sep=""" | """,) # Output in tabular format while len(snake_case_ ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( """ """.center(8 ),("""""".join(snake_case_ )).ljust(snake_case_ ),("""""".join(snake_case_ )).ljust(snake_case_ ),sep=""" | """,) # Output in tabular format return "".join(snake_case_ ) # return Postfix as str def lowerCAmelCase_ ( snake_case_ ): _A : Union[str, Any] = list(infix[::-1] ) # reverse the infix equation for i in range(len(snake_case_ ) ): if infix[i] == "(": _A : str = """)""" # change "(" to ")" elif infix[i] == ")": _A : Union[str, Any] = """(""" # change ")" to "(" return (infix_2_postfix("""""".join(snake_case_ ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": _snake_case = input("\nEnter an Infix Equation = ") # Input an Infix equation _snake_case = "".join(Infix.split()) # Remove spaces from the input print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")
354
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { "MIT/ast-finetuned-audioset-10-10-0.4593": ( "https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json" ), } class lowercase ( UpperCamelCase__ ): _a = "audio-spectrogram-transformer" def __init__( self , _a=768 , _a=12 , _a=12 , _a=3072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1e-12 , _a=16 , _a=True , _a=10 , _a=10 , _a=1024 , _a=128 , **_a , ) -> List[Any]: super().__init__(**_a ) _A : Any = hidden_size _A : Tuple = num_hidden_layers _A : List[str] = num_attention_heads _A : Any = intermediate_size _A : Optional[Any] = hidden_act _A : Optional[Any] = hidden_dropout_prob _A : Any = attention_probs_dropout_prob _A : Optional[Any] = initializer_range _A : Optional[Any] = layer_norm_eps _A : str = patch_size _A : Tuple = qkv_bias _A : Dict = frequency_stride _A : Union[str, Any] = time_stride _A : Any = max_length _A : Tuple = num_mel_bins
343
0
from typing import Any def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_,): _validation( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_,) # Creates data structures and fill initial step _A : dict = {} _A : dict = {} for state in states_space: _A : int = observations_space[0] _A : Optional[Any] = ( initial_probabilities[state] * emission_probabilities[state][observation] ) _A : List[str] = None # Fills the data structure with the probabilities of # different transitions and pointers to previous states for o in range(1,len(snake_case_ ) ): _A : Optional[Any] = observations_space[o] _A : Dict = observations_space[o - 1] for state in states_space: # Calculates the argmax for probability function _A : Union[str, Any] = """""" _A : Any = -1 for k_state in states_space: _A : Dict = ( probabilities[(k_state, prior_observation)] * transition_probabilities[k_state][state] * emission_probabilities[state][observation] ) if probability > max_probability: _A : Optional[Any] = probability _A : Dict = k_state # Update probabilities and pointers dicts _A : Optional[int] = ( probabilities[(arg_max, prior_observation)] * transition_probabilities[arg_max][state] * emission_probabilities[state][observation] ) _A : List[Any] = arg_max # The final observation _A : Union[str, Any] = observations_space[len(snake_case_ ) - 1] # argmax for given final observation _A : List[str] = """""" _A : List[Any] = -1 for k_state in states_space: _A : Optional[int] = probabilities[(k_state, final_observation)] if probability > max_probability: _A : int = probability _A : List[Any] = k_state _A : Union[str, Any] = arg_max # Process pointers backwards _A : Optional[int] = last_state _A : List[str] = [] for o in range(len(snake_case_ ) - 1,-1,-1 ): result.append(snake_case_ ) _A : Union[str, Any] = pointers[previous, observations_space[o]] result.reverse() return result def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_,): _validate_not_empty( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_,) _validate_lists(snake_case_,snake_case_ ) _validate_dicts( snake_case_,snake_case_,snake_case_ ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_,): if not all( [ observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ] ): raise ValueError("""There's an empty parameter""" ) def lowerCAmelCase_ ( snake_case_,snake_case_ ): _validate_list(snake_case_,"""observations_space""" ) _validate_list(snake_case_,"""states_space""" ) def lowerCAmelCase_ ( snake_case_,snake_case_ ): if not isinstance(_object,snake_case_ ): _A : Any = f'''{var_name} must be a list''' raise ValueError(snake_case_ ) else: for x in _object: if not isinstance(snake_case_,snake_case_ ): _A : List[Any] = f'''{var_name} must be a list of strings''' raise ValueError(snake_case_ ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,): _validate_dict(snake_case_,"""initial_probabilities""",snake_case_ ) _validate_nested_dict(snake_case_,"""transition_probabilities""" ) _validate_nested_dict(snake_case_,"""emission_probabilities""" ) def lowerCAmelCase_ ( snake_case_,snake_case_ ): _validate_dict(_object,snake_case_,snake_case_ ) for x in _object.values(): _validate_dict(snake_case_,snake_case_,snake_case_,snake_case_ ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_ = False ): if not isinstance(_object,snake_case_ ): _A : str = f'''{var_name} must be a dict''' raise ValueError(snake_case_ ) if not all(isinstance(snake_case_,snake_case_ ) for x in _object ): _A : Dict = f'''{var_name} all keys must be strings''' raise ValueError(snake_case_ ) if not all(isinstance(snake_case_,snake_case_ ) for x in _object.values() ): _A : str = """nested dictionary """ if nested else """""" _A : Dict = f'''{var_name} {nested_text}all values must be {value_type.__name__}''' raise ValueError(snake_case_ ) if __name__ == "__main__": from doctest import testmod testmod()
355
import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) _snake_case = logging.getLogger() def lowerCAmelCase_ ( ): _A : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""-f""" ) _A : Optional[Any] = parser.parse_args() return args.f class lowercase ( UpperCamelCase__ ): def a__ ( self ) -> None: _A : List[Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(_a ) def a__ ( self , _a ) -> Dict: _A : Tuple = get_gpu_count() if n_gpu > 1: pass # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560 # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py" # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split() # cmd = [sys.executable] + distributed_args + args # execute_subprocess_async(cmd, env=self.get_env()) # XXX: test the results - need to save them first into .json file else: args.insert(0 , """run_glue_deebert.py""" ) with patch.object(_a , """argv""" , _a ): _A : Optional[Any] = run_glue_deebert.main() for value in result.values(): self.assertGreaterEqual(_a , 0.666 ) @slow @require_torch_non_multi_gpu def a__ ( self ) -> Optional[int]: _A : Tuple = """ --model_type roberta --model_name_or_path roberta-base --task_name MRPC --do_train --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --max_seq_length 128 --per_gpu_eval_batch_size=1 --per_gpu_train_batch_size=8 --learning_rate 2e-4 --num_train_epochs 3 --overwrite_output_dir --seed 42 --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --save_steps 0 --overwrite_cache --eval_after_first_stage """.split() self.run_and_check(_a ) _A : Optional[Any] = """ --model_type roberta --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --task_name MRPC --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --max_seq_length 128 --eval_each_highway --eval_highway --overwrite_cache --per_gpu_eval_batch_size=1 """.split() self.run_and_check(_a ) _A : List[str] = """ --model_type roberta --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --task_name MRPC --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --max_seq_length 128 --early_exit_entropy 0.1 --eval_highway --overwrite_cache --per_gpu_eval_batch_size=1 """.split() self.run_and_check(_a )
343
0
import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class lowercase ( unittest.TestCase ): @slow def a__ ( self ) -> Tuple: _A : Optional[int] = FlaxMTaForConditionalGeneration.from_pretrained("""google/mt5-small""" ) _A : int = AutoTokenizer.from_pretrained("""google/mt5-small""" ) _A : str = tokenizer("""Hello there""" , return_tensors="""np""" ).input_ids _A : Optional[int] = tokenizer("""Hi I am""" , return_tensors="""np""" ).input_ids _A : Optional[Any] = shift_tokens_right(_a , model.config.pad_token_id , model.config.decoder_start_token_id ) _A : Union[str, Any] = model(_a , decoder_input_ids=_a ).logits _A : Dict = optax.softmax_cross_entropy(_a , onehot(_a , logits.shape[-1] ) ).mean() _A : List[str] = -(labels.shape[-1] * loss.item()) _A : List[str] = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
356
import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowercase : def __init__( self , _a , _a=13 , _a=30 , _a=2 , _a=3 , _a=True , _a=True , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=10 , _a=0.02 , _a=None , ) -> Union[str, Any]: _A : Optional[int] = parent _A : Dict = batch_size _A : Any = image_size _A : Optional[int] = patch_size _A : Optional[int] = num_channels _A : List[Any] = is_training _A : Optional[Any] = use_labels _A : Any = hidden_size _A : Any = num_hidden_layers _A : List[Any] = num_attention_heads _A : int = intermediate_size _A : Dict = hidden_act _A : Optional[int] = hidden_dropout_prob _A : str = attention_probs_dropout_prob _A : Any = type_sequence_label_size _A : str = initializer_range _A : Tuple = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) _A : List[Any] = (image_size // patch_size) ** 2 _A : str = num_patches + 1 def a__ ( self ) -> Dict: _A : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A : List[str] = None if self.use_labels: _A : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _A : List[Any] = self.get_config() return config, pixel_values, labels def a__ ( self ) -> Union[str, Any]: return ViTMSNConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , ) def a__ ( self , _a , _a , _a ) -> Dict: _A : List[str] = ViTMSNModel(config=_a ) model.to(_a ) model.eval() _A : List[str] = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a__ ( self , _a , _a , _a ) -> List[str]: _A : Union[str, Any] = self.type_sequence_label_size _A : Tuple = ViTMSNForImageClassification(_a ) model.to(_a ) model.eval() _A : Optional[int] = model(_a , labels=_a ) print("""Pixel and labels shape: {pixel_values.shape}, {labels.shape}""" ) print("""Labels: {labels}""" ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images _A : Dict = 1 _A : str = ViTMSNForImageClassification(_a ) model.to(_a ) model.eval() _A : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _A : int = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a__ ( self ) -> Any: _A : Optional[int] = self.prepare_config_and_inputs() _A , _A , _A : Dict = config_and_inputs _A : List[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowercase ( UpperCamelCase__,UpperCamelCase__,unittest.TestCase ): _a = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () _a = ( {"feature-extraction": ViTMSNModel, "image-classification": ViTMSNForImageClassification} if is_torch_available() else {} ) _a = False _a = False _a = False _a = False def a__ ( self ) -> Tuple: _A : Tuple = ViTMSNModelTester(self ) _A : List[Any] = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def a__ ( self ) -> Optional[int]: self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMSN does not use inputs_embeds""" ) def a__ ( self ) -> int: pass def a__ ( self ) -> Any: _A , _A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : Tuple = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _A : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , nn.Linear ) ) def a__ ( self ) -> str: _A , _A : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : int = model_class(_a ) _A : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A : str = [*signature.parameters.keys()] _A : Optional[int] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def a__ ( self ) -> List[Any]: _A : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def a__ ( self ) -> Any: _A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @slow def a__ ( self ) -> int: for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _A : int = ViTMSNModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowerCAmelCase_ ( ): _A : Dict = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class lowercase ( unittest.TestCase ): @cached_property def a__ ( self ) -> int: return ViTImageProcessor.from_pretrained("""facebook/vit-msn-small""" ) if is_vision_available() else None @slow def a__ ( self ) -> Optional[int]: torch.manual_seed(2 ) _A : Tuple = ViTMSNForImageClassification.from_pretrained("""facebook/vit-msn-small""" ).to(_a ) _A : Tuple = self.default_image_processor _A : Dict = prepare_img() _A : Optional[Any] = image_processor(images=_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): _A : int = model(**_a ) # verify the logits _A : Union[str, Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _a ) _A : Optional[int] = torch.tensor([-0.0803, -0.4454, -0.2375] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) )
343
0
from ....configuration_utils import PretrainedConfig from ....utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { "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 lowercase ( __lowerCamelCase ): _a = 'trajectory_transformer' _a = ['past_key_values'] _a = { 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , _a=100 , _a=5 , _a=1 , _a=1 , _a=249 , _a=6 , _a=17 , _a=25 , _a=4 , _a=4 , _a=128 , _a=0.1 , _a=0.1 , _a=0.1 , _a=0.0006 , _a=512 , _a=0.02 , _a=1e-12 , _a=1 , _a=True , _a=1 , _a=5_0256 , _a=5_0256 , **_a , ) -> List[str]: _A : List[str] = vocab_size _A : str = action_weight _A : Optional[int] = reward_weight _A : Optional[int] = value_weight _A : int = max_position_embeddings _A : Tuple = block_size _A : Optional[int] = action_dim _A : Dict = observation_dim _A : Any = transition_dim _A : str = learning_rate _A : List[Any] = n_layer _A : Any = n_head _A : str = n_embd _A : str = embd_pdrop _A : str = attn_pdrop _A : Optional[Any] = resid_pdrop _A : Dict = initializer_range _A : List[str] = layer_norm_eps _A : Any = kaiming_initializer_range _A : Dict = use_cache super().__init__(pad_token_id=UpperCamelCase_ , bos_token_id=UpperCamelCase_ , eos_token_id=UpperCamelCase_ , **UpperCamelCase_ )
357
def lowerCAmelCase_ ( snake_case_ = 1000 ): _A : List[Any] = 3 _A : Tuple = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f"""{solution() = }""")
343
0
import logging from transformers.configuration_utils import PretrainedConfig _snake_case = logging.getLogger(__name__) class lowercase ( lowerCAmelCase_ ): _a = 'masked_bert' def __init__( self , _a=3_0522 , _a=768 , _a=12 , _a=12 , _a=3072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1e-12 , _a=0 , _a="topK" , _a="constant" , _a=0.0 , **_a , ) -> Optional[int]: super().__init__(pad_token_id=__lowerCAmelCase , **__lowerCAmelCase ) _A : int = vocab_size _A : Dict = hidden_size _A : Any = num_hidden_layers _A : List[str] = num_attention_heads _A : Optional[int] = hidden_act _A : Any = intermediate_size _A : str = hidden_dropout_prob _A : List[Any] = attention_probs_dropout_prob _A : List[Any] = max_position_embeddings _A : Any = type_vocab_size _A : Any = initializer_range _A : List[str] = layer_norm_eps _A : List[Any] = pruning_method _A : Any = mask_init _A : Any = mask_scale
358
import inspect import unittest from transformers import ConvNextConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase : def __init__( self , _a , _a=13 , _a=32 , _a=3 , _a=4 , _a=[10, 20, 30, 40] , _a=[2, 2, 3, 2] , _a=True , _a=True , _a=37 , _a="gelu" , _a=10 , _a=0.02 , _a=["stage2", "stage3", "stage4"] , _a=[2, 3, 4] , _a=None , ) -> List[Any]: _A : Tuple = parent _A : Any = batch_size _A : int = image_size _A : Tuple = num_channels _A : List[Any] = num_stages _A : Any = hidden_sizes _A : Union[str, Any] = depths _A : Union[str, Any] = is_training _A : Tuple = use_labels _A : Optional[Any] = intermediate_size _A : Union[str, Any] = hidden_act _A : Any = num_labels _A : List[str] = initializer_range _A : str = out_features _A : int = out_indices _A : List[Any] = scope def a__ ( self ) -> str: _A : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A : str = None if self.use_labels: _A : int = ids_tensor([self.batch_size] , self.num_labels ) _A : str = self.get_config() return config, pixel_values, labels def a__ ( self ) -> List[str]: return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=_a , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def a__ ( self , _a , _a , _a ) -> int: _A : int = ConvNextModel(config=_a ) model.to(_a ) model.eval() _A : int = model(_a ) # expected last hidden states: B, C, H // 32, W // 32 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 , _a ) -> List[Any]: _A : Union[str, Any] = ConvNextForImageClassification(_a ) model.to(_a ) model.eval() _A : List[Any] = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a__ ( self , _a , _a , _a ) -> str: _A : List[str] = ConvNextBackbone(config=_a ) model.to(_a ) model.eval() _A : Optional[int] = model(_a ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None _A : Optional[Any] = None _A : str = ConvNextBackbone(config=_a ) model.to(_a ) model.eval() _A : int = model(_a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def a__ ( self ) -> int: _A : int = self.prepare_config_and_inputs() _A , _A , _A : List[Any] = config_and_inputs _A : Any = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowercase ( UpperCamelCase__,UpperCamelCase__,unittest.TestCase ): _a = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) _a = ( {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification} if is_torch_available() else {} ) _a = True _a = False _a = False _a = False _a = False def a__ ( self ) -> Dict: _A : int = ConvNextModelTester(self ) _A : List[Any] = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def a__ ( self ) -> Any: 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 ) -> str: return @unittest.skip(reason="""ConvNext does not use inputs_embeds""" ) def a__ ( self ) -> Tuple: pass @unittest.skip(reason="""ConvNext does not support input and output embeddings""" ) def a__ ( self ) -> Optional[Any]: pass @unittest.skip(reason="""ConvNext does not use feedforward chunking""" ) def a__ ( self ) -> List[Any]: pass def a__ ( self ) -> Optional[Any]: _A , _A : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : Optional[Any] = model_class(_a ) _A : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A : List[Any] = [*signature.parameters.keys()] _A : int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def a__ ( self ) -> Union[str, Any]: _A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def a__ ( self ) -> Tuple: _A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_a ) def a__ ( self ) -> Tuple: def check_hidden_states_output(_a , _a , _a ): _A : Tuple = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): _A : Dict = model(**self._prepare_for_class(_a , _a ) ) _A : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _A : Dict = self.model_tester.num_stages self.assertEqual(len(_a ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) _A , _A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : List[Any] = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _A : Union[str, Any] = True check_hidden_states_output(_a , _a , _a ) def a__ ( self ) -> int: _A : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @slow def a__ ( self ) -> Optional[int]: for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _A : Optional[Any] = ConvNextModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowerCAmelCase_ ( ): _A : Optional[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class lowercase ( unittest.TestCase ): @cached_property def a__ ( self ) -> str: return AutoImageProcessor.from_pretrained("""facebook/convnext-tiny-224""" ) if is_vision_available() else None @slow def a__ ( self ) -> Optional[Any]: _A : Any = ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224""" ).to(_a ) _A : List[str] = self.default_image_processor _A : int = prepare_img() _A : Union[str, Any] = image_processor(images=_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): _A : Dict = model(**_a ) # verify the logits _A : Optional[Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _a ) _A : Any = torch.tensor([-0.0260, -0.4739, 0.1911] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) ) @require_torch class lowercase ( unittest.TestCase,UpperCamelCase__ ): _a = (ConvNextBackbone,) if is_torch_available() else () _a = ConvNextConfig _a = False def a__ ( self ) -> List[str]: _A : Optional[int] = ConvNextModelTester(self )
343
0
def lowerCAmelCase_ ( snake_case_,snake_case_ ): def get_matched_characters(snake_case_,snake_case_ ) -> str: _A : Optional[Any] = [] _A : Tuple = min(len(_stra ),len(_stra ) ) // 2 for i, l in enumerate(_stra ): _A : Optional[Any] = int(max(0,i - limit ) ) _A : int = int(min(i + limit + 1,len(_stra ) ) ) if l in _stra[left:right]: matched.append(_UpperCamelCase ) _A : str = f'''{_stra[0:_stra.index(_UpperCamelCase )]} {_stra[_stra.index(_UpperCamelCase ) + 1:]}''' return "".join(_UpperCamelCase ) # matching characters _A : Optional[Any] = get_matched_characters(_UpperCamelCase,_UpperCamelCase ) _A : str = get_matched_characters(_UpperCamelCase,_UpperCamelCase ) _A : Union[str, Any] = len(_UpperCamelCase ) # transposition _A : List[str] = ( len([(ca, ca) for ca, ca in zip(_UpperCamelCase,_UpperCamelCase ) if ca != ca] ) // 2 ) if not match_count: _A : int = 0.0 else: _A : Union[str, Any] = ( 1 / 3 * ( match_count / len(_UpperCamelCase ) + match_count / len(_UpperCamelCase ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters _A : Dict = 0 for ca, ca in zip(stra[:4],stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("hello", "world"))
359
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _snake_case = { "configuration_roc_bert": ["ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoCBertConfig"], "tokenization_roc_bert": ["RoCBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ "ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "RoCBertForCausalLM", "RoCBertForMaskedLM", "RoCBertForMultipleChoice", "RoCBertForPreTraining", "RoCBertForQuestionAnswering", "RoCBertForSequenceClassification", "RoCBertForTokenClassification", "RoCBertLayer", "RoCBertModel", "RoCBertPreTrainedModel", "load_tf_weights_in_roc_bert", ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys _snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
343
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class lowercase ( metaclass=UpperCamelCase__ ): _a = ['transformers', 'torch', 'note_seq'] def __init__( self , *_a , **_a ) -> Tuple: requires_backends(self , ["""transformers""", """torch""", """note_seq"""] ) @classmethod def a__ ( cls , *_a , **_a ) -> Tuple: requires_backends(cls , ["""transformers""", """torch""", """note_seq"""] ) @classmethod def a__ ( cls , *_a , **_a ) -> str: requires_backends(cls , ["""transformers""", """torch""", """note_seq"""] )
360
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowercase : _a = 42 # setable values _a = 42 _a = 42 _a = None @classmethod def a__ ( cls , _a , _a , _a ) -> Tuple: return cls(common=_a , init_noise_sigma=_a , timesteps=_a ) @dataclass class lowercase ( UpperCamelCase__ ): _a = 42 class lowercase ( UpperCamelCase__,UpperCamelCase__ ): _a = [e.name for e in FlaxKarrasDiffusionSchedulers] _a = 42 @property def a__ ( self ) -> Dict: return True @register_to_config def __init__( self , _a = 1000 , _a = 0.0001 , _a = 0.02 , _a = "linear" , _a = None , _a = "fixed_small" , _a = True , _a = "epsilon" , _a = jnp.floataa , ) -> Tuple: _A : Tuple = dtype def a__ ( self , _a = None ) -> DDPMSchedulerState: if common is None: _A : Dict = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution _A : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) _A : Tuple = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=_a , init_noise_sigma=_a , timesteps=_a , ) def a__ ( self , _a , _a , _a = None ) -> jnp.ndarray: return sample def a__ ( self , _a , _a , _a = () ) -> DDPMSchedulerState: _A : Any = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 _A : Dict = (jnp.arange(0 , _a ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=_a , timesteps=_a , ) def a__ ( self , _a , _a , _a=None , _a=None ) -> Optional[int]: _A : Optional[Any] = state.common.alphas_cumprod[t] _A : int = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample _A : List[str] = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: _A : Optional[Any] = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": _A : Optional[Any] = jnp.clip(_a , a_min=1e-20 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": _A : Any = jnp.log(jnp.clip(_a , a_min=1e-20 ) ) elif variance_type == "fixed_large": _A : Optional[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log _A : Tuple = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": _A : str = variance _A : Union[str, Any] = state.common.betas[t] _A : Tuple = (predicted_variance + 1) / 2 _A : List[str] = frac * max_log + (1 - frac) * min_log return variance def a__ ( self , _a , _a , _a , _a , _a = None , _a = True , ) -> Union[FlaxDDPMSchedulerOutput, Tuple]: _A : Dict = timestep if key is None: _A : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: _A , _A : List[str] = jnp.split(_a , sample.shape[1] , axis=1 ) else: _A : int = None # 1. compute alphas, betas _A : int = state.common.alphas_cumprod[t] _A : List[str] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) _A : Union[str, Any] = 1 - alpha_prod_t _A : Optional[int] = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": _A : Dict = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": _A : Optional[int] = model_output elif self.config.prediction_type == "v_prediction": _A : Any = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' """ for the FlaxDDPMScheduler.""" ) # 3. Clip "predicted x_0" if self.config.clip_sample: _A : Union[str, Any] = jnp.clip(_a , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _A : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t _A : Dict = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _A : int = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): _A : Tuple = jax.random.split(_a , num=1 ) _A : Dict = jax.random.normal(_a , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(_a , _a , predicted_variance=_a ) ** 0.5) * noise _A : int = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) _A : Union[str, Any] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=_a , state=_a ) def a__ ( self , _a , _a , _a , _a , ) -> jnp.ndarray: return add_noise_common(state.common , _a , _a , _a ) def a__ ( self , _a , _a , _a , _a , ) -> jnp.ndarray: return get_velocity_common(state.common , _a , _a , _a ) def __len__( self ) -> List[Any]: return self.config.num_train_timesteps
343
0
import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class lowercase ( UpperCamelCase__,unittest.TestCase ): _a = CTRLTokenizer _a = False _a = False def a__ ( self ) -> List[Any]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _A : List[str] = ["""adapt""", """re@@""", """a@@""", """apt""", """c@@""", """t""", """<unk>"""] _A : Optional[Any] = dict(zip(_snake_case , range(len(_snake_case ) ) ) ) _A : Optional[int] = ["""#version: 0.2""", """a p""", """ap t</w>""", """r e""", """a d""", """ad apt</w>""", """"""] _A : Optional[Any] = {"""unk_token""": """<unk>"""} _A : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) _A : Dict = 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 a__ ( self , **_a ) -> Dict: kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **_snake_case ) def a__ ( self , _a ) -> Optional[Any]: _A : str = """adapt react readapt apt""" _A : Any = """adapt react readapt apt""" return input_text, output_text def a__ ( self ) -> List[Any]: _A : int = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) _A : List[Any] = """adapt react readapt apt""" _A : str = """adapt re@@ a@@ c@@ t re@@ adapt apt""".split() _A : Optional[Any] = tokenizer.tokenize(_snake_case ) self.assertListEqual(_snake_case , _snake_case ) _A : Optional[Any] = tokens + [tokenizer.unk_token] _A : Union[str, Any] = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(_snake_case ) , _snake_case )
361
# Copyright (c) 2021-, NVIDIA CORPORATION. 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. #################################################################################################### # # Note: If when running this conversion script you're getting an exception: # ModuleNotFoundError: No module named 'megatron.model.enums' # you need to tell python where to find the clone of Megatron-LM, e.g.: # # cd /tmp # git clone https://github.com/NVIDIA/Megatron-LM # PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ... # # if you already have it cloned elsewhere, simply adjust the path to the existing path # # If the training was done using a Megatron-LM fork, e.g., # https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one # in your path, i.e., /path/to/Megatron-DeepSpeed/ # import argparse import os import re import zipfile import torch from transformers import AutoTokenizer, GPTaConfig def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_=0 ): # Format the message. if name is None: _A : Union[str, Any] = None else: _A : Dict = """.""" * max(0,spaces - 2 ) + """# {:""" + str(50 - spaces ) + """s}""" _A : Tuple = fmt.format(snake_case_ ) # Print and recurse (if needed). if isinstance(snake_case_,snake_case_ ): if msg is not None: print(snake_case_ ) for k in val.keys(): recursive_print(snake_case_,val[k],spaces + 2 ) elif isinstance(snake_case_,torch.Tensor ): print(snake_case_,""":""",val.size() ) else: print(snake_case_,""":""",snake_case_ ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_ ): # Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :] # for compatibility with later versions of NVIDIA Megatron-LM. # The inverse operation is performed inside Megatron-LM to read checkpoints: # https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209 # If param is the weight tensor of the self-attention block, the returned tensor # will have to be transposed one more time to be read by HuggingFace GPT2. _A : str = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] _A : Union[str, Any] = (num_heads, hidden_size, num_splits) + input_shape[1:] _A : Tuple = param.view(*snake_case_ ) _A : Any = param.transpose(0,2 ) _A : int = param.transpose(1,2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] _A : Optional[Any] = (num_heads, num_splits, hidden_size) + input_shape[1:] _A : int = param.view(*snake_case_ ) _A : Any = param.transpose(0,1 ).contiguous() _A : Optional[int] = param.view(*snake_case_ ) return param def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): # The converted output model. _A : Any = {} # old versions did not store training args _A : str = input_state_dict.get("""args""",snake_case_ ) if ds_args is not None: # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint # from pprint import pprint # pprint(vars(ds_args)) _A : Union[str, Any] = ds_args.padded_vocab_size _A : List[Any] = ds_args.max_position_embeddings _A : Optional[int] = ds_args.hidden_size _A : List[Any] = ds_args.num_layers _A : List[str] = ds_args.num_attention_heads _A : int = ds_args.ffn_hidden_size # pprint(config) # The number of heads. _A : Union[str, Any] = config.n_head # The hidden_size per head. _A : List[Any] = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): _A : Tuple = input_state_dict["""checkpoint_version"""] else: _A : Any = 0.0 # The model. _A : Any = input_state_dict["""model"""] # The language model. _A : Tuple = model["""language_model"""] # The embeddings. _A : Any = lm["""embedding"""] # The word embeddings. _A : Dict = embeddings["""word_embeddings"""]["""weight"""] # Truncate the embedding table to vocab_size rows. _A : Union[str, Any] = word_embeddings[: config.vocab_size, :] _A : Tuple = word_embeddings # The position embeddings. _A : Tuple = embeddings["""position_embeddings"""]["""weight"""] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] _A : Any = pos_embeddings.size(0 ) if n_positions != config.n_positions: raise ValueError( f'''pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don\'t match''' ) # Store the position embeddings. _A : Optional[int] = pos_embeddings # The transformer. _A : Any = lm["""transformer"""] if """transformer""" in lm.keys() else lm["""encoder"""] # The regex to extract layer names. _A : Optional[int] = re.compile(r"""layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)""" ) # The simple map of names for "automated" rules. _A : Union[str, Any] = { """attention.dense""": """.attn.c_proj.""", """self_attention.dense""": """.attn.c_proj.""", """mlp.dense_h_to_4h""": """.mlp.c_fc.""", """mlp.dense_4h_to_h""": """.mlp.c_proj.""", } # Extract the layers. for key, val in transformer.items(): # Match the name. _A : List[str] = layer_re.match(snake_case_ ) # Stop if that's not a layer if m is None: break # The index of the layer. _A : Tuple = int(m.group(1 ) ) # The name of the operation. _A : Optional[Any] = m.group(2 ) # Is it a weight or a bias? _A : Dict = m.group(3 ) # The name of the layer. _A : Optional[Any] = f'''transformer.h.{layer_idx}''' # For layernorm(s), simply store the layer norm. if op_name.endswith("""layernorm""" ): _A : Union[str, Any] = """ln_1""" if op_name.startswith("""input""" ) else """ln_2""" _A : List[str] = val # Transpose the QKV matrix. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "weight": # Insert a tensor of 1x1xDxD bias. _A : List[str] = torch.tril(torch.ones((n_positions, n_positions),dtype=torch.floataa ) ).view( 1,1,snake_case_,snake_case_ ) _A : Any = causal_mask # Insert a "dummy" tensor for masked_bias. _A : List[str] = torch.tensor(-1e4,dtype=torch.floataa ) _A : Tuple = masked_bias _A : Tuple = fix_query_key_value_ordering(snake_case_,snake_case_,3,snake_case_,snake_case_ ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. _A : Tuple = out_val.transpose(0,1 ).contiguous() # Store. _A : Any = out_val # Transpose the bias. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "bias": _A : List[str] = fix_query_key_value_ordering(snake_case_,snake_case_,3,snake_case_,snake_case_ ) # Store. No change of shape. _A : Tuple = out_val # Transpose the weights. elif weight_or_bias == "weight": _A : List[str] = megatron_to_transformers[op_name] _A : Any = val.transpose(0,1 ) # Copy the bias. elif weight_or_bias == "bias": _A : Dict = megatron_to_transformers[op_name] _A : List[Any] = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. _A : Optional[Any] = transformer["""final_layernorm.weight"""] _A : Dict = transformer["""final_layernorm.bias"""] # For LM head, transformers' wants the matrix to weight embeddings. _A : List[str] = word_embeddings # It should be done! return output_state_dict def lowerCAmelCase_ ( ): # Create the argument parser. _A : Any = argparse.ArgumentParser() parser.add_argument("""--print-checkpoint-structure""",action="""store_true""" ) parser.add_argument( """path_to_checkpoint""",type=snake_case_,help="""Path to the checkpoint file (.zip archive or direct .pt file)""",) parser.add_argument( """--config_file""",default="""""",type=snake_case_,help="""An optional config json file describing the pre-trained model.""",) _A : Optional[int] = parser.parse_args() # Extract the basename. _A : Any = os.path.dirname(args.path_to_checkpoint ) # Load the model. # the .zip is very optional, let's keep it for backward compatibility print(f'''Extracting PyTorch state dictionary from {args.path_to_checkpoint}''' ) if args.path_to_checkpoint.endswith(""".zip""" ): with zipfile.ZipFile(args.path_to_checkpoint,"""r""" ) as checkpoint: with checkpoint.open("""release/mp_rank_00/model_optim_rng.pt""" ) as pytorch_dict: _A : Tuple = torch.load(snake_case_,map_location="""cpu""" ) else: _A : Tuple = torch.load(args.path_to_checkpoint,map_location="""cpu""" ) _A : Optional[Any] = input_state_dict.get("""args""",snake_case_ ) # Read the config, or default to the model released by NVIDIA. if args.config_file == "": if ds_args is not None: if ds_args.bias_gelu_fusion: _A : Union[str, Any] = """gelu_fast""" elif ds_args.openai_gelu: _A : int = """gelu_new""" else: _A : Optional[Any] = """gelu""" else: # in the very early days this used to be "gelu_new" _A : Any = """gelu_new""" # Spell out all parameters in case the defaults change. _A : Any = GPTaConfig( vocab_size=50257,n_positions=1024,n_embd=1024,n_layer=24,n_head=16,n_inner=4096,activation_function=snake_case_,resid_pdrop=0.1,embd_pdrop=0.1,attn_pdrop=0.1,layer_norm_epsilon=1e-5,initializer_range=0.02,summary_type="""cls_index""",summary_use_proj=snake_case_,summary_activation=snake_case_,summary_proj_to_labels=snake_case_,summary_first_dropout=0.1,scale_attn_weights=snake_case_,use_cache=snake_case_,bos_token_id=50256,eos_token_id=50256,) else: _A : Union[str, Any] = GPTaConfig.from_json_file(args.config_file ) _A : List[str] = ["""GPT2LMHeadModel"""] # Convert. print("""Converting""" ) _A : Optional[Any] = convert_megatron_checkpoint(snake_case_,snake_case_,snake_case_ ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(snake_case_,snake_case_ ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: _A : int = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": _A : Any = """gpt2""" elif tokenizer_type == "PretrainedFromHF": _A : List[Any] = ds_args.tokenizer_name_or_path else: raise ValueError(f'''Unrecognized tokenizer_type {tokenizer_type}''' ) else: _A : Optional[Any] = """gpt2""" _A : List[str] = AutoTokenizer.from_pretrained(snake_case_ ) _A : Tuple = type(snake_case_ ).__name__ _A : Union[str, Any] = tokenizer_class # Store the config to file. print("""Saving config""" ) config.save_pretrained(snake_case_ ) # Save tokenizer based on args print(f'''Adding {tokenizer_class} tokenizer files''' ) tokenizer.save_pretrained(snake_case_ ) # Store the state_dict to file. _A : Union[str, Any] = os.path.join(snake_case_,"""pytorch_model.bin""" ) print(f'''Saving checkpoint to "{output_checkpoint_file}"''' ) torch.save(snake_case_,snake_case_ ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
343
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase ( __snake_case,__snake_case,unittest.TestCase ): _a = StableDiffusionSAGPipeline _a = TEXT_TO_IMAGE_PARAMS _a = TEXT_TO_IMAGE_BATCH_PARAMS _a = TEXT_TO_IMAGE_IMAGE_PARAMS _a = TEXT_TO_IMAGE_IMAGE_PARAMS _a = False def a__ ( self ) -> List[str]: torch.manual_seed(0 ) _A : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) _A : int = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=_a , set_alpha_to_one=_a , ) torch.manual_seed(0 ) _A : Optional[int] = 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 ) _A : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _A : Any = CLIPTextModel(_a ) _A : Union[str, Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) _A : str = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def a__ ( self , _a , _a=0 ) -> Tuple: if str(_a ).startswith("""mps""" ): _A : List[Any] = torch.manual_seed(_a ) else: _A : Optional[int] = torch.Generator(device=_a ).manual_seed(_a ) _A : List[Any] = { """prompt""": """.""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 1.0, """sag_scale""": 1.0, """output_type""": """numpy""", } return inputs def a__ ( self ) -> str: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class lowercase ( unittest.TestCase ): def a__ ( self ) -> List[str]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def a__ ( self ) -> Dict: _A : int = StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""" ) _A : Union[str, Any] = sag_pipe.to(_a ) sag_pipe.set_progress_bar_config(disable=_a ) _A : int = """.""" _A : Optional[Any] = torch.manual_seed(0 ) _A : List[Any] = sag_pipe( [prompt] , generator=_a , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" ) _A : List[str] = output.images _A : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _A : Dict = np.array([0.1568, 0.1738, 0.1695, 0.1693, 0.1507, 0.1705, 0.1547, 0.1751, 0.1949] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def a__ ( self ) -> Any: _A : Any = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) _A : Tuple = sag_pipe.to(_a ) sag_pipe.set_progress_bar_config(disable=_a ) _A : Optional[Any] = """.""" _A : Tuple = torch.manual_seed(0 ) _A : Optional[int] = sag_pipe( [prompt] , generator=_a , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" ) _A : int = output.images _A : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _A : Optional[int] = np.array([0.3459, 0.2876, 0.2537, 0.3002, 0.2671, 0.2160, 0.3026, 0.2262, 0.2371] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def a__ ( self ) -> List[Any]: _A : str = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) _A : int = sag_pipe.to(_a ) sag_pipe.set_progress_bar_config(disable=_a ) _A : Dict = """.""" _A : Union[str, Any] = torch.manual_seed(0 ) _A : List[Any] = sag_pipe( [prompt] , width=768 , height=512 , generator=_a , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" , ) _A : Dict = output.images assert image.shape == (1, 512, 768, 3)
362
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer _snake_case = logging.get_logger(__name__) _snake_case = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _snake_case = { "vocab_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } _snake_case = { "vocab_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } _snake_case = { "vocab_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json" ), }, } _snake_case = { "facebook/dpr-ctx_encoder-single-nq-base": 512, "facebook/dpr-ctx_encoder-multiset-base": 512, } _snake_case = { "facebook/dpr-question_encoder-single-nq-base": 512, "facebook/dpr-question_encoder-multiset-base": 512, } _snake_case = { "facebook/dpr-reader-single-nq-base": 512, "facebook/dpr-reader-multiset-base": 512, } _snake_case = { "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True}, } _snake_case = { "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True}, } _snake_case = { "facebook/dpr-reader-single-nq-base": {"do_lower_case": True}, "facebook/dpr-reader-multiset-base": {"do_lower_case": True}, } class lowercase ( UpperCamelCase__ ): _a = VOCAB_FILES_NAMES _a = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _a = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION class lowercase ( UpperCamelCase__ ): _a = VOCAB_FILES_NAMES _a = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _a = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION _snake_case = collections.namedtuple( "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"] ) _snake_case = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"]) _snake_case = r"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n ```\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n ```\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Returns:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n " @add_start_docstrings(UpperCamelCase__ ) class lowercase : def __call__( self , _a , _a = None , _a = None , _a = False , _a = False , _a = None , _a = None , _a = None , **_a , ) -> BatchEncoding: if titles is None and texts is None: return super().__call__( _a , padding=_a , truncation=_a , max_length=_a , return_tensors=_a , return_attention_mask=_a , **_a , ) elif titles is None or texts is None: _A : Optional[Any] = titles if texts is None else texts return super().__call__( _a , _a , padding=_a , truncation=_a , max_length=_a , return_tensors=_a , return_attention_mask=_a , **_a , ) _A : Dict = titles if not isinstance(_a , _a ) else [titles] _A : Tuple = texts if not isinstance(_a , _a ) else [texts] _A : Any = len(_a ) _A : Optional[Any] = questions if not isinstance(_a , _a ) else [questions] * n_passages if len(_a ) != len(_a ): raise ValueError( F'''There should be as many titles than texts but got {len(_a )} titles and {len(_a )} texts.''' ) _A : str = super().__call__(_a , _a , padding=_a , truncation=_a )["""input_ids"""] _A : Optional[int] = super().__call__(_a , add_special_tokens=_a , padding=_a , truncation=_a )["""input_ids"""] _A : Optional[int] = { """input_ids""": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_a , _a ) ] } if return_attention_mask is not False: _A : Any = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) _A : str = attention_mask return self.pad(_a , padding=_a , max_length=_a , return_tensors=_a ) def a__ ( self , _a , _a , _a = 16 , _a = 64 , _a = 4 , ) -> List[DPRSpanPrediction]: _A : Dict = reader_input["""input_ids"""] _A , _A , _A : Tuple = reader_output[:3] _A : List[str] = len(_a ) _A : Tuple = sorted(range(_a ) , reverse=_a , key=relevance_logits.__getitem__ ) _A : List[DPRReaderOutput] = [] for doc_id in sorted_docs: _A : Tuple = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence _A : int = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: _A : Tuple = sequence_ids.index(self.pad_token_id ) else: _A : Tuple = len(_a ) _A : Union[str, Any] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_a , top_spans=_a , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_a , start_index=_a , end_index=_a , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_a ) >= num_spans: break return nbest_spans_predictions[:num_spans] def a__ ( self , _a , _a , _a , _a , ) -> List[DPRSpanPrediction]: _A : Tuple = [] for start_index, start_score in enumerate(_a ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) _A : Tuple = sorted(_a , key=lambda _a : x[1] , reverse=_a ) _A : Union[str, Any] = [] for (start_index, end_index), score in scores: if start_index > end_index: raise ValueError(F'''Wrong span indices: [{start_index}:{end_index}]''' ) _A : Dict = end_index - start_index + 1 if length > max_answer_length: raise ValueError(F'''Span is too long: {length} > {max_answer_length}''' ) if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_a ) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCamelCase__ ) class lowercase ( UpperCamelCase__,UpperCamelCase__ ): _a = VOCAB_FILES_NAMES _a = READER_PRETRAINED_VOCAB_FILES_MAP _a = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = READER_PRETRAINED_INIT_CONFIGURATION _a = ["input_ids", "attention_mask"]
343
0
import inspect import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py _snake_case = "src/transformers" # This is to make sure the transformers module imported is the one in the repo. _snake_case = direct_transformers_import(PATH_TO_TRANSFORMERS) _snake_case = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` _snake_case = re.compile(r"\[(.+?)\]\((https://huggingface\.co/.+?)\)") _snake_case = { "DecisionTransformerConfig", "EncoderDecoderConfig", "MusicgenConfig", "RagConfig", "SpeechEncoderDecoderConfig", "TimmBackboneConfig", "VisionEncoderDecoderConfig", "VisionTextDualEncoderConfig", "LlamaConfig", } def lowerCAmelCase_ ( snake_case_ ): _A : Optional[Any] = None # source code of `config_class` _A : Optional[Any] = inspect.getsource(UpperCamelCase__ ) _A : str = _re_checkpoint.findall(UpperCamelCase__ ) # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` for ckpt_name, ckpt_link in checkpoints: # allow the link to end with `/` if ckpt_link.endswith("""/""" ): _A : Tuple = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link _A : Union[str, Any] = f'''https://huggingface.co/{ckpt_name}''' if ckpt_link == ckpt_link_from_name: _A : Tuple = ckpt_name break return checkpoint def lowerCAmelCase_ ( ): _A : Any = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue _A : Any = get_checkpoint_from_config_class(UpperCamelCase__ ) _A : str = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: _A : List[Any] = """\n""".join(sorted(UpperCamelCase__ ) ) raise ValueError(f'''The following configurations don\'t contain any valid checkpoint:\n{message}''' ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
363
import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class lowercase ( unittest.TestCase ): @property def a__ ( self ) -> Dict: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def a__ ( self ) -> List[Any]: _A : int = ort.SessionOptions() _A : Any = False return options def a__ ( self ) -> Union[str, Any]: _A : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) _A : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) _A : List[str] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy""" ) # using the PNDM scheduler by default _A : str = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=_a , feature_extractor=_a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_a ) _A : Optional[Any] = """A red cat sitting on a park bench""" _A : Optional[Any] = np.random.RandomState(0 ) _A : Dict = pipe( prompt=_a , image=_a , mask_image=_a , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=_a , output_type="""np""" , ) _A : Optional[int] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1e-2
343
0
import numpy as np import torch from torch.utils.data import Dataset from utils import logger class lowercase ( SCREAMING_SNAKE_CASE__ ): def __init__( self , _a , _a ) -> Optional[int]: _A : Any = params _A : Dict = np.array(_SCREAMING_SNAKE_CASE ) _A : Union[str, Any] = np.array([len(_SCREAMING_SNAKE_CASE ) for t in data] ) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self , _a ) -> int: return (self.token_ids[index], self.lengths[index]) def __len__( self ) -> Optional[Any]: return len(self.lengths ) def a__ ( self ) -> int: assert len(self.token_ids ) == len(self.lengths ) assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) ) def a__ ( self ) -> Optional[Any]: _A : Optional[int] = self.params.max_model_input_size _A : str = self.lengths > max_len logger.info(F'''Splitting {sum(_SCREAMING_SNAKE_CASE )} too long sequences.''' ) def divide_chunks(_a , _a ): return [l[i : i + n] for i in range(0 , len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE )] _A : Optional[Any] = [] _A : Optional[int] = [] if self.params.mlm: _A : Union[str, Any] = self.params.special_tok_ids["cls_token"], self.params.special_tok_ids["sep_token"] else: _A : Any = self.params.special_tok_ids["bos_token"], self.params.special_tok_ids["eos_token"] for seq_, len_ in zip(self.token_ids , self.lengths ): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_ ) new_lengths.append(len_ ) else: _A : List[Any] = [] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: _A : Optional[Any] = np.insert(_SCREAMING_SNAKE_CASE , 0 , _SCREAMING_SNAKE_CASE ) if sub_s[-1] != sep_id: _A : Optional[int] = np.insert(_SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) assert len(_SCREAMING_SNAKE_CASE ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(_SCREAMING_SNAKE_CASE ) new_tok_ids.extend(_SCREAMING_SNAKE_CASE ) new_lengths.extend([len(_SCREAMING_SNAKE_CASE ) for l in sub_seqs] ) _A : Union[str, Any] = np.array(_SCREAMING_SNAKE_CASE ) _A : Any = np.array(_SCREAMING_SNAKE_CASE ) def a__ ( self ) -> str: _A : Union[str, Any] = len(self ) _A : List[Any] = self.lengths > 11 _A : Dict = self.token_ids[indices] _A : Any = self.lengths[indices] _A : Optional[int] = len(self ) logger.info(F'''Remove {init_size - new_size} too short (<=11 tokens) sequences.''' ) def a__ ( self ) -> int: if "unk_token" not in self.params.special_tok_ids: return else: _A : Optional[Any] = self.params.special_tok_ids["unk_token"] _A : Tuple = len(self ) _A : int = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) _A : Optional[Any] = (unk_occs / self.lengths) < 0.5 _A : List[str] = self.token_ids[indices] _A : Dict = self.lengths[indices] _A : Union[str, Any] = len(self ) logger.info(F'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).''' ) def a__ ( self ) -> Any: if not self.params.is_master: return logger.info(F'''{len(self )} sequences''' ) # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def a__ ( self , _a ) -> List[str]: _A : int = [t[0] for t in batch] _A : Tuple = [t[1] for t in batch] assert len(_SCREAMING_SNAKE_CASE ) == len(_SCREAMING_SNAKE_CASE ) # Max for paddings _A : Optional[Any] = max(_SCREAMING_SNAKE_CASE ) # Pad token ids if self.params.mlm: _A : Union[str, Any] = self.params.special_tok_ids["pad_token"] else: _A : List[Any] = self.params.special_tok_ids["unk_token"] _A : Optional[int] = [list(t.astype(_SCREAMING_SNAKE_CASE ) ) + [pad_idx] * (max_seq_len_ - len(_SCREAMING_SNAKE_CASE )) for t in token_ids] assert len(tk_ ) == len(_SCREAMING_SNAKE_CASE ) assert all(len(_SCREAMING_SNAKE_CASE ) == max_seq_len_ for t in tk_ ) _A : Tuple = torch.tensor(tk_ ) # (bs, max_seq_len_) _A : Any = torch.tensor(_SCREAMING_SNAKE_CASE ) # (bs) return tk_t, lg_t
364
from __future__ import annotations def lowerCAmelCase_ ( snake_case_ ): create_state_space_tree(snake_case_,[],0,[0 for i in range(len(snake_case_ ) )] ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,): if index == len(snake_case_ ): print(snake_case_ ) return for i in range(len(snake_case_ ) ): if not index_used[i]: current_sequence.append(sequence[i] ) _A : Optional[Any] = True create_state_space_tree(snake_case_,snake_case_,index + 1,snake_case_ ) current_sequence.pop() _A : str = False _snake_case = [3, 1, 2, 4] generate_all_permutations(sequence) _snake_case = ["A", "B", "C"] generate_all_permutations(sequence_a)
343
0
"""simple docstring""" import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 _snake_case = data_utils.TransfoXLTokenizer _snake_case = data_utils.TransfoXLCorpus _snake_case = data_utils _snake_case = data_utils def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_ ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(_UpperCAmelCase,"""rb""" ) as fp: _A : int = pickle.load(_UpperCAmelCase,encoding="""latin1""" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) _A : Any = pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"] print(f'''Save vocabulary to {pytorch_vocab_dump_path}''' ) _A : Optional[int] = corpus.vocab.__dict__ torch.save(_UpperCAmelCase,_UpperCAmelCase ) _A : Optional[int] = corpus.__dict__ corpus_dict_no_vocab.pop("""vocab""",_UpperCAmelCase ) _A : str = pytorch_dump_folder_path + "/" + CORPUS_NAME print(f'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(_UpperCAmelCase,_UpperCAmelCase ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model _A : Optional[Any] = os.path.abspath(_UpperCAmelCase ) _A : Dict = os.path.abspath(_UpperCAmelCase ) print(f'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": _A : Tuple = TransfoXLConfig() else: _A : str = TransfoXLConfig.from_json_file(_UpperCAmelCase ) print(f'''Building PyTorch model from configuration: {config}''' ) _A : List[Any] = TransfoXLLMHeadModel(_UpperCAmelCase ) _A : Any = load_tf_weights_in_transfo_xl(_UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase ) # Save pytorch-model _A : int = os.path.join(_UpperCAmelCase,_UpperCAmelCase ) _A : List[Any] = os.path.join(_UpperCAmelCase,_UpperCAmelCase ) print(f'''Save PyTorch model to {os.path.abspath(_UpperCAmelCase )}''' ) torch.save(model.state_dict(),_UpperCAmelCase ) print(f'''Save configuration file to {os.path.abspath(_UpperCAmelCase )}''' ) with open(_UpperCAmelCase,"""w""",encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) _snake_case = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
365
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def lowerCAmelCase_ ( snake_case_ ): _A : Tuple = filter(lambda snake_case_ : p.requires_grad,model.parameters() ) _A : str = sum([np.prod(p.size() ) for p in model_parameters] ) return params _snake_case = logging.getLogger(__name__) def lowerCAmelCase_ ( snake_case_,snake_case_ ): if metric == "rouge2": _A : Optional[int] = """{val_avg_rouge2:.4f}-{step_count}""" elif metric == "bleu": _A : Dict = """{val_avg_bleu:.4f}-{step_count}""" elif metric == "em": _A : List[str] = """{val_avg_em:.4f}-{step_count}""" else: raise NotImplementedError( f'''seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this''' """ function.""" ) _A : Optional[int] = ModelCheckpoint( dirpath=snake_case_,filename=snake_case_,monitor=f'''val_{metric}''',mode="""max""",save_top_k=3,every_n_epochs=1,) return checkpoint_callback def lowerCAmelCase_ ( snake_case_,snake_case_ ): return EarlyStopping( monitor=f'''val_{metric}''',mode="""min""" if """loss""" in metric else """max""",patience=snake_case_,verbose=snake_case_,) class lowercase ( pl.Callback ): def a__ ( self , _a , _a ) -> Optional[Any]: _A : List[Any] = {F'''lr_group_{i}''': param["""lr"""] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(_a ) @rank_zero_only def a__ ( self , _a , _a , _a , _a=True ) -> None: logger.info(F'''***** {type_path} results at step {trainer.global_step:05d} *****''' ) _A : int = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["""log""", """progress_bar""", """preds"""]} ) # Log results _A : Dict = Path(pl_module.hparams.output_dir ) if type_path == "test": _A : List[Any] = od / """test_results.txt""" _A : List[Any] = od / """test_generations.txt""" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _A : Optional[int] = od / F'''{type_path}_results/{trainer.global_step:05d}.txt''' _A : int = od / F'''{type_path}_generations/{trainer.global_step:05d}.txt''' results_file.parent.mkdir(exist_ok=_a ) generations_file.parent.mkdir(exist_ok=_a ) with open(_a , """a+""" ) as writer: for key in sorted(_a ): if key in ["log", "progress_bar", "preds"]: continue _A : List[Any] = metrics[key] if isinstance(_a , torch.Tensor ): _A : str = val.item() _A : str = F'''{key}: {val:.6f}\n''' writer.write(_a ) if not save_generations: return if "preds" in metrics: _A : List[Any] = """\n""".join(metrics["""preds"""] ) generations_file.open("""w+""" ).write(_a ) @rank_zero_only def a__ ( self , _a , _a ) -> str: try: _A : int = pl_module.model.model.num_parameters() except AttributeError: _A : str = pl_module.model.num_parameters() _A : Optional[int] = count_trainable_parameters(_a ) # mp stands for million parameters trainer.logger.log_metrics({"""n_params""": npars, """mp""": npars / 1e6, """grad_mp""": n_trainable_pars / 1e6} ) @rank_zero_only def a__ ( self , _a , _a ) -> Optional[int]: save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_a , _a , """test""" ) @rank_zero_only def a__ ( self , _a , _a ) -> Tuple: save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
343
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _snake_case = { "configuration_xlm": ["XLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMConfig", "XLMOnnxConfig"], "tokenization_xlm": ["XLMTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ "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: _snake_case = [ "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 _snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
366
from __future__ import annotations from collections.abc import Callable _snake_case = list[list[float | int]] def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : int = len(snake_case_ ) _A : Matrix = [[0 for _ in range(size + 1 )] for _ in range(snake_case_ )] _A : int _A : int _A : int _A : int _A : int _A : float for row in range(snake_case_ ): for col in range(snake_case_ ): _A : Dict = matrix[row][col] _A : List[Any] = vector[row][0] _A : List[Any] = 0 _A : Optional[Any] = 0 while row < size and col < size: # pivoting _A : Any = max((abs(augmented[rowa][col] ), rowa) for rowa in range(snake_case_,snake_case_ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: _A , _A : Optional[Any] = augmented[pivot_row], augmented[row] for rowa in range(row + 1,snake_case_ ): _A : str = augmented[rowa][col] / augmented[row][col] _A : List[Any] = 0 for cola in range(col + 1,size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1,snake_case_ ): for row in range(snake_case_ ): _A : int = augmented[row][col] / augmented[col][col] for cola in range(snake_case_,size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row],10 )] for row in range(snake_case_ ) ] def lowerCAmelCase_ ( snake_case_ ): _A : int = len(snake_case_ ) _A : Matrix = [[0 for _ in range(snake_case_ )] for _ in range(snake_case_ )] _A : Matrix = [[0] for _ in range(snake_case_ )] _A : Matrix _A : int _A : int _A : int for x_val, y_val in enumerate(snake_case_ ): for col in range(snake_case_ ): _A : str = (x_val + 1) ** (size - col - 1) _A : List[str] = y_val _A : Any = solve(snake_case_,snake_case_ ) def interpolated_func(snake_case_ ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(snake_case_ ) ) return interpolated_func def lowerCAmelCase_ ( snake_case_ ): return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def lowerCAmelCase_ ( snake_case_ = question_function,snake_case_ = 10 ): _A : list[int] = [func(snake_case_ ) for x_val in range(1,order + 1 )] _A : list[Callable[[int], int]] = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1,order + 1 ) ] _A : int = 0 _A : Callable[[int], int] _A : int for poly in polynomials: _A : Optional[int] = 1 while func(snake_case_ ) == poly(snake_case_ ): x_val += 1 ret += poly(snake_case_ ) return ret if __name__ == "__main__": print(f"""{solution() = }""")
343
0
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from transformers.modeling_outputs import BaseModelOutput from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING _snake_case = logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase__ ) class lowercase ( UpperCamelCase__ ): def __init__( self , **_a ) -> Dict: super().__init__(**__lowerCamelCase ) if self.framework == "tf": raise ValueError(F'''The {self.__class__} is only available in PyTorch.''' ) requires_backends(self , """vision""" ) self.check_model_type(__lowerCamelCase ) def __call__( self , _a , _a = None , **_a , ) -> Optional[Any]: if "text_queries" in kwargs: _A : Optional[Any] = kwargs.pop("""text_queries""" ) if isinstance(__lowerCamelCase , (str, Image.Image) ): _A : int = {"""image""": image, """candidate_labels""": candidate_labels} else: _A : str = image _A : Optional[Any] = super().__call__(__lowerCamelCase , **__lowerCamelCase ) return results def a__ ( self , **_a ) -> List[str]: _A : Optional[Any] = {} if "threshold" in kwargs: _A : Any = kwargs["""threshold"""] if "top_k" in kwargs: _A : List[str] = kwargs["""top_k"""] return {}, {}, postprocess_params def a__ ( self , _a ) -> Any: _A : List[Any] = load_image(inputs["""image"""] ) _A : int = inputs["""candidate_labels"""] if isinstance(__lowerCamelCase , __lowerCamelCase ): _A : List[str] = candidate_labels.split(""",""" ) _A : Any = torch.tensor([[image.height, image.width]] , dtype=torch.intaa ) for i, candidate_label in enumerate(__lowerCamelCase ): _A : Union[str, Any] = self.tokenizer(__lowerCamelCase , return_tensors=self.framework ) _A : Dict = self.image_processor(__lowerCamelCase , return_tensors=self.framework ) yield { "is_last": i == len(__lowerCamelCase ) - 1, "target_size": target_size, "candidate_label": candidate_label, **text_inputs, **image_features, } def a__ ( self , _a ) -> Any: _A : List[str] = model_inputs.pop("""target_size""" ) _A : str = model_inputs.pop("""candidate_label""" ) _A : Optional[int] = model_inputs.pop("""is_last""" ) _A : Dict = self.model(**__lowerCamelCase ) _A : Tuple = {"""target_size""": target_size, """candidate_label""": candidate_label, """is_last""": is_last, **outputs} return model_outputs def a__ ( self , _a , _a=0.1 , _a=None ) -> int: _A : str = [] for model_output in model_outputs: _A : Optional[Any] = model_output["""candidate_label"""] _A : Optional[int] = BaseModelOutput(__lowerCamelCase ) _A : List[str] = self.image_processor.post_process_object_detection( outputs=__lowerCamelCase , threshold=__lowerCamelCase , target_sizes=model_output["""target_size"""] )[0] for index in outputs["scores"].nonzero(): _A : Tuple = outputs["""scores"""][index].item() _A : str = self._get_bounding_box(outputs["""boxes"""][index][0] ) _A : int = {"""score""": score, """label""": label, """box""": box} results.append(__lowerCamelCase ) _A : List[str] = sorted(__lowerCamelCase , key=lambda _a : x["score"] , reverse=__lowerCamelCase ) if top_k: _A : str = results[:top_k] return results def a__ ( self , _a ) -> Tuple: if self.framework != "pt": raise ValueError("""The ZeroShotObjectDetectionPipeline is only available in PyTorch.""" ) _A , _A , _A , _A : Any = box.int().tolist() _A : Any = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
367
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup _snake_case = "https://www.indeed.co.in/jobs?q=mobile+app+development&l=" def lowerCAmelCase_ ( snake_case_ = "mumbai" ): _A : Optional[Any] = BeautifulSoup(requests.get(url + location ).content,"""html.parser""" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("""div""",attrs={"""data-tn-component""": """organicJob"""} ): _A : Tuple = job.find("""a""",attrs={"""data-tn-element""": """jobTitle"""} ).text.strip() _A : Optional[int] = job.find("""span""",{"""class""": """company"""} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs("Bangalore"), 1): print(f"""Job {i:>2} is {job[0]} at {job[1]}""")
343
0
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 lowercase ( unittest.TestCase ): def a__ ( self , _a ) -> Optional[Any]: for model_result in results.values(): for batch_size, sequence_length in zip(model_result["""bs"""] , model_result["""ss"""] ): _A : Union[str, Any] = model_result["""result"""][batch_size][sequence_length] self.assertIsNotNone(_lowerCamelCase ) def a__ ( self ) -> Any: _A : Tuple = """sshleifer/tiny-gpt2""" _A : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , ) _A : List[str] = PyTorchBenchmark(_lowerCamelCase ) _A : 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 ) -> Optional[int]: _A : int = """sgugger/tiny-distilbert-classification""" _A : Optional[int] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , only_pretrain_model=_lowerCamelCase , ) _A : Tuple = PyTorchBenchmark(_lowerCamelCase ) _A : 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 ) -> List[str]: _A : str = """sshleifer/tiny-gpt2""" _A : List[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , torchscript=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , ) _A : Tuple = PyTorchBenchmark(_lowerCamelCase ) _A : Optional[int] = 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 ) -> Union[str, Any]: _A : List[Any] = """sshleifer/tiny-gpt2""" _A : List[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , fpaa=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , ) _A : Tuple = PyTorchBenchmark(_lowerCamelCase ) _A : 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: _A : Any = """sshleifer/tiny-gpt2""" _A : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) # set architectures equal to `None` _A : Tuple = None _A : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , ) _A : int = PyTorchBenchmark(_lowerCamelCase , configs=[config] ) _A : 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 ) -> Dict: _A : Tuple = """sshleifer/tiny-gpt2""" _A : List[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , ) _A : str = PyTorchBenchmark(_lowerCamelCase ) _A : Tuple = 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 ) -> Dict: _A : int = """sshleifer/tiny-gpt2""" _A : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , fpaa=_lowerCamelCase , multi_process=_lowerCamelCase , ) _A : int = PyTorchBenchmark(_lowerCamelCase ) _A : List[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]: _A : Optional[int] = """sshleifer/tiny-gpt2""" _A : int = AutoConfig.from_pretrained(_lowerCamelCase ) _A : List[str] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , ) _A : str = PyTorchBenchmark(_lowerCamelCase , configs=[config] ) _A : 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 ) -> Any: _A : Tuple = """sshleifer/tinier_bart""" _A : Dict = AutoConfig.from_pretrained(_lowerCamelCase ) _A : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , ) _A : List[Any] = PyTorchBenchmark(_lowerCamelCase , configs=[config] ) _A : 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 ) -> Tuple: _A : Optional[int] = """sshleifer/tiny-gpt2""" _A : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) _A : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , ) _A : Any = PyTorchBenchmark(_lowerCamelCase , configs=[config] ) _A : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def a__ ( self ) -> List[str]: _A : Optional[int] = """sshleifer/tinier_bart""" _A : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) _A : Union[str, Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , ) _A : List[str] = PyTorchBenchmark(_lowerCamelCase , configs=[config] ) _A : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def a__ ( self ) -> Optional[int]: _A : Optional[int] = """sshleifer/tiny-gpt2""" with tempfile.TemporaryDirectory() as tmp_dir: _A : Dict = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , save_to_csv=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(_lowerCamelCase , """inf_time.csv""" ) , train_memory_csv_file=os.path.join(_lowerCamelCase , """train_mem.csv""" ) , inference_memory_csv_file=os.path.join(_lowerCamelCase , """inf_mem.csv""" ) , train_time_csv_file=os.path.join(_lowerCamelCase , """train_time.csv""" ) , env_info_csv_file=os.path.join(_lowerCamelCase , """env.csv""" ) , multi_process=_lowerCamelCase , ) _A : Any = PyTorchBenchmark(_lowerCamelCase ) benchmark.run() self.assertTrue(Path(os.path.join(_lowerCamelCase , """inf_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase , """train_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase , """inf_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase , """train_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase , """env.csv""" ) ).exists() ) def a__ ( self ) -> List[str]: _A : List[Any] = """sshleifer/tiny-gpt2""" def _check_summary_is_not_empty(_a ): self.assertTrue(hasattr(_lowerCamelCase , """sequential""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """cumulative""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """current""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """total""" ) ) with tempfile.TemporaryDirectory() as tmp_dir: _A : Union[str, Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(_lowerCamelCase , """log.txt""" ) , log_print=_lowerCamelCase , trace_memory_line_by_line=_lowerCamelCase , multi_process=_lowerCamelCase , ) _A : Any = PyTorchBenchmark(_lowerCamelCase ) _A : Any = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_lowerCamelCase , """log.txt""" ) ).exists() )
368
from __future__ import annotations from decimal import Decimal from numpy import array def lowerCAmelCase_ ( snake_case_ ): _A : Tuple = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(snake_case_ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix _A : List[Any] = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creates a copy of the matrix with swapped positions of the elements _A : Tuple = [[0.0, 0.0], [0.0, 0.0]] _A , _A : List[str] = matrix[1][1], matrix[0][0] _A , _A : List[str] = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(snake_case_ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(snake_case_ ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule _A : List[str] = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creating cofactor matrix _A : List[Any] = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] _A : Union[str, Any] = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) _A : Optional[Any] = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) _A : Any = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) _A : List[Any] = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) _A : int = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) _A : Union[str, Any] = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) _A : Any = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) _A : List[str] = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) _A : Optional[int] = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) _A : List[Any] = array(snake_case_ ) for i in range(3 ): for j in range(3 ): _A : List[str] = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix _A : Union[str, Any] = array(snake_case_ ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(snake_case_ ) # Calculate the inverse of the matrix return [[float(d(snake_case_ ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError("""Please provide a matrix of size 2x2 or 3x3.""" )
343
0
"""simple docstring""" import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() _snake_case = logging.get_logger(__name__) def lowerCAmelCase_ ( snake_case_ ): _A : Optional[int] = MobileNetVaConfig(layer_norm_eps=0.0_01 ) if "_quant" in model_name: raise ValueError("""Quantized models are not supported.""" ) _A : int = re.match(r"""^mobilenet_v1_([^_]*)_([^_]*)$""",_snake_case ) if matches: _A : List[str] = float(matches[1] ) _A : Dict = int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". _A : List[str] = 1001 _A : Tuple = "imagenet-1k-id2label.json" _A : Union[str, Any] = "huggingface/label-files" _A : str = json.load(open(hf_hub_download(_snake_case,_snake_case,repo_type="""dataset""" ),"""r""" ) ) _A : Tuple = {int(_snake_case ) + 1: v for k, v in idalabel.items()} _A : Dict = "background" _A : str = idalabel _A : List[Any] = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase_ ( ): _A : Optional[int] = "http://images.cocodataset.org/val2017/000000039769.jpg" _A : Any = Image.open(requests.get(_snake_case,stream=_snake_case ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_=False ): _A : int = get_mobilenet_va_config(_snake_case ) # Load 🤗 model _A : List[Any] = MobileNetVaForImageClassification(_snake_case ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(_snake_case,_snake_case,_snake_case ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor _A : Dict = MobileNetVaImageProcessor( crop_size={"""width""": config.image_size, """height""": config.image_size},size={"""shortest_edge""": config.image_size + 32},) _A : int = image_processor(images=prepare_img(),return_tensors="""pt""" ) _A : Any = model(**_snake_case ) _A : Dict = outputs.logits assert logits.shape == (1, 1001) if model_name == "mobilenet_v1_1.0_224": _A : Tuple = torch.tensor([-4.17_39, -1.12_33, 3.12_05] ) elif model_name == "mobilenet_v1_0.75_192": _A : Optional[Any] = torch.tensor([-3.94_40, -2.31_41, -0.33_33] ) else: _A : str = None if expected_logits is not None: assert torch.allclose(logits[0, :3],_snake_case,atol=1e-4 ) Path(_snake_case ).mkdir(exist_ok=_snake_case ) print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(_snake_case ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(_snake_case ) if push_to_hub: print("""Pushing to the hub...""" ) _A : List[str] = "google/" + model_name image_processor.push_to_hub(_snake_case ) model.push_to_hub(_snake_case ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="mobilenet_v1_1.0_224", type=str, help="Name of the MobileNetV1 model you'd like to convert. Should in the form 'mobilenet_v1_<depth>_<size>'.", ) parser.add_argument( "--checkpoint_path", required=True, type=str, help="Path to the original TensorFlow checkpoint (.ckpt file)." ) parser.add_argument( "--pytorch_dump_folder_path", required=True, 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." ) _snake_case = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
369
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class lowercase ( UpperCamelCase__ ): _a = 42 class lowercase ( UpperCamelCase__,UpperCamelCase__ ): @register_to_config def __init__( self , _a = 32 , _a = 64 , _a = 20 , _a = 768 , _a=77 , _a=4 , _a = 0.0 , _a = "silu" , _a = None , _a = None , _a = "linear" , _a = "prd" , _a = None , _a = None , _a = None , ) -> Any: super().__init__() _A : int = num_attention_heads _A : Union[str, Any] = attention_head_dim _A : Tuple = num_attention_heads * attention_head_dim _A : Any = additional_embeddings _A : Any = time_embed_dim or inner_dim _A : List[str] = embedding_proj_dim or embedding_dim _A : Optional[int] = clip_embed_dim or embedding_dim _A : Union[str, Any] = Timesteps(_a , _a , 0 ) _A : str = TimestepEmbedding(_a , _a , out_dim=_a , act_fn=_a ) _A : Dict = nn.Linear(_a , _a ) if embedding_proj_norm_type is None: _A : int = None elif embedding_proj_norm_type == "layer": _A : Optional[Any] = nn.LayerNorm(_a ) else: raise ValueError(F'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}''' ) _A : Optional[Any] = nn.Linear(_a , _a ) if encoder_hid_proj_type is None: _A : Union[str, Any] = None elif encoder_hid_proj_type == "linear": _A : Tuple = nn.Linear(_a , _a ) else: raise ValueError(F'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}''' ) _A : List[str] = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , _a ) ) if added_emb_type == "prd": _A : str = nn.Parameter(torch.zeros(1 , 1 , _a ) ) elif added_emb_type is None: _A : Union[str, Any] = None else: raise ValueError( F'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.''' ) _A : int = nn.ModuleList( [ BasicTransformerBlock( _a , _a , _a , dropout=_a , activation_fn="""gelu""" , attention_bias=_a , ) for d in range(_a ) ] ) if norm_in_type == "layer": _A : Union[str, Any] = nn.LayerNorm(_a ) elif norm_in_type is None: _A : Tuple = None else: raise ValueError(F'''Unsupported norm_in_type: {norm_in_type}.''' ) _A : int = nn.LayerNorm(_a ) _A : str = nn.Linear(_a , _a ) _A : Any = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -10000.0 ) causal_attention_mask.triu_(1 ) _A : Optional[int] = causal_attention_mask[None, ...] self.register_buffer("""causal_attention_mask""" , _a , persistent=_a ) _A : Tuple = nn.Parameter(torch.zeros(1 , _a ) ) _A : Dict = nn.Parameter(torch.zeros(1 , _a ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def a__ ( self ) -> Dict[str, AttentionProcessor]: _A : List[str] = {} def fn_recursive_add_processors(_a , _a , _a ): if hasattr(_a , """set_processor""" ): _A : Tuple = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F'''{name}.{sub_name}''' , _a , _a ) return processors for name, module in self.named_children(): fn_recursive_add_processors(_a , _a , _a ) return processors def a__ ( self , _a ) -> List[str]: _A : Optional[int] = len(self.attn_processors.keys() ) if isinstance(_a , _a ) and len(_a ) != count: raise ValueError( F'''A dict of processors was passed, but the number of processors {len(_a )} does not match the''' F''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''' ) def fn_recursive_attn_processor(_a , _a , _a ): if hasattr(_a , """set_processor""" ): if not isinstance(_a , _a ): module.set_processor(_a ) else: module.set_processor(processor.pop(F'''{name}.processor''' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F'''{name}.{sub_name}''' , _a , _a ) for name, module in self.named_children(): fn_recursive_attn_processor(_a , _a , _a ) def a__ ( self ) -> Union[str, Any]: self.set_attn_processor(AttnProcessor() ) def a__ ( self , _a , _a , _a , _a = None , _a = None , _a = True , ) -> Optional[Any]: _A : Tuple = hidden_states.shape[0] _A : List[Any] = timestep if not torch.is_tensor(_a ): _A : Dict = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(_a ) and len(timesteps.shape ) == 0: _A : Tuple = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML _A : Optional[int] = timesteps * torch.ones(_a , dtype=timesteps.dtype , device=timesteps.device ) _A : Dict = self.time_proj(_a ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. _A : Tuple = timesteps_projected.to(dtype=self.dtype ) _A : List[Any] = self.time_embedding(_a ) if self.embedding_proj_norm is not None: _A : Dict = self.embedding_proj_norm(_a ) _A : List[Any] = self.embedding_proj(_a ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: _A : List[Any] = self.encoder_hidden_states_proj(_a ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""" ) _A : Optional[int] = self.proj_in(_a ) _A : Optional[int] = self.positional_embedding.to(hidden_states.dtype ) _A : Union[str, Any] = [] _A : List[str] = 0 if encoder_hidden_states is not None: additional_embeds.append(_a ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: _A : List[str] = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: _A : List[str] = hidden_states[:, None, :] _A : Dict = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: _A : Optional[int] = self.prd_embedding.to(hidden_states.dtype ).expand(_a , -1 , -1 ) additional_embeds.append(_a ) _A : str = torch.cat( _a , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens _A : Dict = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: _A : Union[str, Any] = F.pad( _a , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) _A : Optional[Any] = hidden_states + positional_embeddings if attention_mask is not None: _A : Optional[Any] = (1 - attention_mask.to(hidden_states.dtype )) * -10000.0 _A : List[Any] = F.pad(_a , (0, self.additional_embeddings) , value=0.0 ) _A : Optional[Any] = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) _A : int = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: _A : str = self.norm_in(_a ) for block in self.transformer_blocks: _A : List[Any] = block(_a , attention_mask=_a ) _A : Any = self.norm_out(_a ) if self.prd_embedding is not None: _A : int = hidden_states[:, -1] else: _A : Any = hidden_states[:, additional_embeddings_len:] _A : Union[str, Any] = self.proj_to_clip_embeddings(_a ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=_a ) def a__ ( self , _a ) -> Tuple: _A : List[Any] = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
343
0
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class lowercase ( unittest.TestCase ): def __init__( self , _a , _a=7 , _a=3 , _a=18 , _a=30 , _a=400 , _a=True , _a=None , _a=True , ) -> Dict: _A : int = size if size is not None else {"height": 18, "width": 18} _A : List[Any] = parent _A : Tuple = batch_size _A : Optional[int] = num_channels _A : Tuple = image_size _A : Tuple = min_resolution _A : Optional[int] = max_resolution _A : str = do_resize _A : int = size _A : Tuple = apply_ocr def a__ ( self ) -> List[Any]: return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class lowercase ( _a,unittest.TestCase ): _a = LayoutLMvaImageProcessor if is_pytesseract_available() else None def a__ ( self ) -> Optional[int]: _A : int = LayoutLMvaImageProcessingTester(self ) @property def a__ ( self ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def a__ ( self ) -> Optional[Any]: _A : Tuple = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , """do_resize""" ) ) self.assertTrue(hasattr(_a , """size""" ) ) self.assertTrue(hasattr(_a , """apply_ocr""" ) ) def a__ ( self ) -> Union[str, Any]: _A : str = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) _A : int = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def a__ ( self ) -> Optional[Any]: pass def a__ ( self ) -> Any: # Initialize image_processing _A : Any = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _A : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _A : Optional[Any] = image_processing(image_inputs[0] , return_tensors="""pt""" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) self.assertIsInstance(encoding.words , _a ) self.assertIsInstance(encoding.boxes , _a ) # Test batched _A : Optional[Any] = image_processing(_a , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def a__ ( self ) -> str: # Initialize image_processing _A : Any = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _A : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for image in image_inputs: self.assertIsInstance(_a , np.ndarray ) # Test not batched input _A : Optional[int] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched _A : List[str] = image_processing(_a , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def a__ ( self ) -> int: # Initialize image_processing _A : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _A : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) for image in image_inputs: self.assertIsInstance(_a , torch.Tensor ) # Test not batched input _A : List[str] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched _A : Dict = image_processing(_a , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def a__ ( self ) -> Optional[int]: # with apply_OCR = True _A : Union[str, Any] = LayoutLMvaImageProcessor() from datasets import load_dataset _A : Union[str, Any] = load_dataset("""hf-internal-testing/fixtures_docvqa""" , split="""test""" ) _A : Dict = Image.open(ds[0]["""file"""] ).convert("""RGB""" ) _A : List[Any] = image_processing(_a , return_tensors="""pt""" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 _A : List[Any] = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231 _A : List[Any] = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , _a ) self.assertListEqual(encoding.boxes , _a ) # with apply_OCR = False _A : Any = LayoutLMvaImageProcessor(apply_ocr=_a ) _A : Dict = image_processing(_a , return_tensors="""pt""" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
370
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : Any = None if token is not None: _A : int = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} _A : Any = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' _A : Union[str, Any] = requests.get(snake_case_,headers=snake_case_ ).json() _A : str = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) _A : int = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(snake_case_ ): _A : List[str] = requests.get(url + f'''&page={i + 2}''',headers=snake_case_ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : int = None if token is not None: _A : List[str] = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} _A : str = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100''' _A : Optional[Any] = requests.get(snake_case_,headers=snake_case_ ).json() _A : Any = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) _A : Tuple = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(snake_case_ ): _A : List[Any] = requests.get(url + f'''&page={i + 2}''',headers=snake_case_ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_ ): _A : Dict = None if token is not None: _A : int = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} _A : Tuple = requests.get(snake_case_,headers=snake_case_,allow_redirects=snake_case_ ) _A : Tuple = result.headers["""Location"""] _A : Union[str, Any] = requests.get(snake_case_,allow_redirects=snake_case_ ) _A : Dict = os.path.join(snake_case_,f'''{artifact_name}.zip''' ) with open(snake_case_,"""wb""" ) as fp: fp.write(response.content ) def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : List[str] = [] _A : int = [] _A : Tuple = None with zipfile.ZipFile(snake_case_ ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case_ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(snake_case_ ) as f: for line in f: _A : Any = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs _A : Dict = line[: line.index(""": """ )] _A : Dict = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed _A : List[str] = line[len("""FAILED """ ) :] failed_tests.append(snake_case_ ) elif filename == "job_name.txt": _A : Optional[int] = line if len(snake_case_ ) != len(snake_case_ ): raise ValueError( f'''`errors` and `failed_tests` should have the same number of elements. Got {len(snake_case_ )} for `errors` ''' f'''and {len(snake_case_ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some''' """ problem.""" ) _A : Any = None if job_name and job_links: _A : Dict = job_links.get(snake_case_,snake_case_ ) # A list with elements of the form (line of error, error, failed test) _A : Optional[int] = [x + [y] + [job_link] for x, y in zip(snake_case_,snake_case_ )] return result def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : Dict = [] _A : Optional[int] = [os.path.join(snake_case_,snake_case_ ) for p in os.listdir(snake_case_ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(snake_case_,job_links=snake_case_ ) ) return errors def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : Dict = Counter() counter.update([x[1] for x in logs] ) _A : Tuple = counter.most_common() _A : Tuple = {} for error, count in counts: if error_filter is None or error not in error_filter: _A : str = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} _A : Union[str, Any] = dict(sorted(r.items(),key=lambda snake_case_ : item[1]["count"],reverse=snake_case_ ) ) return r def lowerCAmelCase_ ( snake_case_ ): _A : Union[str, Any] = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): _A : Dict = test.split("""/""" )[2] else: _A : str = None return test def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : str = [(x[0], x[1], get_model(x[2] )) for x in logs] _A : Union[str, Any] = [x for x in logs if x[2] is not None] _A : Optional[Any] = {x[2] for x in logs} _A : List[Any] = {} for test in tests: _A : Any = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) _A : Union[str, Any] = counter.most_common() _A : Any = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} _A : str = sum(error_counts.values() ) if n_errors > 0: _A : Optional[int] = {"""count""": n_errors, """errors""": error_counts} _A : Union[str, Any] = dict(sorted(r.items(),key=lambda snake_case_ : item[1]["count"],reverse=snake_case_ ) ) return r def lowerCAmelCase_ ( snake_case_ ): _A : Optional[int] = """| no. | error | status |""" _A : List[Any] = """|-:|:-|:-|""" _A : List[Any] = [header, sep] for error in reduced_by_error: _A : List[str] = reduced_by_error[error]["""count"""] _A : List[Any] = f'''| {count} | {error[:100]} | |''' lines.append(snake_case_ ) return "\n".join(snake_case_ ) def lowerCAmelCase_ ( snake_case_ ): _A : List[Any] = """| model | no. of errors | major error | count |""" _A : Optional[Any] = """|-:|-:|-:|-:|""" _A : Union[str, Any] = [header, sep] for model in reduced_by_model: _A : Dict = reduced_by_model[model]["""count"""] _A , _A : str = list(reduced_by_model[model]["""errors"""].items() )[0] _A : Union[str, Any] = f'''| {model} | {count} | {error[:60]} | {_count} |''' lines.append(snake_case_ ) return "\n".join(snake_case_ ) if __name__ == "__main__": _snake_case = 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.") _snake_case = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) _snake_case = get_job_links(args.workflow_run_id, token=args.token) _snake_case = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: _snake_case = k.find(" / ") _snake_case = k[index + len(" / ") :] _snake_case = v with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) _snake_case = 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) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) _snake_case = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error _snake_case = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors _snake_case = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) _snake_case = reduce_by_error(errors) _snake_case = reduce_by_model(errors) _snake_case = make_github_table(reduced_by_error) _snake_case = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: fp.write(sa) with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: fp.write(sa)
343
0
def lowerCAmelCase_ ( snake_case_ ): if not grid or not grid[0]: raise TypeError("""The grid does not contain the appropriate information""" ) for cell_n in range(1,len(grid[0] ) ): grid[0][cell_n] += grid[0][cell_n - 1] _A : Any = grid[0] for row_n in range(1,len(_lowerCAmelCase ) ): _A : List[str] = grid[row_n] _A : Tuple = fill_row(_lowerCAmelCase,_lowerCAmelCase ) _A : Optional[int] = grid[row_n] return grid[-1][-1] def lowerCAmelCase_ ( snake_case_,snake_case_ ): current_row[0] += row_above[0] for cell_n in range(1,len(_lowerCAmelCase ) ): current_row[cell_n] += min(current_row[cell_n - 1],row_above[cell_n] ) return current_row if __name__ == "__main__": import doctest doctest.testmod()
371
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class lowercase ( unittest.TestCase ): def a__ ( self ) -> List[str]: debug_launcher(test_script.main ) def a__ ( self ) -> Any: debug_launcher(test_ops.main )
343
0
from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING _snake_case = logging.get_logger(__name__) @add_end_docstrings(__lowerCamelCase ) class lowercase ( __lowerCamelCase ): def __init__( self , *_a , **_a ) -> Dict: super().__init__(*__lowercase , **__lowercase ) requires_backends(self , """vision""" ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == """tf""" else MODEL_FOR_VISION_2_SEQ_MAPPING ) def a__ ( self , _a=None , _a=None , _a=None ) -> List[Any]: _A : Dict = {} _A : str = {} if prompt is not None: _A : Dict = prompt if generate_kwargs is not None: _A : Optional[Any] = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: _A : List[str] = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( """\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,""" """ please use only one""" ) _A : List[str] = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self , _a , **_a ) -> Optional[Any]: return super().__call__(__lowercase , **__lowercase ) def a__ ( self , _a , _a=None ) -> Dict: _A : str = load_image(__lowercase ) if prompt is not None: if not isinstance(__lowercase , __lowercase ): raise ValueError( F'''Received an invalid text input, got - {type(__lowercase )} - but expected a single string. ''' """Note also that one single text can be provided for conditional image to text generation.""" ) _A : Tuple = self.model.config.model_type if model_type == "git": _A : str = self.image_processor(images=__lowercase , return_tensors=self.framework ) _A : Union[str, Any] = self.tokenizer(text=__lowercase , add_special_tokens=__lowercase ).input_ids _A : str = [self.tokenizer.cls_token_id] + input_ids _A : Any = torch.tensor(__lowercase ).unsqueeze(0 ) model_inputs.update({"""input_ids""": input_ids} ) elif model_type == "pix2struct": _A : Dict = self.image_processor(images=__lowercase , header_text=__lowercase , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation _A : Union[str, Any] = self.image_processor(images=__lowercase , return_tensors=self.framework ) _A : List[Any] = self.tokenizer(__lowercase , return_tensors=self.framework ) model_inputs.update(__lowercase ) else: raise ValueError(F'''Model type {model_type} does not support conditional text generation''' ) else: _A : str = self.image_processor(images=__lowercase , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: _A : Dict = None return model_inputs def a__ ( self , _a , _a=None ) -> Optional[Any]: # Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the # pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first. if ( "input_ids" in model_inputs and isinstance(model_inputs["""input_ids"""] , __lowercase ) and all(x is None for x in model_inputs["""input_ids"""] ) ): _A : Optional[int] = None if generate_kwargs is None: _A : Optional[int] = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. _A : Dict = model_inputs.pop(self.model.main_input_name ) _A : Dict = self.model.generate(__lowercase , **__lowercase , **__lowercase ) return model_outputs def a__ ( self , _a ) -> Union[str, Any]: _A : Optional[int] = [] for output_ids in model_outputs: _A : str = { '''generated_text''': self.tokenizer.decode( __lowercase , skip_special_tokens=__lowercase , ) } records.append(__lowercase ) return records
350
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _snake_case = logging.get_logger(__name__) _snake_case = { "microsoft/resnet-50": "https://huggingface.co/microsoft/resnet-50/blob/main/config.json", } class lowercase ( UpperCamelCase__,UpperCamelCase__ ): _a = "resnet" _a = ["basic", "bottleneck"] def __init__( self , _a=3 , _a=64 , _a=[256, 512, 1024, 2048] , _a=[3, 4, 6, 3] , _a="bottleneck" , _a="relu" , _a=False , _a=None , _a=None , **_a , ) -> int: super().__init__(**_a ) if layer_type not in self.layer_types: raise ValueError(F'''layer_type={layer_type} is not one of {",".join(self.layer_types )}''' ) _A : Optional[Any] = num_channels _A : List[Any] = embedding_size _A : int = hidden_sizes _A : Union[str, Any] = depths _A : Optional[int] = layer_type _A : Any = hidden_act _A : List[Any] = downsample_in_first_stage _A : int = ["""stem"""] + [F'''stage{idx}''' for idx in range(1 , len(_a ) + 1 )] _A , _A : str = get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names ) class lowercase ( UpperCamelCase__ ): _a = version.parse("1.11" ) @property def a__ ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def a__ ( self ) -> float: return 1e-3
343
0
from __future__ import annotations def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_,): _A : Optional[Any] = len(_UpperCAmelCase ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append([""". """ * i + """Q """ + """. """ * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(_UpperCAmelCase ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col],[*diagonal_right_collisions, row - col],[*diagonal_left_collisions, row + col],_UpperCAmelCase,_UpperCAmelCase,) def lowerCAmelCase_ ( snake_case_ ): _A : list[list[str]] = [] depth_first_search([],[],[],_UpperCAmelCase,_UpperCAmelCase ) # Print all the boards for board in boards: for column in board: print(_UpperCAmelCase ) print("""""" ) print(len(_UpperCAmelCase ),"""solutions were found.""" ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
351
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowerCAmelCase_ ( snake_case_,snake_case_ ): # Load checkpoint _A : Optional[int] = torch.load(snake_case_,map_location="""cpu""" ) _A : Any = chkpt["""model"""] # We have the base model one level deeper than the original XLM repository _A : Any = {} for k, v in state_dict.items(): if "pred_layer" in k: _A : Tuple = v else: _A : Dict = v _A : Optional[Any] = chkpt["""params"""] _A : Union[str, Any] = {n: v for n, v in config.items() if not isinstance(snake_case_,(torch.FloatTensor, numpy.ndarray) )} _A : str = chkpt["""dico_word2id"""] _A : Optional[Any] = {s + """</w>""" if s.find("""@@""" ) == -1 and i > 13 else s.replace("""@@""","""""" ): i for s, i in vocab.items()} # Save pytorch-model _A : Dict = pytorch_dump_folder_path + """/""" + WEIGHTS_NAME _A : Any = pytorch_dump_folder_path + """/""" + CONFIG_NAME _A : Optional[int] = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""vocab_file"""] print(f'''Save PyTorch model to {pytorch_weights_dump_path}''' ) torch.save(snake_case_,snake_case_ ) print(f'''Save configuration file to {pytorch_config_dump_path}''' ) with open(snake_case_,"""w""",encoding="""utf-8""" ) as f: f.write(json.dumps(snake_case_,indent=2 ) + """\n""" ) print(f'''Save vocab file to {pytorch_config_dump_path}''' ) with open(snake_case_,"""w""",encoding="""utf-8""" ) as f: f.write(json.dumps(snake_case_,indent=2 ) + """\n""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( "--xlm_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) _snake_case = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
343
0
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class lowercase ( unittest.TestCase ): def a__ ( self ): debug_launcher(test_script.main ) def a__ ( self ): debug_launcher(test_ops.main )
352
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowercase ( UpperCamelCase__ ): _a = ["image_processor", "tokenizer"] _a = "BlipImageProcessor" _a = ("BertTokenizer", "BertTokenizerFast") def __init__( self , _a , _a ) -> Any: _A : List[Any] = False super().__init__(_a , _a ) _A : Optional[int] = self.image_processor def __call__( self , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ) -> BatchEncoding: if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None: _A : Dict = self.tokenizer _A : Dict = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) return text_encoding # add pixel_values _A : int = self.image_processor(_a , return_tensors=_a ) if text is not None: _A : List[Any] = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) else: _A : int = None if text_encoding is not None: encoding_image_processor.update(_a ) return encoding_image_processor def a__ ( self , *_a , **_a ) -> Any: return self.tokenizer.batch_decode(*_a , **_a ) def a__ ( self , *_a , **_a ) -> List[str]: return self.tokenizer.decode(*_a , **_a ) @property def a__ ( self ) -> Optional[Any]: _A : Any = self.tokenizer.model_input_names _A : List[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
343
0
from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .attention_processor import AttentionProcessor, AttnProcessor from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder @dataclass class lowercase ( snake_case_ ): _a = 4_2 class lowercase ( snake_case_,snake_case_ ): _a = True @register_to_config def __init__( self , _a = 3 , _a = 3 , _a = ("DownEncoderBlock2D",) , _a = ("UpDecoderBlock2D",) , _a = (64,) , _a = 1 , _a = "silu" , _a = 4 , _a = 32 , _a = 32 , _a = 0.18215 , ) -> Optional[Any]: super().__init__() # pass init params to Encoder _A : Union[str, Any] = Encoder( in_channels=_a , out_channels=_a , down_block_types=_a , block_out_channels=_a , layers_per_block=_a , act_fn=_a , norm_num_groups=_a , double_z=_a , ) # pass init params to Decoder _A : int = Decoder( in_channels=_a , out_channels=_a , up_block_types=_a , block_out_channels=_a , layers_per_block=_a , norm_num_groups=_a , act_fn=_a , ) _A : Tuple = nn.Convad(2 * latent_channels , 2 * latent_channels , 1 ) _A : Optional[Any] = nn.Convad(_a , _a , 1 ) _A : List[str] = False _A : Optional[Any] = False # only relevant if vae tiling is enabled _A : Tuple = self.config.sample_size _A : int = ( self.config.sample_size[0] if isinstance(self.config.sample_size , (list, tuple) ) else self.config.sample_size ) _A : List[str] = int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) ) _A : int = 0.25 def a__ ( self , _a , _a=False ) -> Tuple: if isinstance(_a , (Encoder, Decoder) ): _A : str = value def a__ ( self , _a = True ) -> List[str]: _A : Tuple = use_tiling def a__ ( self ) -> Dict: self.enable_tiling(_a ) def a__ ( self ) -> Tuple: _A : Optional[Any] = True def a__ ( self ) -> Union[str, Any]: _A : Union[str, Any] = False @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def a__ ( self ) -> Dict[str, AttentionProcessor]: _A : str = {} def fn_recursive_add_processors(_a , _a , _a ): if hasattr(_a , """set_processor""" ): _A : int = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F'''{name}.{sub_name}''' , _a , _a ) return processors for name, module in self.named_children(): fn_recursive_add_processors(_a , _a , _a ) return processors def a__ ( self , _a ) -> Optional[int]: _A : Optional[int] = len(self.attn_processors.keys() ) if isinstance(_a , _a ) and len(_a ) != count: raise ValueError( F'''A dict of processors was passed, but the number of processors {len(_a )} does not match the''' F''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''' ) def fn_recursive_attn_processor(_a , _a , _a ): if hasattr(_a , """set_processor""" ): if not isinstance(_a , _a ): module.set_processor(_a ) else: module.set_processor(processor.pop(F'''{name}.processor''' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F'''{name}.{sub_name}''' , _a , _a ) for name, module in self.named_children(): fn_recursive_attn_processor(_a , _a , _a ) def a__ ( self ) -> Tuple: self.set_attn_processor(AttnProcessor() ) @apply_forward_hook def a__ ( self , _a , _a = True ) -> AutoencoderKLOutput: if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size): return self.tiled_encode(_a , return_dict=_a ) if self.use_slicing and x.shape[0] > 1: _A : int = [self.encoder(_a ) for x_slice in x.split(1 )] _A : str = torch.cat(_a ) else: _A : Optional[Any] = self.encoder(_a ) _A : Tuple = self.quant_conv(_a ) _A : str = DiagonalGaussianDistribution(_a ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=_a ) def a__ ( self , _a , _a = True ) -> Union[DecoderOutput, torch.FloatTensor]: if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size): return self.tiled_decode(_a , return_dict=_a ) _A : int = self.post_quant_conv(_a ) _A : Dict = self.decoder(_a ) if not return_dict: return (dec,) return DecoderOutput(sample=_a ) @apply_forward_hook def a__ ( self , _a , _a = True ) -> Union[DecoderOutput, torch.FloatTensor]: if self.use_slicing and z.shape[0] > 1: _A : Optional[int] = [self._decode(_a ).sample for z_slice in z.split(1 )] _A : List[str] = torch.cat(_a ) else: _A : Optional[Any] = self._decode(_a ).sample if not return_dict: return (decoded,) return DecoderOutput(sample=_a ) def a__ ( self , _a , _a , _a ) -> Any: _A : Union[str, Any] = min(a.shape[2] , b.shape[2] , _a ) for y in range(_a ): _A : Optional[int] = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent) return b def a__ ( self , _a , _a , _a ) -> str: _A : Tuple = min(a.shape[3] , b.shape[3] , _a ) for x in range(_a ): _A : Union[str, Any] = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent) return b def a__ ( self , _a , _a = True ) -> AutoencoderKLOutput: _A : int = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) ) _A : Optional[int] = int(self.tile_latent_min_size * self.tile_overlap_factor ) _A : Optional[int] = self.tile_latent_min_size - blend_extent # Split the image into 512x512 tiles and encode them separately. _A : List[str] = [] for i in range(0 , x.shape[2] , _a ): _A : str = [] for j in range(0 , x.shape[3] , _a ): _A : str = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size] _A : Optional[Any] = self.encoder(_a ) _A : Optional[int] = self.quant_conv(_a ) row.append(_a ) rows.append(_a ) _A : List[str] = [] for i, row in enumerate(_a ): _A : Optional[Any] = [] for j, tile in enumerate(_a ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: _A : Any = self.blend_v(rows[i - 1][j] , _a , _a ) if j > 0: _A : Optional[Any] = self.blend_h(row[j - 1] , _a , _a ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(_a , dim=3 ) ) _A : List[Any] = torch.cat(_a , dim=2 ) _A : Union[str, Any] = DiagonalGaussianDistribution(_a ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=_a ) def a__ ( self , _a , _a = True ) -> Union[DecoderOutput, torch.FloatTensor]: _A : int = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) ) _A : Any = int(self.tile_sample_min_size * self.tile_overlap_factor ) _A : Tuple = self.tile_sample_min_size - blend_extent # Split z into overlapping 64x64 tiles and decode them separately. # The tiles have an overlap to avoid seams between tiles. _A : List[str] = [] for i in range(0 , z.shape[2] , _a ): _A : Dict = [] for j in range(0 , z.shape[3] , _a ): _A : Any = z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size] _A : Any = self.post_quant_conv(_a ) _A : str = self.decoder(_a ) row.append(_a ) rows.append(_a ) _A : Union[str, Any] = [] for i, row in enumerate(_a ): _A : str = [] for j, tile in enumerate(_a ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: _A : Any = self.blend_v(rows[i - 1][j] , _a , _a ) if j > 0: _A : Tuple = self.blend_h(row[j - 1] , _a , _a ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(_a , dim=3 ) ) _A : int = torch.cat(_a , dim=2 ) if not return_dict: return (dec,) return DecoderOutput(sample=_a ) def a__ ( self , _a , _a = False , _a = True , _a = None , ) -> Union[DecoderOutput, torch.FloatTensor]: _A : Dict = sample _A : int = self.encode(_a ).latent_dist if sample_posterior: _A : Optional[int] = posterior.sample(generator=_a ) else: _A : Optional[Any] = posterior.mode() _A : Tuple = self.decode(_a ).sample if not return_dict: return (dec,) return DecoderOutput(sample=_a )
353
from random import randint from tempfile import TemporaryFile import numpy as np def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : Tuple = 0 if start < end: _A : Tuple = randint(snake_case_,snake_case_ ) _A : Any = a[end] _A : int = a[pivot] _A : int = temp _A , _A : List[Any] = _in_place_partition(snake_case_,snake_case_,snake_case_ ) count += _in_place_quick_sort(snake_case_,snake_case_,p - 1 ) count += _in_place_quick_sort(snake_case_,p + 1,snake_case_ ) return count def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : str = 0 _A : List[str] = randint(snake_case_,snake_case_ ) _A : Union[str, Any] = a[end] _A : List[str] = a[pivot] _A : List[Any] = temp _A : List[str] = start - 1 for index in range(snake_case_,snake_case_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value _A : Union[str, Any] = new_pivot_index + 1 _A : List[Any] = a[new_pivot_index] _A : Optional[int] = a[index] _A : List[Any] = temp _A : Optional[Any] = a[new_pivot_index + 1] _A : Any = a[end] _A : Dict = temp return new_pivot_index + 1, count _snake_case = TemporaryFile() _snake_case = 100 # 1000 elements are to be sorted _snake_case , _snake_case = 0, 1 # mean and standard deviation _snake_case = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array _snake_case = np.load(outfile) _snake_case = len(M) - 1 _snake_case = _in_place_quick_sort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
343
0
import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class lowercase ( UpperCamelCase__ ): _a = 4_2 _a = None def lowerCAmelCase_ ( snake_case_,snake_case_=0.9_99,snake_case_="cosine",): if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case_ ): return math.cos((t + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case_ ): return math.exp(t * -12.0 ) else: raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) _A : List[Any] = [] for i in range(_lowerCAmelCase ): _A : int = i / num_diffusion_timesteps _A : List[Any] = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(_lowerCAmelCase ) / alpha_bar_fn(_lowerCAmelCase ),_lowerCAmelCase ) ) return torch.tensor(_lowerCAmelCase,dtype=torch.floataa ) class lowercase ( UpperCamelCase__,UpperCamelCase__ ): @register_to_config def __init__( self , _a = 1000 , _a = "fixed_small_log" , _a = True , _a = 1.0 , _a = "epsilon" , _a = "squaredcos_cap_v2" , ) -> Optional[int]: if beta_schedule != "squaredcos_cap_v2": raise ValueError("""UnCLIPScheduler only supports `beta_schedule`: \'squaredcos_cap_v2\'""" ) _A : Dict = betas_for_alpha_bar(_lowerCAmelCase ) _A : List[Any] = 1.0 - self.betas _A : str = torch.cumprod(self.alphas , dim=0 ) _A : str = torch.tensor(1.0 ) # standard deviation of the initial noise distribution _A : Dict = 1.0 # setable values _A : Dict = None _A : Any = torch.from_numpy(np.arange(0 , _lowerCAmelCase )[::-1].copy() ) _A : Any = variance_type def a__ ( self , _a , _a = None ) -> Dict: return sample def a__ ( self , _a , _a = None ) -> Any: _A : Optional[Any] = num_inference_steps _A : int = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) _A : List[str] = (np.arange(0 , _lowerCAmelCase ) * step_ratio).round()[::-1].copy().astype(np.intaa ) _A : str = torch.from_numpy(_lowerCAmelCase ).to(_lowerCAmelCase ) def a__ ( self , _a , _a=None , _a=None , _a=None ) -> Optional[int]: if prev_timestep is None: _A : int = t - 1 _A : Optional[int] = self.alphas_cumprod[t] _A : Any = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one _A : Tuple = 1 - alpha_prod_t _A : str = 1 - alpha_prod_t_prev if prev_timestep == t - 1: _A : int = self.betas[t] else: _A : Union[str, Any] = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample _A : Dict = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: _A : Optional[Any] = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": _A : Tuple = torch.log(torch.clamp(_lowerCAmelCase , min=1e-20 ) ) _A : Union[str, Any] = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler _A : List[Any] = variance.log() _A : str = beta.log() _A : Dict = (predicted_variance + 1) / 2 _A : Optional[int] = frac * max_log + (1 - frac) * min_log return variance def a__ ( self , _a , _a , _a , _a = None , _a=None , _a = True , ) -> Tuple: _A : int = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": _A , _A : List[str] = torch.split(_lowerCAmelCase , sample.shape[1] , dim=1 ) else: _A : Tuple = None # 1. compute alphas, betas if prev_timestep is None: _A : Any = t - 1 _A : Optional[Any] = self.alphas_cumprod[t] _A : Optional[Any] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one _A : List[str] = 1 - alpha_prod_t _A : Dict = 1 - alpha_prod_t_prev if prev_timestep == t - 1: _A : str = self.betas[t] _A : str = self.alphas[t] else: _A : str = 1 - alpha_prod_t / alpha_prod_t_prev _A : List[str] = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": _A : Dict = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": _A : Optional[int] = model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`''' """ for the UnCLIPScheduler.""" ) # 3. Clip "predicted x_0" if self.config.clip_sample: _A : List[Any] = torch.clamp( _lowerCAmelCase , -self.config.clip_sample_range , self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _A : List[str] = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t _A : List[str] = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _A : str = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise _A : List[str] = 0 if t > 0: _A : List[Any] = randn_tensor( model_output.shape , dtype=model_output.dtype , generator=_lowerCAmelCase , device=model_output.device ) _A : List[str] = self._get_variance( _lowerCAmelCase , predicted_variance=_lowerCAmelCase , prev_timestep=_lowerCAmelCase , ) if self.variance_type == "fixed_small_log": _A : List[str] = variance elif self.variance_type == "learned_range": _A : Optional[int] = (0.5 * variance).exp() else: raise ValueError( F'''variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`''' """ for the UnCLIPScheduler.""" ) _A : Optional[Any] = variance * variance_noise _A : Optional[Any] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=_lowerCAmelCase , pred_original_sample=_lowerCAmelCase ) def a__ ( self , _a , _a , _a , ) -> Optional[int]: _A : List[Any] = self.alphas_cumprod.to(device=original_samples.device , dtype=original_samples.dtype ) _A : Union[str, Any] = timesteps.to(original_samples.device ) _A : Union[str, Any] = alphas_cumprod[timesteps] ** 0.5 _A : List[Any] = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): _A : str = sqrt_alpha_prod.unsqueeze(-1 ) _A : List[str] = (1 - alphas_cumprod[timesteps]) ** 0.5 _A : int = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): _A : Optional[Any] = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) _A : Tuple = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
354
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { "MIT/ast-finetuned-audioset-10-10-0.4593": ( "https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json" ), } class lowercase ( UpperCamelCase__ ): _a = "audio-spectrogram-transformer" def __init__( self , _a=768 , _a=12 , _a=12 , _a=3072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1e-12 , _a=16 , _a=True , _a=10 , _a=10 , _a=1024 , _a=128 , **_a , ) -> List[Any]: super().__init__(**_a ) _A : Any = hidden_size _A : Tuple = num_hidden_layers _A : List[str] = num_attention_heads _A : Any = intermediate_size _A : Optional[Any] = hidden_act _A : Optional[Any] = hidden_dropout_prob _A : Any = attention_probs_dropout_prob _A : Optional[Any] = initializer_range _A : Optional[Any] = layer_norm_eps _A : str = patch_size _A : Tuple = qkv_bias _A : Dict = frequency_stride _A : Union[str, Any] = time_stride _A : Any = max_length _A : Tuple = num_mel_bins
343
0
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _snake_case = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' _snake_case = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' _snake_case = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,_KWARGS_DESCRIPTION ) class lowercase ( datasets.Metric ): def a__ ( self ) -> Any: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://github.com/krishnap25/mauve""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/krishnap25/mauve"""] , reference_urls=[ """https://arxiv.org/abs/2102.01454""", """https://github.com/krishnap25/mauve""", ] , ) def a__ ( self , _a , _a , _a=None , _a=None , _a=None , _a=None , _a="auto" , _a=-1 , _a=0.9 , _a=5 , _a=500 , _a="gpt2-large" , _a=-1 , _a=1024 , _a=25 , _a=5 , _a=True , _a=25 , ) -> List[str]: _A : Optional[Any] = compute_mauve( p_text=_SCREAMING_SNAKE_CASE , q_text=_SCREAMING_SNAKE_CASE , p_features=_SCREAMING_SNAKE_CASE , q_features=_SCREAMING_SNAKE_CASE , p_tokens=_SCREAMING_SNAKE_CASE , q_tokens=_SCREAMING_SNAKE_CASE , num_buckets=_SCREAMING_SNAKE_CASE , pca_max_data=_SCREAMING_SNAKE_CASE , kmeans_explained_var=_SCREAMING_SNAKE_CASE , kmeans_num_redo=_SCREAMING_SNAKE_CASE , kmeans_max_iter=_SCREAMING_SNAKE_CASE , featurize_model_name=_SCREAMING_SNAKE_CASE , device_id=_SCREAMING_SNAKE_CASE , max_text_length=_SCREAMING_SNAKE_CASE , divergence_curve_discretization_size=_SCREAMING_SNAKE_CASE , mauve_scaling_factor=_SCREAMING_SNAKE_CASE , verbose=_SCREAMING_SNAKE_CASE , seed=_SCREAMING_SNAKE_CASE , ) return out
355
import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) _snake_case = logging.getLogger() def lowerCAmelCase_ ( ): _A : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""-f""" ) _A : Optional[Any] = parser.parse_args() return args.f class lowercase ( UpperCamelCase__ ): def a__ ( self ) -> None: _A : List[Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(_a ) def a__ ( self , _a ) -> Dict: _A : Tuple = get_gpu_count() if n_gpu > 1: pass # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560 # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py" # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split() # cmd = [sys.executable] + distributed_args + args # execute_subprocess_async(cmd, env=self.get_env()) # XXX: test the results - need to save them first into .json file else: args.insert(0 , """run_glue_deebert.py""" ) with patch.object(_a , """argv""" , _a ): _A : Optional[Any] = run_glue_deebert.main() for value in result.values(): self.assertGreaterEqual(_a , 0.666 ) @slow @require_torch_non_multi_gpu def a__ ( self ) -> Optional[int]: _A : Tuple = """ --model_type roberta --model_name_or_path roberta-base --task_name MRPC --do_train --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --max_seq_length 128 --per_gpu_eval_batch_size=1 --per_gpu_train_batch_size=8 --learning_rate 2e-4 --num_train_epochs 3 --overwrite_output_dir --seed 42 --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --save_steps 0 --overwrite_cache --eval_after_first_stage """.split() self.run_and_check(_a ) _A : Optional[Any] = """ --model_type roberta --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --task_name MRPC --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --max_seq_length 128 --eval_each_highway --eval_highway --overwrite_cache --per_gpu_eval_batch_size=1 """.split() self.run_and_check(_a ) _A : List[str] = """ --model_type roberta --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --task_name MRPC --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --max_seq_length 128 --early_exit_entropy 0.1 --eval_highway --overwrite_cache --per_gpu_eval_batch_size=1 """.split() self.run_and_check(_a )
343
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { "andreasmadsen/efficient_mlm_m0.40": ( "https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json" ), } class lowercase ( snake_case_ ): _a = "roberta-prelayernorm" def __init__( self , _a=5_0265 , _a=768 , _a=12 , _a=12 , _a=3072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1e-12 , _a=1 , _a=0 , _a=2 , _a="absolute" , _a=True , _a=None , **_a , ) -> Optional[int]: super().__init__(pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a ) _A : List[Any] = vocab_size _A : List[Any] = hidden_size _A : Any = num_hidden_layers _A : Tuple = num_attention_heads _A : Any = hidden_act _A : Union[str, Any] = intermediate_size _A : Optional[Any] = hidden_dropout_prob _A : Tuple = attention_probs_dropout_prob _A : Tuple = max_position_embeddings _A : Optional[Any] = type_vocab_size _A : Union[str, Any] = initializer_range _A : Union[str, Any] = layer_norm_eps _A : str = position_embedding_type _A : Tuple = use_cache _A : int = classifier_dropout class lowercase ( snake_case_ ): @property def a__ ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _A : List[str] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: _A : str = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
356
import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowercase : def __init__( self , _a , _a=13 , _a=30 , _a=2 , _a=3 , _a=True , _a=True , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=10 , _a=0.02 , _a=None , ) -> Union[str, Any]: _A : Optional[int] = parent _A : Dict = batch_size _A : Any = image_size _A : Optional[int] = patch_size _A : Optional[int] = num_channels _A : List[Any] = is_training _A : Optional[Any] = use_labels _A : Any = hidden_size _A : Any = num_hidden_layers _A : List[Any] = num_attention_heads _A : int = intermediate_size _A : Dict = hidden_act _A : Optional[int] = hidden_dropout_prob _A : str = attention_probs_dropout_prob _A : Any = type_sequence_label_size _A : str = initializer_range _A : Tuple = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) _A : List[Any] = (image_size // patch_size) ** 2 _A : str = num_patches + 1 def a__ ( self ) -> Dict: _A : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A : List[str] = None if self.use_labels: _A : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _A : List[Any] = self.get_config() return config, pixel_values, labels def a__ ( self ) -> Union[str, Any]: return ViTMSNConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , ) def a__ ( self , _a , _a , _a ) -> Dict: _A : List[str] = ViTMSNModel(config=_a ) model.to(_a ) model.eval() _A : List[str] = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a__ ( self , _a , _a , _a ) -> List[str]: _A : Union[str, Any] = self.type_sequence_label_size _A : Tuple = ViTMSNForImageClassification(_a ) model.to(_a ) model.eval() _A : Optional[int] = model(_a , labels=_a ) print("""Pixel and labels shape: {pixel_values.shape}, {labels.shape}""" ) print("""Labels: {labels}""" ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images _A : Dict = 1 _A : str = ViTMSNForImageClassification(_a ) model.to(_a ) model.eval() _A : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _A : int = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a__ ( self ) -> Any: _A : Optional[int] = self.prepare_config_and_inputs() _A , _A , _A : Dict = config_and_inputs _A : List[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowercase ( UpperCamelCase__,UpperCamelCase__,unittest.TestCase ): _a = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () _a = ( {"feature-extraction": ViTMSNModel, "image-classification": ViTMSNForImageClassification} if is_torch_available() else {} ) _a = False _a = False _a = False _a = False def a__ ( self ) -> Tuple: _A : Tuple = ViTMSNModelTester(self ) _A : List[Any] = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def a__ ( self ) -> Optional[int]: self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMSN does not use inputs_embeds""" ) def a__ ( self ) -> int: pass def a__ ( self ) -> Any: _A , _A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : Tuple = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _A : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , nn.Linear ) ) def a__ ( self ) -> str: _A , _A : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : int = model_class(_a ) _A : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A : str = [*signature.parameters.keys()] _A : Optional[int] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def a__ ( self ) -> List[Any]: _A : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def a__ ( self ) -> Any: _A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @slow def a__ ( self ) -> int: for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _A : int = ViTMSNModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowerCAmelCase_ ( ): _A : Dict = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class lowercase ( unittest.TestCase ): @cached_property def a__ ( self ) -> int: return ViTImageProcessor.from_pretrained("""facebook/vit-msn-small""" ) if is_vision_available() else None @slow def a__ ( self ) -> Optional[int]: torch.manual_seed(2 ) _A : Tuple = ViTMSNForImageClassification.from_pretrained("""facebook/vit-msn-small""" ).to(_a ) _A : Tuple = self.default_image_processor _A : Dict = prepare_img() _A : Optional[Any] = image_processor(images=_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): _A : int = model(**_a ) # verify the logits _A : Union[str, Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _a ) _A : Optional[int] = torch.tensor([-0.0803, -0.4454, -0.2375] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) )
343
0
def lowerCAmelCase_ ( snake_case_ ): _A : List[str] = generate_pascal_triangle(snake_case_ ) for row_idx in range(snake_case_ ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=""" """ ) # Print row values for col_idx in range(row_idx + 1 ): if col_idx != row_idx: print(triangle[row_idx][col_idx],end=""" """ ) else: print(triangle[row_idx][col_idx],end="""""" ) print() def lowerCAmelCase_ ( snake_case_ ): if not isinstance(snake_case_,snake_case_ ): raise TypeError("""The input value of \'num_rows\' should be \'int\'""" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( """The input value of \'num_rows\' should be greater than or equal to 0""" ) _A : list[list[int]] = [] for current_row_idx in range(snake_case_ ): _A : str = populate_current_row(snake_case_,snake_case_ ) triangle.append(snake_case_ ) return triangle def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : List[Any] = [-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 _A : Optional[int] = 1, 1 for current_col_idx in range(1,snake_case_ ): calculate_current_element( snake_case_,snake_case_,snake_case_,snake_case_ ) return current_row def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,): _A : Optional[Any] = triangle[current_row_idx - 1][current_col_idx - 1] _A : List[Any] = triangle[current_row_idx - 1][current_col_idx] _A : Tuple = above_to_left_elt + above_to_right_elt def lowerCAmelCase_ ( snake_case_ ): if not isinstance(snake_case_,snake_case_ ): raise TypeError("""The input value of \'num_rows\' should be \'int\'""" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( """The input value of \'num_rows\' should be greater than or equal to 0""" ) _A : list[list[int]] = [[1]] for row_index in range(1,snake_case_ ): _A : Tuple = [0] + result[-1] + [0] _A : Any = row_index + 1 # Calculate the number of distinct elements in a row _A : str = sum(divmod(snake_case_,2 ) ) _A : Optional[int] = [ temp_row[i - 1] + temp_row[i] for i in range(1,distinct_elements + 1 ) ] _A : int = row_first_half[: (row_index + 1) // 2] row_second_half.reverse() _A : List[Any] = row_first_half + row_second_half result.append(snake_case_ ) return result def lowerCAmelCase_ ( ): from collections.abc import Callable from timeit import timeit def benchmark_a_function(snake_case_,snake_case_ ) -> None: _A : Tuple = f'''{func.__name__}({value})''' _A : Dict = timeit(f'''__main__.{call}''',setup="""import __main__""" ) # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(f'''{call:38} -- {timing:.4f} seconds''' ) for value in range(15 ): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(snake_case_,snake_case_ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
357
def lowerCAmelCase_ ( snake_case_ = 1000 ): _A : List[Any] = 3 _A : Tuple = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f"""{solution() = }""")
343
0
import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) 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 lowercase ( lowerCamelCase__,unittest.TestCase ): _a = KandinskyVaaControlnetPipeline _a = ['image_embeds', 'negative_image_embeds', 'hint'] _a = ['image_embeds', 'negative_image_embeds', 'hint'] _a = [ 'generator', 'height', 'width', 'latents', 'guidance_scale', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] _a = False @property def a__ ( self ) -> Union[str, Any]: return 32 @property def a__ ( self ) -> List[str]: return 32 @property def a__ ( self ) -> Tuple: return self.time_input_dim @property def a__ ( self ) -> Dict: return self.time_input_dim * 4 @property def a__ ( self ) -> Optional[Any]: return 100 @property def a__ ( self ) -> Optional[int]: torch.manual_seed(0 ) _A : List[Any] = { """in_channels""": 8, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image_hint""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } _A : List[Any] = UNetaDConditionModel(**lowercase__ ) return model @property def a__ ( self ) -> Dict: return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "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", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def a__ ( self ) -> str: torch.manual_seed(0 ) _A : List[str] = VQModel(**self.dummy_movq_kwargs ) return model def a__ ( self ) -> Tuple: _A : str = self.dummy_unet _A : List[str] = self.dummy_movq _A : Any = DDIMScheduler( num_train_timesteps=1000 , beta_schedule="""linear""" , beta_start=0.00085 , beta_end=0.012 , clip_sample=lowercase__ , set_alpha_to_one=lowercase__ , steps_offset=1 , prediction_type="""epsilon""" , thresholding=lowercase__ , ) _A : List[Any] = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def a__ ( self , _a , _a=0 ) -> List[str]: _A : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(lowercase__ ) ).to(lowercase__ ) _A : Any = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( lowercase__ ) # create hint _A : str = floats_tensor((1, 3, 64, 64) , rng=random.Random(lowercase__ ) ).to(lowercase__ ) if str(lowercase__ ).startswith("""mps""" ): _A : Tuple = torch.manual_seed(lowercase__ ) else: _A : Tuple = torch.Generator(device=lowercase__ ).manual_seed(lowercase__ ) _A : List[Any] = { """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """hint""": hint, """generator""": generator, """height""": 64, """width""": 64, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def a__ ( self ) -> List[str]: _A : List[Any] = """cpu""" _A : str = self.get_dummy_components() _A : int = self.pipeline_class(**lowercase__ ) _A : Any = pipe.to(lowercase__ ) pipe.set_progress_bar_config(disable=lowercase__ ) _A : Optional[Any] = pipe(**self.get_dummy_inputs(lowercase__ ) ) _A : Any = output.images _A : Union[str, Any] = pipe( **self.get_dummy_inputs(lowercase__ ) , return_dict=lowercase__ , )[0] _A : Union[str, Any] = image[0, -3:, -3:, -1] _A : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _A : Any = np.array( [0.6959826, 0.868279, 0.7558092, 0.68769467, 0.85805804, 0.65977496, 0.44885302, 0.5959111, 0.4251595] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' @slow @require_torch_gpu class lowercase ( unittest.TestCase ): def a__ ( self ) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def a__ ( self ) -> str: _A : Optional[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy""" ) _A : Union[str, Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/hint_image_cat.png""" ) _A : Optional[Any] = torch.from_numpy(np.array(lowercase__ ) ).float() / 255.0 _A : List[str] = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) _A : Any = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(lowercase__ ) _A : Optional[int] = KandinskyVaaControlnetPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa ) _A : Any = pipeline.to(lowercase__ ) pipeline.set_progress_bar_config(disable=lowercase__ ) _A : Tuple = """A robot, 4k photo""" _A : Optional[Any] = torch.Generator(device="""cuda""" ).manual_seed(0 ) _A , _A : Optional[Any] = pipe_prior( lowercase__ , generator=lowercase__ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() _A : Optional[int] = torch.Generator(device="""cuda""" ).manual_seed(0 ) _A : List[str] = pipeline( image_embeds=lowercase__ , negative_image_embeds=lowercase__ , hint=lowercase__ , generator=lowercase__ , num_inference_steps=100 , output_type="""np""" , ) _A : Any = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(lowercase__ , lowercase__ )
358
import inspect import unittest from transformers import ConvNextConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase : def __init__( self , _a , _a=13 , _a=32 , _a=3 , _a=4 , _a=[10, 20, 30, 40] , _a=[2, 2, 3, 2] , _a=True , _a=True , _a=37 , _a="gelu" , _a=10 , _a=0.02 , _a=["stage2", "stage3", "stage4"] , _a=[2, 3, 4] , _a=None , ) -> List[Any]: _A : Tuple = parent _A : Any = batch_size _A : int = image_size _A : Tuple = num_channels _A : List[Any] = num_stages _A : Any = hidden_sizes _A : Union[str, Any] = depths _A : Union[str, Any] = is_training _A : Tuple = use_labels _A : Optional[Any] = intermediate_size _A : Union[str, Any] = hidden_act _A : Any = num_labels _A : List[str] = initializer_range _A : str = out_features _A : int = out_indices _A : List[Any] = scope def a__ ( self ) -> str: _A : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A : str = None if self.use_labels: _A : int = ids_tensor([self.batch_size] , self.num_labels ) _A : str = self.get_config() return config, pixel_values, labels def a__ ( self ) -> List[str]: return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=_a , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def a__ ( self , _a , _a , _a ) -> int: _A : int = ConvNextModel(config=_a ) model.to(_a ) model.eval() _A : int = model(_a ) # expected last hidden states: B, C, H // 32, W // 32 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 , _a ) -> List[Any]: _A : Union[str, Any] = ConvNextForImageClassification(_a ) model.to(_a ) model.eval() _A : List[Any] = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a__ ( self , _a , _a , _a ) -> str: _A : List[str] = ConvNextBackbone(config=_a ) model.to(_a ) model.eval() _A : Optional[int] = model(_a ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None _A : Optional[Any] = None _A : str = ConvNextBackbone(config=_a ) model.to(_a ) model.eval() _A : int = model(_a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def a__ ( self ) -> int: _A : int = self.prepare_config_and_inputs() _A , _A , _A : List[Any] = config_and_inputs _A : Any = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowercase ( UpperCamelCase__,UpperCamelCase__,unittest.TestCase ): _a = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) _a = ( {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification} if is_torch_available() else {} ) _a = True _a = False _a = False _a = False _a = False def a__ ( self ) -> Dict: _A : int = ConvNextModelTester(self ) _A : List[Any] = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def a__ ( self ) -> Any: 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 ) -> str: return @unittest.skip(reason="""ConvNext does not use inputs_embeds""" ) def a__ ( self ) -> Tuple: pass @unittest.skip(reason="""ConvNext does not support input and output embeddings""" ) def a__ ( self ) -> Optional[Any]: pass @unittest.skip(reason="""ConvNext does not use feedforward chunking""" ) def a__ ( self ) -> List[Any]: pass def a__ ( self ) -> Optional[Any]: _A , _A : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : Optional[Any] = model_class(_a ) _A : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A : List[Any] = [*signature.parameters.keys()] _A : int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def a__ ( self ) -> Union[str, Any]: _A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def a__ ( self ) -> Tuple: _A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_a ) def a__ ( self ) -> Tuple: def check_hidden_states_output(_a , _a , _a ): _A : Tuple = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): _A : Dict = model(**self._prepare_for_class(_a , _a ) ) _A : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _A : Dict = self.model_tester.num_stages self.assertEqual(len(_a ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) _A , _A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A : List[Any] = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _A : Union[str, Any] = True check_hidden_states_output(_a , _a , _a ) def a__ ( self ) -> int: _A : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @slow def a__ ( self ) -> Optional[int]: for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _A : Optional[Any] = ConvNextModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowerCAmelCase_ ( ): _A : Optional[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class lowercase ( unittest.TestCase ): @cached_property def a__ ( self ) -> str: return AutoImageProcessor.from_pretrained("""facebook/convnext-tiny-224""" ) if is_vision_available() else None @slow def a__ ( self ) -> Optional[Any]: _A : Any = ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224""" ).to(_a ) _A : List[str] = self.default_image_processor _A : int = prepare_img() _A : Union[str, Any] = image_processor(images=_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): _A : Dict = model(**_a ) # verify the logits _A : Optional[Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _a ) _A : Any = torch.tensor([-0.0260, -0.4739, 0.1911] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) ) @require_torch class lowercase ( unittest.TestCase,UpperCamelCase__ ): _a = (ConvNextBackbone,) if is_torch_available() else () _a = ConvNextConfig _a = False def a__ ( self ) -> List[str]: _A : Optional[int] = ConvNextModelTester(self )
343
0
print((lambda quine: quine % quine)("print((lambda quine: quine %% quine)(%r))"))
359
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _snake_case = { "configuration_roc_bert": ["ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoCBertConfig"], "tokenization_roc_bert": ["RoCBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ "ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "RoCBertForCausalLM", "RoCBertForMaskedLM", "RoCBertForMultipleChoice", "RoCBertForPreTraining", "RoCBertForQuestionAnswering", "RoCBertForSequenceClassification", "RoCBertForTokenClassification", "RoCBertLayer", "RoCBertModel", "RoCBertPreTrainedModel", "load_tf_weights_in_roc_bert", ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys _snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
343
0
"""simple docstring""" def lowerCAmelCase_ ( snake_case_,snake_case_ ): # "extended trapezoidal rule" # int(f) = dx/2 * (f1 + 2f2 + ... + fn) _A : Tuple = (boundary[1] - boundary[0]) / steps _A : Optional[Any] = boundary[0] _A : Union[str, Any] = boundary[1] _A : Tuple = make_points(a__,a__,a__ ) _A : Tuple = 0.0 y += (h / 2.0) * f(a__ ) for i in x_i: # print(i) y += h * f(a__ ) y += (h / 2.0) * f(a__ ) return y def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : Any = a + h while x < (b - h): yield x _A : Any = x + h def lowerCAmelCase_ ( snake_case_ ): # enter your function here _A : Dict = (x - 0) * (x - 0) return y def lowerCAmelCase_ ( ): _A : List[Any] = 0.0 # Lower bound of integration _A : Optional[Any] = 1.0 # Upper bound of integration _A : Optional[int] = 10.0 # define number of steps or resolution _A : Optional[int] = [a, b] # define boundary of integration _A : str = method_a(a__,a__ ) print(f'''y = {y}''' ) if __name__ == "__main__": main()
360
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowercase : _a = 42 # setable values _a = 42 _a = 42 _a = None @classmethod def a__ ( cls , _a , _a , _a ) -> Tuple: return cls(common=_a , init_noise_sigma=_a , timesteps=_a ) @dataclass class lowercase ( UpperCamelCase__ ): _a = 42 class lowercase ( UpperCamelCase__,UpperCamelCase__ ): _a = [e.name for e in FlaxKarrasDiffusionSchedulers] _a = 42 @property def a__ ( self ) -> Dict: return True @register_to_config def __init__( self , _a = 1000 , _a = 0.0001 , _a = 0.02 , _a = "linear" , _a = None , _a = "fixed_small" , _a = True , _a = "epsilon" , _a = jnp.floataa , ) -> Tuple: _A : Tuple = dtype def a__ ( self , _a = None ) -> DDPMSchedulerState: if common is None: _A : Dict = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution _A : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) _A : Tuple = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=_a , init_noise_sigma=_a , timesteps=_a , ) def a__ ( self , _a , _a , _a = None ) -> jnp.ndarray: return sample def a__ ( self , _a , _a , _a = () ) -> DDPMSchedulerState: _A : Any = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 _A : Dict = (jnp.arange(0 , _a ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=_a , timesteps=_a , ) def a__ ( self , _a , _a , _a=None , _a=None ) -> Optional[int]: _A : Optional[Any] = state.common.alphas_cumprod[t] _A : int = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample _A : List[str] = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: _A : Optional[Any] = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": _A : Optional[Any] = jnp.clip(_a , a_min=1e-20 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": _A : Any = jnp.log(jnp.clip(_a , a_min=1e-20 ) ) elif variance_type == "fixed_large": _A : Optional[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log _A : Tuple = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": _A : str = variance _A : Union[str, Any] = state.common.betas[t] _A : Tuple = (predicted_variance + 1) / 2 _A : List[str] = frac * max_log + (1 - frac) * min_log return variance def a__ ( self , _a , _a , _a , _a , _a = None , _a = True , ) -> Union[FlaxDDPMSchedulerOutput, Tuple]: _A : Dict = timestep if key is None: _A : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: _A , _A : List[str] = jnp.split(_a , sample.shape[1] , axis=1 ) else: _A : int = None # 1. compute alphas, betas _A : int = state.common.alphas_cumprod[t] _A : List[str] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) _A : Union[str, Any] = 1 - alpha_prod_t _A : Optional[int] = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": _A : Dict = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": _A : Optional[int] = model_output elif self.config.prediction_type == "v_prediction": _A : Any = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' """ for the FlaxDDPMScheduler.""" ) # 3. Clip "predicted x_0" if self.config.clip_sample: _A : Union[str, Any] = jnp.clip(_a , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _A : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t _A : Dict = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _A : int = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): _A : Tuple = jax.random.split(_a , num=1 ) _A : Dict = jax.random.normal(_a , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(_a , _a , predicted_variance=_a ) ** 0.5) * noise _A : int = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) _A : Union[str, Any] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=_a , state=_a ) def a__ ( self , _a , _a , _a , _a , ) -> jnp.ndarray: return add_noise_common(state.common , _a , _a , _a ) def a__ ( self , _a , _a , _a , _a , ) -> jnp.ndarray: return get_velocity_common(state.common , _a , _a , _a ) def __len__( self ) -> List[Any]: return self.config.num_train_timesteps
343
0
import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList _snake_case = ["\nclass", "\ndef", "\n#", "\n@", "\nprint", "\nif"] class lowercase ( __lowercase ): def __init__( self , _a , _a , _a=None , _a=1 ) -> Optional[Any]: _A : List[str] = tokenizer _A : str = dataset _A : List[str] = len(UpperCAmelCase__ ) if n_tasks is None else n_tasks _A : int = n_copies def __iter__( self ) -> Optional[int]: _A : Union[str, Any] = [] for task in range(self.n_tasks ): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]["""prompt"""].strip() ) _A : Any = self.tokenizer(UpperCAmelCase__ , padding=UpperCAmelCase__ , return_tensors="""pt""" ) for task in range(self.n_tasks ): for _ in range(self.n_copies ): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class lowercase ( __lowercase ): def __init__( self , _a , _a , _a ) -> str: _A : Any = start_length _A : int = eof_strings _A : List[Any] = tokenizer def __call__( self , _a , _a , **_a ) -> Union[str, Any]: _A : str = self.tokenizer.batch_decode(input_ids[:, self.start_length :] ) _A : Tuple = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings ) ) return all(UpperCAmelCase__ ) def lowerCAmelCase_ ( snake_case_ ): _A : Optional[int] = re.split("""(%s)""" % """|""".join(snake_case_ ),snake_case_ ) # last string should be "" return "".join(string_list[:-2] ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_,snake_case_=20,**snake_case_ ): _A : Union[str, Any] = defaultdict(snake_case_ ) # dict of list of generated tokens for step, batch in tqdm(enumerate(snake_case_ ) ): with torch.no_grad(): _A : Union[str, Any] = batch["""ids"""].shape[-1] _A : Any = accelerator.unwrap_model(snake_case_ ).generate( input_ids=batch["""ids"""][:, : batch["""input_len"""]],num_return_sequences=snake_case_,**snake_case_ ) # each task is generated batch_size times _A : str = batch["""task_id"""].repeat(snake_case_ ) _A : Union[str, Any] = accelerator.pad_across_processes( snake_case_,dim=1,pad_index=tokenizer.pad_token_id ) _A , _A : Tuple = accelerator.gather((generated_tokens, generated_tasks) ) _A : str = generated_tokens.cpu().numpy() _A : int = generated_tasks.cpu().numpy() for task, generated_tokens in zip(snake_case_,snake_case_ ): gen_token_dict[task].append(snake_case_ ) _A : List[Any] = [[] for _ in range(snake_case_ )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: _A : Optional[int] = tokenizer.decode(snake_case_,skip_special_tokens=snake_case_,clean_up_tokenization_spaces=snake_case_ ) code_gens[task].append(remove_last_block(snake_case_ ) ) return code_gens def lowerCAmelCase_ ( ): # Setup configuration _A : Optional[int] = HfArgumentParser(snake_case_ ) _A : str = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric _A : List[Any] = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing _A : Dict = """false""" if args.num_workers is None: _A : Optional[int] = multiprocessing.cpu_count() # Use dataset load to feed to accelerate _A : Union[str, Any] = Accelerator() set_seed(args.seed,device_specific=snake_case_ ) # Load model and tokenizer _A : str = AutoTokenizer.from_pretrained(args.model_ckpt ) _A : Optional[int] = tokenizer.eos_token _A : Tuple = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings _A : Optional[int] = { """do_sample""": args.do_sample, """temperature""": args.temperature, """max_new_tokens""": args.max_new_tokens, """top_p""": args.top_p, """top_k""": args.top_k, """stopping_criteria""": StoppingCriteriaList([EndOfFunctionCriteria(0,snake_case_,snake_case_ )] ), } # Load evaluation dataset and metric _A : List[str] = load_dataset("""openai_humaneval""" ) _A : Any = load_metric("""code_eval""" ) _A : Optional[Any] = args.num_tasks if args.num_tasks is not None else len(human_eval["""test"""] ) _A : List[str] = args.n_samples // args.batch_size _A : Union[str, Any] = TokenizedDataset(snake_case_,human_eval["""test"""],n_copies=snake_case_,n_tasks=snake_case_ ) # do not confuse args.batch_size, which is actually the num_return_sequences _A : List[Any] = DataLoader(snake_case_,batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: _A : Union[str, Any] = code_eval_metric.compute(references=[""""""],predictions=[[""""""]] ) except ValueError as exception: print( """Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL=\"1\"`""" """ flag to enable code evaluation.""" ) raise exception _A , _A : int = accelerator.prepare(snake_case_,snake_case_ ) _A : List[Any] = complete_code( snake_case_,snake_case_,snake_case_,snake_case_,n_tasks=snake_case_,batch_size=args.batch_size,**snake_case_,) if accelerator.is_main_process: _A : str = [] for task in tqdm(range(snake_case_ ) ): _A : List[Any] = human_eval["""test"""][task]["""test"""] _A : Optional[Any] = f'''check({human_eval["test"][task]["entry_point"]})''' references.append("""\n""" + test_func + """\n""" + entry_point ) # Evaluate completions with "code_eval" metric _A , _A : Union[str, Any] = code_eval_metric.compute( references=snake_case_,predictions=snake_case_,num_workers=args.num_workers ) print(f'''Results: {pass_at_k}''' ) # Save results to json file with open(args.output_file,"""w""" ) as fp: json.dump(snake_case_,snake_case_ ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
361
# Copyright (c) 2021-, NVIDIA CORPORATION. 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. #################################################################################################### # # Note: If when running this conversion script you're getting an exception: # ModuleNotFoundError: No module named 'megatron.model.enums' # you need to tell python where to find the clone of Megatron-LM, e.g.: # # cd /tmp # git clone https://github.com/NVIDIA/Megatron-LM # PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ... # # if you already have it cloned elsewhere, simply adjust the path to the existing path # # If the training was done using a Megatron-LM fork, e.g., # https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one # in your path, i.e., /path/to/Megatron-DeepSpeed/ # import argparse import os import re import zipfile import torch from transformers import AutoTokenizer, GPTaConfig def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_=0 ): # Format the message. if name is None: _A : Union[str, Any] = None else: _A : Dict = """.""" * max(0,spaces - 2 ) + """# {:""" + str(50 - spaces ) + """s}""" _A : Tuple = fmt.format(snake_case_ ) # Print and recurse (if needed). if isinstance(snake_case_,snake_case_ ): if msg is not None: print(snake_case_ ) for k in val.keys(): recursive_print(snake_case_,val[k],spaces + 2 ) elif isinstance(snake_case_,torch.Tensor ): print(snake_case_,""":""",val.size() ) else: print(snake_case_,""":""",snake_case_ ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_ ): # Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :] # for compatibility with later versions of NVIDIA Megatron-LM. # The inverse operation is performed inside Megatron-LM to read checkpoints: # https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209 # If param is the weight tensor of the self-attention block, the returned tensor # will have to be transposed one more time to be read by HuggingFace GPT2. _A : str = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] _A : Union[str, Any] = (num_heads, hidden_size, num_splits) + input_shape[1:] _A : Tuple = param.view(*snake_case_ ) _A : Any = param.transpose(0,2 ) _A : int = param.transpose(1,2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] _A : Optional[Any] = (num_heads, num_splits, hidden_size) + input_shape[1:] _A : int = param.view(*snake_case_ ) _A : Any = param.transpose(0,1 ).contiguous() _A : Optional[int] = param.view(*snake_case_ ) return param def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): # The converted output model. _A : Any = {} # old versions did not store training args _A : str = input_state_dict.get("""args""",snake_case_ ) if ds_args is not None: # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint # from pprint import pprint # pprint(vars(ds_args)) _A : Union[str, Any] = ds_args.padded_vocab_size _A : List[Any] = ds_args.max_position_embeddings _A : Optional[int] = ds_args.hidden_size _A : List[Any] = ds_args.num_layers _A : List[str] = ds_args.num_attention_heads _A : int = ds_args.ffn_hidden_size # pprint(config) # The number of heads. _A : Union[str, Any] = config.n_head # The hidden_size per head. _A : List[Any] = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): _A : Tuple = input_state_dict["""checkpoint_version"""] else: _A : Any = 0.0 # The model. _A : Any = input_state_dict["""model"""] # The language model. _A : Tuple = model["""language_model"""] # The embeddings. _A : Any = lm["""embedding"""] # The word embeddings. _A : Dict = embeddings["""word_embeddings"""]["""weight"""] # Truncate the embedding table to vocab_size rows. _A : Union[str, Any] = word_embeddings[: config.vocab_size, :] _A : Tuple = word_embeddings # The position embeddings. _A : Tuple = embeddings["""position_embeddings"""]["""weight"""] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] _A : Any = pos_embeddings.size(0 ) if n_positions != config.n_positions: raise ValueError( f'''pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don\'t match''' ) # Store the position embeddings. _A : Optional[int] = pos_embeddings # The transformer. _A : Any = lm["""transformer"""] if """transformer""" in lm.keys() else lm["""encoder"""] # The regex to extract layer names. _A : Optional[int] = re.compile(r"""layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)""" ) # The simple map of names for "automated" rules. _A : Union[str, Any] = { """attention.dense""": """.attn.c_proj.""", """self_attention.dense""": """.attn.c_proj.""", """mlp.dense_h_to_4h""": """.mlp.c_fc.""", """mlp.dense_4h_to_h""": """.mlp.c_proj.""", } # Extract the layers. for key, val in transformer.items(): # Match the name. _A : List[str] = layer_re.match(snake_case_ ) # Stop if that's not a layer if m is None: break # The index of the layer. _A : Tuple = int(m.group(1 ) ) # The name of the operation. _A : Optional[Any] = m.group(2 ) # Is it a weight or a bias? _A : Dict = m.group(3 ) # The name of the layer. _A : Optional[Any] = f'''transformer.h.{layer_idx}''' # For layernorm(s), simply store the layer norm. if op_name.endswith("""layernorm""" ): _A : Union[str, Any] = """ln_1""" if op_name.startswith("""input""" ) else """ln_2""" _A : List[str] = val # Transpose the QKV matrix. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "weight": # Insert a tensor of 1x1xDxD bias. _A : List[str] = torch.tril(torch.ones((n_positions, n_positions),dtype=torch.floataa ) ).view( 1,1,snake_case_,snake_case_ ) _A : Any = causal_mask # Insert a "dummy" tensor for masked_bias. _A : List[str] = torch.tensor(-1e4,dtype=torch.floataa ) _A : Tuple = masked_bias _A : Tuple = fix_query_key_value_ordering(snake_case_,snake_case_,3,snake_case_,snake_case_ ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. _A : Tuple = out_val.transpose(0,1 ).contiguous() # Store. _A : Any = out_val # Transpose the bias. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "bias": _A : List[str] = fix_query_key_value_ordering(snake_case_,snake_case_,3,snake_case_,snake_case_ ) # Store. No change of shape. _A : Tuple = out_val # Transpose the weights. elif weight_or_bias == "weight": _A : List[str] = megatron_to_transformers[op_name] _A : Any = val.transpose(0,1 ) # Copy the bias. elif weight_or_bias == "bias": _A : Dict = megatron_to_transformers[op_name] _A : List[Any] = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. _A : Optional[Any] = transformer["""final_layernorm.weight"""] _A : Dict = transformer["""final_layernorm.bias"""] # For LM head, transformers' wants the matrix to weight embeddings. _A : List[str] = word_embeddings # It should be done! return output_state_dict def lowerCAmelCase_ ( ): # Create the argument parser. _A : Any = argparse.ArgumentParser() parser.add_argument("""--print-checkpoint-structure""",action="""store_true""" ) parser.add_argument( """path_to_checkpoint""",type=snake_case_,help="""Path to the checkpoint file (.zip archive or direct .pt file)""",) parser.add_argument( """--config_file""",default="""""",type=snake_case_,help="""An optional config json file describing the pre-trained model.""",) _A : Optional[int] = parser.parse_args() # Extract the basename. _A : Any = os.path.dirname(args.path_to_checkpoint ) # Load the model. # the .zip is very optional, let's keep it for backward compatibility print(f'''Extracting PyTorch state dictionary from {args.path_to_checkpoint}''' ) if args.path_to_checkpoint.endswith(""".zip""" ): with zipfile.ZipFile(args.path_to_checkpoint,"""r""" ) as checkpoint: with checkpoint.open("""release/mp_rank_00/model_optim_rng.pt""" ) as pytorch_dict: _A : Tuple = torch.load(snake_case_,map_location="""cpu""" ) else: _A : Tuple = torch.load(args.path_to_checkpoint,map_location="""cpu""" ) _A : Optional[Any] = input_state_dict.get("""args""",snake_case_ ) # Read the config, or default to the model released by NVIDIA. if args.config_file == "": if ds_args is not None: if ds_args.bias_gelu_fusion: _A : Union[str, Any] = """gelu_fast""" elif ds_args.openai_gelu: _A : int = """gelu_new""" else: _A : Optional[Any] = """gelu""" else: # in the very early days this used to be "gelu_new" _A : Any = """gelu_new""" # Spell out all parameters in case the defaults change. _A : Any = GPTaConfig( vocab_size=50257,n_positions=1024,n_embd=1024,n_layer=24,n_head=16,n_inner=4096,activation_function=snake_case_,resid_pdrop=0.1,embd_pdrop=0.1,attn_pdrop=0.1,layer_norm_epsilon=1e-5,initializer_range=0.02,summary_type="""cls_index""",summary_use_proj=snake_case_,summary_activation=snake_case_,summary_proj_to_labels=snake_case_,summary_first_dropout=0.1,scale_attn_weights=snake_case_,use_cache=snake_case_,bos_token_id=50256,eos_token_id=50256,) else: _A : Union[str, Any] = GPTaConfig.from_json_file(args.config_file ) _A : List[str] = ["""GPT2LMHeadModel"""] # Convert. print("""Converting""" ) _A : Optional[Any] = convert_megatron_checkpoint(snake_case_,snake_case_,snake_case_ ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(snake_case_,snake_case_ ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: _A : int = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": _A : Any = """gpt2""" elif tokenizer_type == "PretrainedFromHF": _A : List[Any] = ds_args.tokenizer_name_or_path else: raise ValueError(f'''Unrecognized tokenizer_type {tokenizer_type}''' ) else: _A : Optional[Any] = """gpt2""" _A : List[str] = AutoTokenizer.from_pretrained(snake_case_ ) _A : Tuple = type(snake_case_ ).__name__ _A : Union[str, Any] = tokenizer_class # Store the config to file. print("""Saving config""" ) config.save_pretrained(snake_case_ ) # Save tokenizer based on args print(f'''Adding {tokenizer_class} tokenizer files''' ) tokenizer.save_pretrained(snake_case_ ) # Store the state_dict to file. _A : Union[str, Any] = os.path.join(snake_case_,"""pytorch_model.bin""" ) print(f'''Saving checkpoint to "{output_checkpoint_file}"''' ) torch.save(snake_case_,snake_case_ ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
343
0
def lowerCAmelCase_ ( snake_case_,snake_case_ ): if not isinstance(__lowerCAmelCase,__lowerCAmelCase ): raise ValueError("""iterations must be defined as integers""" ) if not isinstance(__lowerCAmelCase,__lowerCAmelCase ) or not number >= 1: raise ValueError( """starting number must be and integer and be more than 0""" ) if not iterations >= 1: raise ValueError("""Iterations must be done more than 0 times to play FizzBuzz""" ) _A : Tuple = """""" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(__lowerCAmelCase ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
362
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer _snake_case = logging.get_logger(__name__) _snake_case = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _snake_case = { "vocab_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } _snake_case = { "vocab_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } _snake_case = { "vocab_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json" ), }, } _snake_case = { "facebook/dpr-ctx_encoder-single-nq-base": 512, "facebook/dpr-ctx_encoder-multiset-base": 512, } _snake_case = { "facebook/dpr-question_encoder-single-nq-base": 512, "facebook/dpr-question_encoder-multiset-base": 512, } _snake_case = { "facebook/dpr-reader-single-nq-base": 512, "facebook/dpr-reader-multiset-base": 512, } _snake_case = { "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True}, } _snake_case = { "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True}, } _snake_case = { "facebook/dpr-reader-single-nq-base": {"do_lower_case": True}, "facebook/dpr-reader-multiset-base": {"do_lower_case": True}, } class lowercase ( UpperCamelCase__ ): _a = VOCAB_FILES_NAMES _a = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _a = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION class lowercase ( UpperCamelCase__ ): _a = VOCAB_FILES_NAMES _a = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _a = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION _snake_case = collections.namedtuple( "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"] ) _snake_case = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"]) _snake_case = r"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n ```\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n ```\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Returns:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n " @add_start_docstrings(UpperCamelCase__ ) class lowercase : def __call__( self , _a , _a = None , _a = None , _a = False , _a = False , _a = None , _a = None , _a = None , **_a , ) -> BatchEncoding: if titles is None and texts is None: return super().__call__( _a , padding=_a , truncation=_a , max_length=_a , return_tensors=_a , return_attention_mask=_a , **_a , ) elif titles is None or texts is None: _A : Optional[Any] = titles if texts is None else texts return super().__call__( _a , _a , padding=_a , truncation=_a , max_length=_a , return_tensors=_a , return_attention_mask=_a , **_a , ) _A : Dict = titles if not isinstance(_a , _a ) else [titles] _A : Tuple = texts if not isinstance(_a , _a ) else [texts] _A : Any = len(_a ) _A : Optional[Any] = questions if not isinstance(_a , _a ) else [questions] * n_passages if len(_a ) != len(_a ): raise ValueError( F'''There should be as many titles than texts but got {len(_a )} titles and {len(_a )} texts.''' ) _A : str = super().__call__(_a , _a , padding=_a , truncation=_a )["""input_ids"""] _A : Optional[int] = super().__call__(_a , add_special_tokens=_a , padding=_a , truncation=_a )["""input_ids"""] _A : Optional[int] = { """input_ids""": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_a , _a ) ] } if return_attention_mask is not False: _A : Any = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) _A : str = attention_mask return self.pad(_a , padding=_a , max_length=_a , return_tensors=_a ) def a__ ( self , _a , _a , _a = 16 , _a = 64 , _a = 4 , ) -> List[DPRSpanPrediction]: _A : Dict = reader_input["""input_ids"""] _A , _A , _A : Tuple = reader_output[:3] _A : List[str] = len(_a ) _A : Tuple = sorted(range(_a ) , reverse=_a , key=relevance_logits.__getitem__ ) _A : List[DPRReaderOutput] = [] for doc_id in sorted_docs: _A : Tuple = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence _A : int = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: _A : Tuple = sequence_ids.index(self.pad_token_id ) else: _A : Tuple = len(_a ) _A : Union[str, Any] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_a , top_spans=_a , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_a , start_index=_a , end_index=_a , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_a ) >= num_spans: break return nbest_spans_predictions[:num_spans] def a__ ( self , _a , _a , _a , _a , ) -> List[DPRSpanPrediction]: _A : Tuple = [] for start_index, start_score in enumerate(_a ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) _A : Tuple = sorted(_a , key=lambda _a : x[1] , reverse=_a ) _A : Union[str, Any] = [] for (start_index, end_index), score in scores: if start_index > end_index: raise ValueError(F'''Wrong span indices: [{start_index}:{end_index}]''' ) _A : Dict = end_index - start_index + 1 if length > max_answer_length: raise ValueError(F'''Span is too long: {length} > {max_answer_length}''' ) if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_a ) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCamelCase__ ) class lowercase ( UpperCamelCase__,UpperCamelCase__ ): _a = VOCAB_FILES_NAMES _a = READER_PRETRAINED_VOCAB_FILES_MAP _a = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = READER_PRETRAINED_INIT_CONFIGURATION _a = ["input_ids", "attention_mask"]
343
0
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class lowercase ( unittest.TestCase ): @require_torch def a__ ( self ) -> Tuple: _A : Dict = pipeline( task="""zero-shot-audio-classification""" , model="""hf-internal-testing/tiny-clap-htsat-unfused""" ) _A : Optional[Any] = load_dataset("""ashraq/esc50""" ) _A : int = dataset["""train"""]["""audio"""][-1]["""array"""] _A : List[Any] = audio_classifier(__SCREAMING_SNAKE_CASE , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [{"""score""": 0.501, """label""": """Sound of a dog"""}, {"""score""": 0.499, """label""": """Sound of vaccum cleaner"""}] , ) @unittest.skip("""No models are available in TF""" ) def a__ ( self ) -> Tuple: pass @slow @require_torch def a__ ( self ) -> Dict: _A : List[Any] = pipeline( task="""zero-shot-audio-classification""" , model="""laion/clap-htsat-unfused""" , ) # This is an audio of a dog _A : int = load_dataset("""ashraq/esc50""" ) _A : int = dataset["""train"""]["""audio"""][-1]["""array"""] _A : Dict = audio_classifier(__SCREAMING_SNAKE_CASE , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ {"""score""": 0.999, """label""": """Sound of a dog"""}, {"""score""": 0.001, """label""": """Sound of vaccum cleaner"""}, ] , ) _A : List[Any] = audio_classifier([audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ [ {"""score""": 0.999, """label""": """Sound of a dog"""}, {"""score""": 0.001, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) _A : Optional[Any] = audio_classifier( [audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] , batch_size=5 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ [ {"""score""": 0.999, """label""": """Sound of a dog"""}, {"""score""": 0.001, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) @unittest.skip("""No models are available in TF""" ) def a__ ( self ) -> Tuple: pass
363
import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class lowercase ( unittest.TestCase ): @property def a__ ( self ) -> Dict: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def a__ ( self ) -> List[Any]: _A : int = ort.SessionOptions() _A : Any = False return options def a__ ( self ) -> Union[str, Any]: _A : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) _A : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) _A : List[str] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy""" ) # using the PNDM scheduler by default _A : str = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=_a , feature_extractor=_a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_a ) _A : Optional[Any] = """A red cat sitting on a park bench""" _A : Optional[Any] = np.random.RandomState(0 ) _A : Dict = pipe( prompt=_a , image=_a , mask_image=_a , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=_a , output_type="""np""" , ) _A : Optional[int] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1e-2
343
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _snake_case = { 'configuration_cpmant': ['CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CpmAntConfig'], 'tokenization_cpmant': ['CpmAntTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ 'CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST', 'CpmAntForCausalLM', 'CpmAntModel', 'CpmAntPreTrainedModel', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys _snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
364
from __future__ import annotations def lowerCAmelCase_ ( snake_case_ ): create_state_space_tree(snake_case_,[],0,[0 for i in range(len(snake_case_ ) )] ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,): if index == len(snake_case_ ): print(snake_case_ ) return for i in range(len(snake_case_ ) ): if not index_used[i]: current_sequence.append(sequence[i] ) _A : Optional[Any] = True create_state_space_tree(snake_case_,snake_case_,index + 1,snake_case_ ) current_sequence.pop() _A : str = False _snake_case = [3, 1, 2, 4] generate_all_permutations(sequence) _snake_case = ["A", "B", "C"] generate_all_permutations(sequence_a)
343
0
"""simple docstring""" import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets _snake_case = "\n@inproceedings{xu-etal-2016-optimizing,\n title = {Optimizing Statistical Machine Translation for Text Simplification},\n authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris},\n journal = {Transactions of the Association for Computational Linguistics},\n volume = {4},\n year={2016},\n url = {https://www.aclweb.org/anthology/Q16-1029},\n pages = {401--415\n},\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" _snake_case = "\\nWIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU\nIt can be used to evaluate the quality of machine-generated texts.\n" _snake_case = "\nCalculates sari score (between 0 and 100) given a list of source and predicted\nsentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.\nArgs:\n sources: list of source sentences where each sentence should be a string.\n predictions: list of predicted sentences where each sentence should be a string.\n references: list of lists of reference sentences where each sentence should be a string.\nReturns:\n sari: sari score\n sacrebleu: sacrebleu score\n exact: exact score\n\nExamples:\n >>> sources=[\"About 95 species are currently accepted .\"]\n >>> predictions=[\"About 95 you now get in .\"]\n >>> references=[[\"About 95 species are currently known .\"]]\n >>> wiki_split = datasets.load_metric(\"wiki_split\")\n >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)\n >>> print(results)\n {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0}\n" def lowerCAmelCase_ ( snake_case_ ): def remove_articles(snake_case_ ): _A : Union[str, Any] = re.compile(r"""\b(a|an|the)\b""",re.UNICODE ) return re.sub(_a,""" """,_a ) def white_space_fix(snake_case_ ): return " ".join(text.split() ) def remove_punc(snake_case_ ): _A : List[str] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(snake_case_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_a ) ) ) ) def lowerCAmelCase_ ( snake_case_,snake_case_ ): return int(normalize_answer(_a ) == normalize_answer(_a ) ) def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : Any = [any(compute_exact(_a,_a ) for ref in refs ) for pred, refs in zip(_a,_a )] return (sum(_a ) / len(_a )) * 100 def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_ ): _A : int = [rgram for rgrams in rgramslist for rgram in rgrams] _A : List[str] = Counter(_a ) _A : Tuple = Counter(_a ) _A : Any = Counter() for sgram, scount in sgramcounter.items(): _A : List[str] = scount * numref _A : List[str] = Counter(_a ) _A : List[Any] = Counter() for cgram, ccount in cgramcounter.items(): _A : Optional[int] = ccount * numref # KEEP _A : int = sgramcounter_rep & cgramcounter_rep _A : Tuple = keepgramcounter_rep & rgramcounter _A : Optional[int] = sgramcounter_rep & rgramcounter _A : Tuple = 0 _A : List[Any] = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. _A : Optional[Any] = 1 _A : Union[str, Any] = 1 if len(_a ) > 0: _A : List[Any] = keeptmpscorea / len(_a ) if len(_a ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) _A : str = keeptmpscorea / sum(keepgramcounterall_rep.values() ) _A : List[Any] = 0 if keepscore_precision > 0 or keepscore_recall > 0: _A : int = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION _A : List[str] = sgramcounter_rep - cgramcounter_rep _A : Optional[int] = delgramcounter_rep - rgramcounter _A : int = sgramcounter_rep - rgramcounter _A : List[Any] = 0 _A : Any = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. _A : int = 1 if len(_a ) > 0: _A : Union[str, Any] = deltmpscorea / len(_a ) # ADDITION _A : Optional[int] = set(_a ) - set(_a ) _A : Dict = set(_a ) & set(_a ) _A : str = set(_a ) - set(_a ) _A : List[Any] = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. _A : int = 1 _A : Optional[Any] = 1 if len(_a ) > 0: _A : Any = addtmpscore / len(_a ) if len(_a ) > 0: _A : Union[str, Any] = addtmpscore / len(_a ) _A : Tuple = 0 if addscore_precision > 0 or addscore_recall > 0: _A : Dict = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : Optional[Any] = len(_a ) _A : Optional[int] = ssent.split(""" """ ) _A : Any = csent.split(""" """ ) _A : Optional[Any] = [] _A : List[str] = [] _A : Union[str, Any] = [] _A : int = [] _A : Dict = [] _A : Any = [] _A : List[str] = [] _A : int = [] _A : Dict = [] _A : str = [] for rsent in rsents: _A : int = rsent.split(""" """ ) _A : Optional[int] = [] _A : int = [] _A : Optional[int] = [] ragramslist.append(_a ) for i in range(0,len(_a ) - 1 ): if i < len(_a ) - 1: _A : Any = ragrams[i] + """ """ + ragrams[i + 1] ragrams.append(_a ) if i < len(_a ) - 2: _A : Any = ragrams[i] + """ """ + ragrams[i + 1] + """ """ + ragrams[i + 2] ragrams.append(_a ) if i < len(_a ) - 3: _A : Dict = ragrams[i] + """ """ + ragrams[i + 1] + """ """ + ragrams[i + 2] + """ """ + ragrams[i + 3] ragrams.append(_a ) ragramslist.append(_a ) ragramslist.append(_a ) ragramslist.append(_a ) for i in range(0,len(_a ) - 1 ): if i < len(_a ) - 1: _A : Any = sagrams[i] + """ """ + sagrams[i + 1] sagrams.append(_a ) if i < len(_a ) - 2: _A : List[str] = sagrams[i] + """ """ + sagrams[i + 1] + """ """ + sagrams[i + 2] sagrams.append(_a ) if i < len(_a ) - 3: _A : List[Any] = sagrams[i] + """ """ + sagrams[i + 1] + """ """ + sagrams[i + 2] + """ """ + sagrams[i + 3] sagrams.append(_a ) for i in range(0,len(_a ) - 1 ): if i < len(_a ) - 1: _A : str = cagrams[i] + """ """ + cagrams[i + 1] cagrams.append(_a ) if i < len(_a ) - 2: _A : int = cagrams[i] + """ """ + cagrams[i + 1] + """ """ + cagrams[i + 2] cagrams.append(_a ) if i < len(_a ) - 3: _A : str = cagrams[i] + """ """ + cagrams[i + 1] + """ """ + cagrams[i + 2] + """ """ + cagrams[i + 3] cagrams.append(_a ) (_A) : Optional[Any] = SARIngram(_a,_a,_a,_a ) (_A) : str = SARIngram(_a,_a,_a,_a ) (_A) : str = SARIngram(_a,_a,_a,_a ) (_A) : Any = SARIngram(_a,_a,_a,_a ) _A : int = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 _A : Dict = sum([delascore, delascore, delascore, delascore] ) / 4 _A : Tuple = sum([addascore, addascore, addascore, addascore] ) / 4 _A : str = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def lowerCAmelCase_ ( snake_case_,snake_case_ = True,snake_case_ = "13a",snake_case_ = True ): if lowercase: _A : Optional[Any] = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: _A : Optional[int] = sacrebleu.metrics.bleu._get_tokenizer(_a )()(_a ) else: _A : Any = sacrebleu.TOKENIZERS[tokenizer]()(_a ) elif tokenizer == "moses": _A : int = sacremoses.MosesTokenizer().tokenize(_a,return_str=_a,escape=_a ) elif tokenizer == "penn": _A : Union[str, Any] = sacremoses.MosesTokenizer().penn_tokenize(_a,return_str=_a ) else: _A : int = sentence if not return_str: _A : List[str] = normalized_sent.split() return normalized_sent def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): if not (len(_a ) == len(_a ) == len(_a )): raise ValueError("""Sources length must match predictions and references lengths.""" ) _A : Optional[int] = 0 for src, pred, refs in zip(_a,_a,_a ): sari_score += SARIsent(normalize(_a ),normalize(_a ),[normalize(_a ) for sent in refs] ) _A : List[Any] = sari_score / len(_a ) return 100 * sari_score def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_="exp",snake_case_=None,snake_case_=False,snake_case_=False,snake_case_=False,): _A : List[str] = len(references[0] ) if any(len(_a ) != references_per_prediction for refs in references ): raise ValueError("""Sacrebleu requires the same number of references for each prediction""" ) _A : Optional[Any] = [[refs[i] for refs in references] for i in range(_a )] _A : str = sacrebleu.corpus_bleu( _a,_a,smooth_method=_a,smooth_value=_a,force=_a,lowercase=_a,use_effective_order=_a,) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,_KWARGS_DESCRIPTION ) class lowercase ( datasets.Metric ): def a__ ( self ) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Sequence(datasets.Value("""string""" , id="""sequence""" ) , id="""references""" ), } ) , codebase_urls=[ """https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py""", """https://github.com/cocoxu/simplification/blob/master/SARI.py""", """https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py""", """https://github.com/mjpost/sacreBLEU""", ] , reference_urls=[ """https://www.aclweb.org/anthology/Q16-1029.pdf""", """https://github.com/mjpost/sacreBLEU""", """https://en.wikipedia.org/wiki/BLEU""", """https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213""", ] , ) def a__ ( self , _a , _a , _a ) -> List[str]: _A : str = {} result.update({"""sari""": compute_sari(sources=lowerCamelCase_ , predictions=lowerCamelCase_ , references=lowerCamelCase_ )} ) result.update({"""sacrebleu""": compute_sacrebleu(predictions=lowerCamelCase_ , references=lowerCamelCase_ )} ) result.update({"""exact""": compute_em(predictions=lowerCamelCase_ , references=lowerCamelCase_ )} ) return result
365
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def lowerCAmelCase_ ( snake_case_ ): _A : Tuple = filter(lambda snake_case_ : p.requires_grad,model.parameters() ) _A : str = sum([np.prod(p.size() ) for p in model_parameters] ) return params _snake_case = logging.getLogger(__name__) def lowerCAmelCase_ ( snake_case_,snake_case_ ): if metric == "rouge2": _A : Optional[int] = """{val_avg_rouge2:.4f}-{step_count}""" elif metric == "bleu": _A : Dict = """{val_avg_bleu:.4f}-{step_count}""" elif metric == "em": _A : List[str] = """{val_avg_em:.4f}-{step_count}""" else: raise NotImplementedError( f'''seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this''' """ function.""" ) _A : Optional[int] = ModelCheckpoint( dirpath=snake_case_,filename=snake_case_,monitor=f'''val_{metric}''',mode="""max""",save_top_k=3,every_n_epochs=1,) return checkpoint_callback def lowerCAmelCase_ ( snake_case_,snake_case_ ): return EarlyStopping( monitor=f'''val_{metric}''',mode="""min""" if """loss""" in metric else """max""",patience=snake_case_,verbose=snake_case_,) class lowercase ( pl.Callback ): def a__ ( self , _a , _a ) -> Optional[Any]: _A : List[Any] = {F'''lr_group_{i}''': param["""lr"""] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(_a ) @rank_zero_only def a__ ( self , _a , _a , _a , _a=True ) -> None: logger.info(F'''***** {type_path} results at step {trainer.global_step:05d} *****''' ) _A : int = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["""log""", """progress_bar""", """preds"""]} ) # Log results _A : Dict = Path(pl_module.hparams.output_dir ) if type_path == "test": _A : List[Any] = od / """test_results.txt""" _A : List[Any] = od / """test_generations.txt""" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _A : Optional[int] = od / F'''{type_path}_results/{trainer.global_step:05d}.txt''' _A : int = od / F'''{type_path}_generations/{trainer.global_step:05d}.txt''' results_file.parent.mkdir(exist_ok=_a ) generations_file.parent.mkdir(exist_ok=_a ) with open(_a , """a+""" ) as writer: for key in sorted(_a ): if key in ["log", "progress_bar", "preds"]: continue _A : List[Any] = metrics[key] if isinstance(_a , torch.Tensor ): _A : str = val.item() _A : str = F'''{key}: {val:.6f}\n''' writer.write(_a ) if not save_generations: return if "preds" in metrics: _A : List[Any] = """\n""".join(metrics["""preds"""] ) generations_file.open("""w+""" ).write(_a ) @rank_zero_only def a__ ( self , _a , _a ) -> str: try: _A : int = pl_module.model.model.num_parameters() except AttributeError: _A : str = pl_module.model.num_parameters() _A : Optional[int] = count_trainable_parameters(_a ) # mp stands for million parameters trainer.logger.log_metrics({"""n_params""": npars, """mp""": npars / 1e6, """grad_mp""": n_trainable_pars / 1e6} ) @rank_zero_only def a__ ( self , _a , _a ) -> Optional[int]: save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_a , _a , """test""" ) @rank_zero_only def a__ ( self , _a , _a ) -> Tuple: save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
343
0
import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json _snake_case = """sshleifer/mar_enro_6_3_student""" class lowercase ( UpperCamelCase__ ): def a__ ( self ) -> Tuple: super().setUp() _A : Any = cached_path( """https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz""" , extract_compressed_file=_lowercase , ) _A : int = F'''{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k''' @slow @require_torch_gpu def a__ ( self ) -> List[Any]: MarianMTModel.from_pretrained(_lowercase ) @slow @require_torch_gpu def a__ ( self ) -> int: _A : List[Any] = { """$MAX_LEN""": 64, """$BS""": 64, """$GAS""": 1, """$ENRO_DIR""": self.data_dir, """facebook/mbart-large-cc25""": MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", """--learning_rate=3e-5""": """--learning_rate 3e-4""", """--num_train_epochs 6""": """--num_train_epochs 1""", } # Clean up bash script _A : List[Any] = (self.test_file_dir / """train_mbart_cc25_enro.sh""").open().read().split("""finetune.py""" )[1].strip() _A : str = bash_script.replace("""\\\n""" , """""" ).strip().replace("""\"$@\"""" , """""" ) for k, v in env_vars_to_replace.items(): _A : str = bash_script.replace(_lowercase , str(_lowercase ) ) _A : Dict = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") _A : str = F'''\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n '''.split() # XXX: args.gpus > 1 : handle multi_gpu in the future _A : Tuple = ["""finetune.py"""] + bash_script.split() + args with patch.object(_lowercase , """argv""" , _lowercase ): _A : Dict = argparse.ArgumentParser() _A : str = pl.Trainer.add_argparse_args(_lowercase ) _A : Optional[int] = SummarizationModule.add_model_specific_args(_lowercase , os.getcwd() ) _A : List[str] = parser.parse_args() _A : str = main(_lowercase ) # Check metrics _A : Tuple = load_json(model.metrics_save_path ) _A : Tuple = metrics["""val"""][0] _A : int = metrics["""val"""][-1] self.assertEqual(len(metrics["""val"""] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[F'''val_avg_{model.val_metric}'''] , _lowercase ) self.assertGreater(last_step_stats["""val_avg_gen_time"""] , 0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats["""val_avg_gen_time"""] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats["""val_avg_bleu"""] - first_step_stats["""val_avg_bleu"""] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats["""val_avg_bleu"""] , 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics["""val"""][-1]["""val_avg_bleu"""] - metrics["""test"""][-1]["""test_avg_bleu"""] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict _A : List[str] = os.listdir(_lowercase ) _A : str = [x for x in contents if x.endswith(""".ckpt""" )][0] _A : Union[str, Any] = os.path.join(args.output_dir , _lowercase ) _A : Union[str, Any] = torch.load(_lowercase , map_location="""cpu""" ) _A : Optional[Any] = """model.model.decoder.layers.0.encoder_attn_layer_norm.weight""" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: _A : Optional[int] = {os.path.basename(_lowercase ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["""test"""] ) == 1 class lowercase ( UpperCamelCase__ ): @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def a__ ( self ) -> Optional[int]: _A : List[Any] = F'''{self.test_file_dir_str}/test_data/wmt_en_ro''' _A : List[Any] = { """--fp16_opt_level=O1""": """""", """$MAX_LEN""": 128, """$BS""": 16, """$GAS""": 1, """$ENRO_DIR""": data_dir, """$m""": """sshleifer/student_marian_en_ro_6_1""", """val_check_interval=0.25""": """val_check_interval=1.0""", } # Clean up bash script _A : int = ( (self.test_file_dir / """distil_marian_no_teacher.sh""").open().read().split("""distillation.py""" )[1].strip() ) _A : Optional[int] = bash_script.replace("""\\\n""" , """""" ).strip().replace("""\"$@\"""" , """""" ) _A : List[str] = bash_script.replace("""--fp16 """ , """ """ ) for k, v in env_vars_to_replace.items(): _A : Any = bash_script.replace(_lowercase , str(_lowercase ) ) _A : Dict = self.get_auto_remove_tmp_dir() _A : str = bash_script.replace("""--fp16""" , """""" ) _A : str = 6 _A : Optional[Any] = ( ["""distillation.py"""] + bash_script.split() + [ F'''--output_dir={output_dir}''', """--gpus=1""", """--learning_rate=1e-3""", F'''--num_train_epochs={epochs}''', """--warmup_steps=10""", """--val_check_interval=1.0""", """--do_predict""", ] ) with patch.object(_lowercase , """argv""" , _lowercase ): _A : Optional[int] = argparse.ArgumentParser() _A : Union[str, Any] = pl.Trainer.add_argparse_args(_lowercase ) _A : Optional[int] = SummarizationDistiller.add_model_specific_args(_lowercase , os.getcwd() ) _A : Dict = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu _A : Tuple = distill_main(_lowercase ) # Check metrics _A : Optional[int] = load_json(model.metrics_save_path ) _A : Optional[Any] = metrics["""val"""][0] _A : Dict = metrics["""val"""][-1] assert len(metrics["""val"""] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[F'''val_avg_{model.val_metric}'''] , _lowercase ) # check lightning ckpt can be loaded and has a reasonable statedict _A : int = os.listdir(_lowercase ) _A : List[str] = [x for x in contents if x.endswith(""".ckpt""" )][0] _A : Tuple = os.path.join(args.output_dir , _lowercase ) _A : int = torch.load(_lowercase , map_location="""cpu""" ) _A : Union[str, Any] = """model.model.decoder.layers.0.encoder_attn_layer_norm.weight""" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: _A : Tuple = {os.path.basename(_lowercase ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["""test"""] ) == 1
366
from __future__ import annotations from collections.abc import Callable _snake_case = list[list[float | int]] def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : int = len(snake_case_ ) _A : Matrix = [[0 for _ in range(size + 1 )] for _ in range(snake_case_ )] _A : int _A : int _A : int _A : int _A : int _A : float for row in range(snake_case_ ): for col in range(snake_case_ ): _A : Dict = matrix[row][col] _A : List[Any] = vector[row][0] _A : List[Any] = 0 _A : Optional[Any] = 0 while row < size and col < size: # pivoting _A : Any = max((abs(augmented[rowa][col] ), rowa) for rowa in range(snake_case_,snake_case_ ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: _A , _A : Optional[Any] = augmented[pivot_row], augmented[row] for rowa in range(row + 1,snake_case_ ): _A : str = augmented[rowa][col] / augmented[row][col] _A : List[Any] = 0 for cola in range(col + 1,size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1,snake_case_ ): for row in range(snake_case_ ): _A : int = augmented[row][col] / augmented[col][col] for cola in range(snake_case_,size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row],10 )] for row in range(snake_case_ ) ] def lowerCAmelCase_ ( snake_case_ ): _A : int = len(snake_case_ ) _A : Matrix = [[0 for _ in range(snake_case_ )] for _ in range(snake_case_ )] _A : Matrix = [[0] for _ in range(snake_case_ )] _A : Matrix _A : int _A : int _A : int for x_val, y_val in enumerate(snake_case_ ): for col in range(snake_case_ ): _A : str = (x_val + 1) ** (size - col - 1) _A : List[str] = y_val _A : Any = solve(snake_case_,snake_case_ ) def interpolated_func(snake_case_ ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(snake_case_ ) ) return interpolated_func def lowerCAmelCase_ ( snake_case_ ): return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def lowerCAmelCase_ ( snake_case_ = question_function,snake_case_ = 10 ): _A : list[int] = [func(snake_case_ ) for x_val in range(1,order + 1 )] _A : list[Callable[[int], int]] = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1,order + 1 ) ] _A : int = 0 _A : Callable[[int], int] _A : int for poly in polynomials: _A : Optional[int] = 1 while func(snake_case_ ) == poly(snake_case_ ): x_val += 1 ret += poly(snake_case_ ) return ret if __name__ == "__main__": print(f"""{solution() = }""")
343
0
def lowerCAmelCase_ ( snake_case_ ): _A : Optional[Any] = int(SCREAMING_SNAKE_CASE__ ) if n_element < 1: _A : Optional[int] = ValueError("""a should be a positive number""" ) raise my_error _A : Optional[Any] = [1] _A , _A , _A : List[str] = (0, 0, 0) _A : Dict = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2,hamming_list[j] * 3,hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": _snake_case = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") _snake_case = hamming(int(n)) print("-----------------------------------------------------") print(f"""The list with nth numbers is: {hamming_numbers}""") print("-----------------------------------------------------")
367
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup _snake_case = "https://www.indeed.co.in/jobs?q=mobile+app+development&l=" def lowerCAmelCase_ ( snake_case_ = "mumbai" ): _A : Optional[Any] = BeautifulSoup(requests.get(url + location ).content,"""html.parser""" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("""div""",attrs={"""data-tn-component""": """organicJob"""} ): _A : Tuple = job.find("""a""",attrs={"""data-tn-element""": """jobTitle"""} ).text.strip() _A : Optional[int] = job.find("""span""",{"""class""": """company"""} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs("Bangalore"), 1): print(f"""Job {i:>2} is {job[0]} at {job[1]}""")
343
0
import doctest from collections import deque import numpy as np class lowercase : def __init__( self ) -> Optional[Any]: _A : Optional[int] = [2, 1, 2, -1] _A : List[str] = [1, 2, 3, 4] def a__ ( self ) -> Dict: _A : int = len(self.first_signal ) _A : Tuple = len(self.second_signal ) _A : Union[str, Any] = max(__lowerCamelCase , __lowerCamelCase ) # create a zero matrix of max_length x max_length _A : Tuple = [[0] * max_length for i in range(__lowerCamelCase )] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(__lowerCamelCase ): _A : List[Any] = deque(self.second_signal ) rotated_signal.rotate(__lowerCamelCase ) for j, item in enumerate(__lowerCamelCase ): matrix[i][j] += item # multiply the matrix with the first signal _A : Any = np.matmul(np.transpose(__lowerCamelCase ) , np.transpose(self.first_signal ) ) # rounding-off to two decimal places return [round(__lowerCamelCase , 2 ) for i in final_signal] if __name__ == "__main__": doctest.testmod()
368
from __future__ import annotations from decimal import Decimal from numpy import array def lowerCAmelCase_ ( snake_case_ ): _A : Tuple = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(snake_case_ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix _A : List[Any] = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creates a copy of the matrix with swapped positions of the elements _A : Tuple = [[0.0, 0.0], [0.0, 0.0]] _A , _A : List[str] = matrix[1][1], matrix[0][0] _A , _A : List[str] = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(snake_case_ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(snake_case_ ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule _A : List[str] = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creating cofactor matrix _A : List[Any] = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] _A : Union[str, Any] = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) _A : Optional[Any] = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) _A : Any = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) _A : List[Any] = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) _A : int = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) _A : Union[str, Any] = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) _A : Any = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) _A : List[str] = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) _A : Optional[int] = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) _A : List[Any] = array(snake_case_ ) for i in range(3 ): for j in range(3 ): _A : List[str] = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix _A : Union[str, Any] = array(snake_case_ ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(snake_case_ ) # Calculate the inverse of the matrix return [[float(d(snake_case_ ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError("""Please provide a matrix of size 2x2 or 3x3.""" )
343
0
"""simple docstring""" from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class lowercase : _a = 4_2 _a = None _a = None def lowerCAmelCase_ ( ): _A : Any = Node(1 ) _A : List[str] = Node(2 ) _A : int = Node(3 ) _A : List[Any] = Node(4 ) _A : int = Node(5 ) return tree def lowerCAmelCase_ ( snake_case_ ): return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def lowerCAmelCase_ ( snake_case_ ): return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def lowerCAmelCase_ ( snake_case_ ): return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def lowerCAmelCase_ ( snake_case_ ): return (max(height(root.left ),height(root.right ) ) + 1) if root else 0 def lowerCAmelCase_ ( snake_case_ ): _A : Any = [] if root is None: return output _A : Any = deque([root] ) while process_queue: _A : List[Any] = process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : int = [] def populate_output(snake_case_,snake_case_ ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left,level - 1 ) populate_output(root.right,level - 1 ) populate_output(a__,a__ ) return output def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : int = [] def populate_output(snake_case_,snake_case_ ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right,level - 1 ) populate_output(root.left,level - 1 ) populate_output(a__,a__ ) return output def lowerCAmelCase_ ( snake_case_ ): if root is None: return [] _A : Tuple = [] _A : Tuple = 0 _A : Union[str, Any] = height(a__ ) for h in range(1,height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(a__,a__ ) ) _A : Tuple = 1 else: output.append(get_nodes_from_right_to_left(a__,a__ ) ) _A : str = 0 return output def lowerCAmelCase_ ( ): # Main function for testing. _A : List[str] = make_tree() print(f'''In-order Traversal: {inorder(a__ )}''' ) print(f'''Pre-order Traversal: {preorder(a__ )}''' ) print(f'''Post-order Traversal: {postorder(a__ )}''',"""\n""" ) print(f'''Height of Tree: {height(a__ )}''',"""\n""" ) print("""Complete Level Order Traversal: """ ) print(level_order(a__ ),"""\n""" ) print("""Level-wise order Traversal: """ ) for level in range(1,height(a__ ) + 1 ): print(f'''Level {level}:''',get_nodes_from_left_to_right(a__,level=a__ ) ) print("""\nZigZag order Traversal: """ ) print(zigzag(a__ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
369
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class lowercase ( UpperCamelCase__ ): _a = 42 class lowercase ( UpperCamelCase__,UpperCamelCase__ ): @register_to_config def __init__( self , _a = 32 , _a = 64 , _a = 20 , _a = 768 , _a=77 , _a=4 , _a = 0.0 , _a = "silu" , _a = None , _a = None , _a = "linear" , _a = "prd" , _a = None , _a = None , _a = None , ) -> Any: super().__init__() _A : int = num_attention_heads _A : Union[str, Any] = attention_head_dim _A : Tuple = num_attention_heads * attention_head_dim _A : Any = additional_embeddings _A : Any = time_embed_dim or inner_dim _A : List[str] = embedding_proj_dim or embedding_dim _A : Optional[int] = clip_embed_dim or embedding_dim _A : Union[str, Any] = Timesteps(_a , _a , 0 ) _A : str = TimestepEmbedding(_a , _a , out_dim=_a , act_fn=_a ) _A : Dict = nn.Linear(_a , _a ) if embedding_proj_norm_type is None: _A : int = None elif embedding_proj_norm_type == "layer": _A : Optional[Any] = nn.LayerNorm(_a ) else: raise ValueError(F'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}''' ) _A : Optional[Any] = nn.Linear(_a , _a ) if encoder_hid_proj_type is None: _A : Union[str, Any] = None elif encoder_hid_proj_type == "linear": _A : Tuple = nn.Linear(_a , _a ) else: raise ValueError(F'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}''' ) _A : List[str] = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , _a ) ) if added_emb_type == "prd": _A : str = nn.Parameter(torch.zeros(1 , 1 , _a ) ) elif added_emb_type is None: _A : Union[str, Any] = None else: raise ValueError( F'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.''' ) _A : int = nn.ModuleList( [ BasicTransformerBlock( _a , _a , _a , dropout=_a , activation_fn="""gelu""" , attention_bias=_a , ) for d in range(_a ) ] ) if norm_in_type == "layer": _A : Union[str, Any] = nn.LayerNorm(_a ) elif norm_in_type is None: _A : Tuple = None else: raise ValueError(F'''Unsupported norm_in_type: {norm_in_type}.''' ) _A : int = nn.LayerNorm(_a ) _A : str = nn.Linear(_a , _a ) _A : Any = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -10000.0 ) causal_attention_mask.triu_(1 ) _A : Optional[int] = causal_attention_mask[None, ...] self.register_buffer("""causal_attention_mask""" , _a , persistent=_a ) _A : Tuple = nn.Parameter(torch.zeros(1 , _a ) ) _A : Dict = nn.Parameter(torch.zeros(1 , _a ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def a__ ( self ) -> Dict[str, AttentionProcessor]: _A : List[str] = {} def fn_recursive_add_processors(_a , _a , _a ): if hasattr(_a , """set_processor""" ): _A : Tuple = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F'''{name}.{sub_name}''' , _a , _a ) return processors for name, module in self.named_children(): fn_recursive_add_processors(_a , _a , _a ) return processors def a__ ( self , _a ) -> List[str]: _A : Optional[int] = len(self.attn_processors.keys() ) if isinstance(_a , _a ) and len(_a ) != count: raise ValueError( F'''A dict of processors was passed, but the number of processors {len(_a )} does not match the''' F''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''' ) def fn_recursive_attn_processor(_a , _a , _a ): if hasattr(_a , """set_processor""" ): if not isinstance(_a , _a ): module.set_processor(_a ) else: module.set_processor(processor.pop(F'''{name}.processor''' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F'''{name}.{sub_name}''' , _a , _a ) for name, module in self.named_children(): fn_recursive_attn_processor(_a , _a , _a ) def a__ ( self ) -> Union[str, Any]: self.set_attn_processor(AttnProcessor() ) def a__ ( self , _a , _a , _a , _a = None , _a = None , _a = True , ) -> Optional[Any]: _A : Tuple = hidden_states.shape[0] _A : List[Any] = timestep if not torch.is_tensor(_a ): _A : Dict = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(_a ) and len(timesteps.shape ) == 0: _A : Tuple = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML _A : Optional[int] = timesteps * torch.ones(_a , dtype=timesteps.dtype , device=timesteps.device ) _A : Dict = self.time_proj(_a ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. _A : Tuple = timesteps_projected.to(dtype=self.dtype ) _A : List[Any] = self.time_embedding(_a ) if self.embedding_proj_norm is not None: _A : Dict = self.embedding_proj_norm(_a ) _A : List[Any] = self.embedding_proj(_a ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: _A : List[Any] = self.encoder_hidden_states_proj(_a ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""" ) _A : Optional[int] = self.proj_in(_a ) _A : Optional[int] = self.positional_embedding.to(hidden_states.dtype ) _A : Union[str, Any] = [] _A : List[str] = 0 if encoder_hidden_states is not None: additional_embeds.append(_a ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: _A : List[str] = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: _A : List[str] = hidden_states[:, None, :] _A : Dict = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: _A : Optional[int] = self.prd_embedding.to(hidden_states.dtype ).expand(_a , -1 , -1 ) additional_embeds.append(_a ) _A : str = torch.cat( _a , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens _A : Dict = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: _A : Union[str, Any] = F.pad( _a , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) _A : Optional[Any] = hidden_states + positional_embeddings if attention_mask is not None: _A : Optional[Any] = (1 - attention_mask.to(hidden_states.dtype )) * -10000.0 _A : List[Any] = F.pad(_a , (0, self.additional_embeddings) , value=0.0 ) _A : Optional[Any] = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) _A : int = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: _A : str = self.norm_in(_a ) for block in self.transformer_blocks: _A : List[Any] = block(_a , attention_mask=_a ) _A : Any = self.norm_out(_a ) if self.prd_embedding is not None: _A : int = hidden_states[:, -1] else: _A : Any = hidden_states[:, additional_embeddings_len:] _A : Union[str, Any] = self.proj_to_clip_embeddings(_a ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=_a ) def a__ ( self , _a ) -> Tuple: _A : List[Any] = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
343
0
import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() _snake_case = logging.get_logger(__name__) _snake_case = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } _snake_case = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_ ): for attribute in key.split(""".""" ): _A : Any = getattr(_lowerCamelCase,_lowerCamelCase ) if weight_type is not None: _A : List[str] = getattr(_lowerCamelCase,_lowerCamelCase ).shape else: _A : Union[str, Any] = hf_pointer.shape assert hf_shape == value.shape, ( f'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be''' f''' {value.shape} for {full_name}''' ) if weight_type == "weight": _A : List[Any] = value elif weight_type == "weight_g": _A : Union[str, Any] = value elif weight_type == "weight_v": _A : Tuple = value elif weight_type == "bias": _A : int = value else: _A : Union[str, Any] = value logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : int = [] _A : Tuple = fairseq_model.state_dict() _A : Tuple = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight _A : Any = None for name, value in fairseq_dict.items(): _A : Optional[Any] = False if "conv_layers" in name: load_conv_layer( _lowerCamelCase,_lowerCamelCase,_lowerCamelCase,_lowerCamelCase,hf_model.config.feat_extract_norm == """group""",) _A : Optional[Any] = True elif name.split(""".""" )[0] == "proj": _A : int = fairseq_model.proj _A : List[Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: _A : int = True if "*" in mapped_key: _A : Dict = name.split(_lowerCamelCase )[0].split(""".""" )[-2] _A : Dict = mapped_key.replace("""*""",_lowerCamelCase ) if "weight_g" in name: _A : Optional[Any] = "weight_g" elif "weight_v" in name: _A : Tuple = "weight_v" elif "bias" in name: _A : List[str] = "bias" elif "weight" in name: _A : Dict = "weight" else: _A : List[Any] = None set_recursively(_lowerCamelCase,_lowerCamelCase,_lowerCamelCase,_lowerCamelCase,_lowerCamelCase ) continue if not is_used: unused_weights.append(_lowerCamelCase ) logger.warning(f'''Unused weights: {unused_weights}''' ) return proj_weight def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_ ): _A : List[str] = full_name.split("""conv_layers.""" )[-1] _A : List[str] = name.split(""".""" ) _A : int = int(items[0] ) _A : Any = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) _A : Dict = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) _A : Union[str, Any] = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) _A : Union[str, Any] = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) _A : int = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(_lowerCamelCase ) def lowerCAmelCase_ ( snake_case_ ): _A : Optional[Any] = emb.weight.shape _A : List[Any] = nn.Linear(_lowerCamelCase,_lowerCamelCase,bias=_lowerCamelCase ) _A : Optional[int] = emb.weight.data return lin_layer def lowerCAmelCase_ ( snake_case_ ): with open(_lowerCamelCase,"""r""",encoding="""utf-8""" ) as f: _A : str = f.readlines() _A : int = [line.split(""" """ )[0] for line in lines] _A : Optional[int] = len(_lowerCamelCase ) _A : Union[str, Any] = { "<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3, } vocab_dict.update(dict(zip(_lowerCamelCase,range(4,num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_,snake_case_,snake_case_,): _A : str = WavaVecaConfig.from_pretrained(_lowerCamelCase ) _A : Any = SpeechaTextaConfig.from_pretrained( _lowerCamelCase,vocab_size=_lowerCamelCase,decoder_layers=_lowerCamelCase,do_stable_layer_norm=_lowerCamelCase ) _A : str = WavaVecaFeatureExtractor( feature_size=1,sampling_rate=16000,padding_value=0,do_normalize=_lowerCamelCase,return_attention_mask=_lowerCamelCase,) _A : Tuple = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path],arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) _A : Tuple = model[0].eval() # set weights for wav2vec2 encoder _A : str = WavaVecaModel(_lowerCamelCase ) _A : List[str] = recursively_load_weights_wavaveca(model.encoder,_lowerCamelCase ) _A : int = SpeechaTextaForCausalLM(_lowerCamelCase ) _A : Optional[int] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict(),strict=_lowerCamelCase ) # set output linear layer unexpected_keys.remove("""embed_out""" ) _A : Union[str, Any] = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f'''The following keys are missing when loading the decoder weights: {missing_keys}''' ) logger.warning(f'''The following keys are unexpected when loading the decoder weights: {unexpected_keys}''' ) _A : int = SpeechEncoderDecoderModel(encoder=_lowerCamelCase,decoder=_lowerCamelCase ) _A : List[str] = False # add projection layer _A : str = nn.Parameter(projection_layer.weight ) _A : int = nn.Parameter(projection_layer.bias ) _A : int = create_vocab_dict(_lowerCamelCase ) with open(os.path.join(_lowerCamelCase,"""vocab.json""" ),"""w""" ) as fp: json.dump(_lowerCamelCase,_lowerCamelCase ) _A : str = SpeechaTextaTokenizer(os.path.join(_lowerCamelCase,"""vocab.json""" ) ) tokenizer.save_pretrained(_lowerCamelCase ) _A : Tuple = hf_wavavec.config.to_dict() _A : Any = tokenizer.pad_token_id _A : List[Any] = tokenizer.bos_token_id _A : List[str] = tokenizer.eos_token_id _A : Dict = "speech_to_text_2" _A : List[str] = "wav2vec2" _A : Tuple = SpeechEncoderDecoderConfig.from_dict(_lowerCamelCase ) hf_wavavec.save_pretrained(_lowerCamelCase ) feature_extractor.save_pretrained(_lowerCamelCase ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument( "--encoder_config_path", default="facebook/wav2vec2-large-lv60", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/s2t-small-mustc-en-fr-st", type=str, help="Path to hf decoder s2t checkpoint config", ) parser.add_argument("--vocab_size", default=10224, type=int, help="Vocab size of decoder") parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers") _snake_case = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
370
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : Any = None if token is not None: _A : int = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} _A : Any = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' _A : Union[str, Any] = requests.get(snake_case_,headers=snake_case_ ).json() _A : str = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) _A : int = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(snake_case_ ): _A : List[str] = requests.get(url + f'''&page={i + 2}''',headers=snake_case_ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : int = None if token is not None: _A : List[str] = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} _A : str = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100''' _A : Optional[Any] = requests.get(snake_case_,headers=snake_case_ ).json() _A : Any = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) _A : Tuple = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(snake_case_ ): _A : List[Any] = requests.get(url + f'''&page={i + 2}''',headers=snake_case_ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_ ): _A : Dict = None if token is not None: _A : int = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} _A : Tuple = requests.get(snake_case_,headers=snake_case_,allow_redirects=snake_case_ ) _A : Tuple = result.headers["""Location"""] _A : Union[str, Any] = requests.get(snake_case_,allow_redirects=snake_case_ ) _A : Dict = os.path.join(snake_case_,f'''{artifact_name}.zip''' ) with open(snake_case_,"""wb""" ) as fp: fp.write(response.content ) def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : List[str] = [] _A : int = [] _A : Tuple = None with zipfile.ZipFile(snake_case_ ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case_ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(snake_case_ ) as f: for line in f: _A : Any = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs _A : Dict = line[: line.index(""": """ )] _A : Dict = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed _A : List[str] = line[len("""FAILED """ ) :] failed_tests.append(snake_case_ ) elif filename == "job_name.txt": _A : Optional[int] = line if len(snake_case_ ) != len(snake_case_ ): raise ValueError( f'''`errors` and `failed_tests` should have the same number of elements. Got {len(snake_case_ )} for `errors` ''' f'''and {len(snake_case_ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some''' """ problem.""" ) _A : Any = None if job_name and job_links: _A : Dict = job_links.get(snake_case_,snake_case_ ) # A list with elements of the form (line of error, error, failed test) _A : Optional[int] = [x + [y] + [job_link] for x, y in zip(snake_case_,snake_case_ )] return result def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : Dict = [] _A : Optional[int] = [os.path.join(snake_case_,snake_case_ ) for p in os.listdir(snake_case_ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(snake_case_,job_links=snake_case_ ) ) return errors def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : Dict = Counter() counter.update([x[1] for x in logs] ) _A : Tuple = counter.most_common() _A : Tuple = {} for error, count in counts: if error_filter is None or error not in error_filter: _A : str = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} _A : Union[str, Any] = dict(sorted(r.items(),key=lambda snake_case_ : item[1]["count"],reverse=snake_case_ ) ) return r def lowerCAmelCase_ ( snake_case_ ): _A : Union[str, Any] = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): _A : Dict = test.split("""/""" )[2] else: _A : str = None return test def lowerCAmelCase_ ( snake_case_,snake_case_=None ): _A : str = [(x[0], x[1], get_model(x[2] )) for x in logs] _A : Union[str, Any] = [x for x in logs if x[2] is not None] _A : Optional[Any] = {x[2] for x in logs} _A : List[Any] = {} for test in tests: _A : Any = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) _A : Union[str, Any] = counter.most_common() _A : Any = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} _A : str = sum(error_counts.values() ) if n_errors > 0: _A : Optional[int] = {"""count""": n_errors, """errors""": error_counts} _A : Union[str, Any] = dict(sorted(r.items(),key=lambda snake_case_ : item[1]["count"],reverse=snake_case_ ) ) return r def lowerCAmelCase_ ( snake_case_ ): _A : Optional[int] = """| no. | error | status |""" _A : List[Any] = """|-:|:-|:-|""" _A : List[Any] = [header, sep] for error in reduced_by_error: _A : List[str] = reduced_by_error[error]["""count"""] _A : List[Any] = f'''| {count} | {error[:100]} | |''' lines.append(snake_case_ ) return "\n".join(snake_case_ ) def lowerCAmelCase_ ( snake_case_ ): _A : List[Any] = """| model | no. of errors | major error | count |""" _A : Optional[Any] = """|-:|-:|-:|-:|""" _A : Union[str, Any] = [header, sep] for model in reduced_by_model: _A : Dict = reduced_by_model[model]["""count"""] _A , _A : str = list(reduced_by_model[model]["""errors"""].items() )[0] _A : Union[str, Any] = f'''| {model} | {count} | {error[:60]} | {_count} |''' lines.append(snake_case_ ) return "\n".join(snake_case_ ) if __name__ == "__main__": _snake_case = 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.") _snake_case = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) _snake_case = get_job_links(args.workflow_run_id, token=args.token) _snake_case = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: _snake_case = k.find(" / ") _snake_case = k[index + len(" / ") :] _snake_case = v with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) _snake_case = 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) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) _snake_case = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error _snake_case = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors _snake_case = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) _snake_case = reduce_by_error(errors) _snake_case = reduce_by_model(errors) _snake_case = make_github_table(reduced_by_error) _snake_case = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: fp.write(sa) with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: fp.write(sa)
343
0
from __future__ import annotations from collections import namedtuple def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : Optional[Any] = namedtuple("""result""","""name value""" ) if (voltage, current, power).count(0 ) != 1: raise ValueError("""Only one argument must be 0""" ) elif power < 0: raise ValueError( """Power cannot be negative in any electrical/electronics system""" ) elif voltage == 0: return result("""voltage""",power / current ) elif current == 0: return result("""current""",power / voltage ) elif power == 0: return result("""power""",float(round(abs(voltage * current ),2 ) ) ) else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
371
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class lowercase ( unittest.TestCase ): def a__ ( self ) -> List[str]: debug_launcher(test_script.main ) def a__ ( self ) -> Any: debug_launcher(test_ops.main )
343
0
from typing import TYPE_CHECKING from ...utils import _LazyModule _snake_case = {"tokenization_byt5": ["ByT5Tokenizer"]} if TYPE_CHECKING: from .tokenization_byta import ByTaTokenizer else: import sys _snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
350
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _snake_case = logging.get_logger(__name__) _snake_case = { "microsoft/resnet-50": "https://huggingface.co/microsoft/resnet-50/blob/main/config.json", } class lowercase ( UpperCamelCase__,UpperCamelCase__ ): _a = "resnet" _a = ["basic", "bottleneck"] def __init__( self , _a=3 , _a=64 , _a=[256, 512, 1024, 2048] , _a=[3, 4, 6, 3] , _a="bottleneck" , _a="relu" , _a=False , _a=None , _a=None , **_a , ) -> int: super().__init__(**_a ) if layer_type not in self.layer_types: raise ValueError(F'''layer_type={layer_type} is not one of {",".join(self.layer_types )}''' ) _A : Optional[Any] = num_channels _A : List[Any] = embedding_size _A : int = hidden_sizes _A : Union[str, Any] = depths _A : Optional[int] = layer_type _A : Any = hidden_act _A : List[Any] = downsample_in_first_stage _A : int = ["""stem"""] + [F'''stage{idx}''' for idx in range(1 , len(_a ) + 1 )] _A , _A : str = get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names ) class lowercase ( UpperCamelCase__ ): _a = version.parse("1.11" ) @property def a__ ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def a__ ( self ) -> float: return 1e-3
343
0
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class lowercase ( __SCREAMING_SNAKE_CASE ): _a = CustomTokenizer pass
351
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowerCAmelCase_ ( snake_case_,snake_case_ ): # Load checkpoint _A : Optional[int] = torch.load(snake_case_,map_location="""cpu""" ) _A : Any = chkpt["""model"""] # We have the base model one level deeper than the original XLM repository _A : Any = {} for k, v in state_dict.items(): if "pred_layer" in k: _A : Tuple = v else: _A : Dict = v _A : Optional[Any] = chkpt["""params"""] _A : Union[str, Any] = {n: v for n, v in config.items() if not isinstance(snake_case_,(torch.FloatTensor, numpy.ndarray) )} _A : str = chkpt["""dico_word2id"""] _A : Optional[Any] = {s + """</w>""" if s.find("""@@""" ) == -1 and i > 13 else s.replace("""@@""","""""" ): i for s, i in vocab.items()} # Save pytorch-model _A : Dict = pytorch_dump_folder_path + """/""" + WEIGHTS_NAME _A : Any = pytorch_dump_folder_path + """/""" + CONFIG_NAME _A : Optional[int] = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""vocab_file"""] print(f'''Save PyTorch model to {pytorch_weights_dump_path}''' ) torch.save(snake_case_,snake_case_ ) print(f'''Save configuration file to {pytorch_config_dump_path}''' ) with open(snake_case_,"""w""",encoding="""utf-8""" ) as f: f.write(json.dumps(snake_case_,indent=2 ) + """\n""" ) print(f'''Save vocab file to {pytorch_config_dump_path}''' ) with open(snake_case_,"""w""",encoding="""utf-8""" ) as f: f.write(json.dumps(snake_case_,indent=2 ) + """\n""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( "--xlm_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) _snake_case = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
343
0
_snake_case = '\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' _snake_case = [{'type': 'code', 'content': INSTALL_CONTENT}] _snake_case = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
352
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowercase ( UpperCamelCase__ ): _a = ["image_processor", "tokenizer"] _a = "BlipImageProcessor" _a = ("BertTokenizer", "BertTokenizerFast") def __init__( self , _a , _a ) -> Any: _A : List[Any] = False super().__init__(_a , _a ) _A : Optional[int] = self.image_processor def __call__( self , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ) -> BatchEncoding: if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None: _A : Dict = self.tokenizer _A : Dict = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) return text_encoding # add pixel_values _A : int = self.image_processor(_a , return_tensors=_a ) if text is not None: _A : List[Any] = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) else: _A : int = None if text_encoding is not None: encoding_image_processor.update(_a ) return encoding_image_processor def a__ ( self , *_a , **_a ) -> Any: return self.tokenizer.batch_decode(*_a , **_a ) def a__ ( self , *_a , **_a ) -> List[str]: return self.tokenizer.decode(*_a , **_a ) @property def a__ ( self ) -> Optional[Any]: _A : Any = self.tokenizer.model_input_names _A : List[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
343
0