code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
def A ( _lowercase ): SCREAMING_SNAKE_CASE : int = int(_lowercase ) if decimal in (0, 1): # Exit cases for the recursion return str(_lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = divmod(_lowercase , 2 ) return binary_recursive(_lowercase ) + str(_lowercase ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Optional[int] = str(_lowercase ).strip() if not number: raise ValueError('''No input value was provided''' ) SCREAMING_SNAKE_CASE : str = '''-''' if number.startswith('''-''' ) else '''''' SCREAMING_SNAKE_CASE : Union[str, Any] = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return f"""{negative}0b{binary_recursive(int(_lowercase ) )}""" if __name__ == "__main__": from doctest import testmod testmod()
248
import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef __UpperCamelCase : List[Any] = ( 'This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ' 'library. You can have a look at this example script for pointers: ' 'https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py' ) def A ( _lowercase , _lowercase ): warnings.warn(_lowercase , _lowercase ) requires_backends(_lowercase , '''sklearn''' ) return (preds == labels).mean() def A ( _lowercase , _lowercase ): warnings.warn(_lowercase , _lowercase ) requires_backends(_lowercase , '''sklearn''' ) SCREAMING_SNAKE_CASE : int = simple_accuracy(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE : Tuple = fa_score(y_true=_lowercase , y_pred=_lowercase ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def A ( _lowercase , _lowercase ): warnings.warn(_lowercase , _lowercase ) requires_backends(_lowercase , '''sklearn''' ) SCREAMING_SNAKE_CASE : str = pearsonr(_lowercase , _lowercase )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = spearmanr(_lowercase , _lowercase )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def A ( _lowercase , _lowercase , _lowercase ): warnings.warn(_lowercase , _lowercase ) requires_backends(_lowercase , '''sklearn''' ) assert len(_lowercase ) == len(_lowercase ), f"""Predictions and labels have mismatched lengths {len(_lowercase )} and {len(_lowercase )}""" if task_name == "cola": return {"mcc": matthews_corrcoef(_lowercase , _lowercase )} elif task_name == "sst-2": return {"acc": simple_accuracy(_lowercase , _lowercase )} elif task_name == "mrpc": return acc_and_fa(_lowercase , _lowercase ) elif task_name == "sts-b": return pearson_and_spearman(_lowercase , _lowercase ) elif task_name == "qqp": return acc_and_fa(_lowercase , _lowercase ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(_lowercase , _lowercase )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(_lowercase , _lowercase )} elif task_name == "qnli": return {"acc": simple_accuracy(_lowercase , _lowercase )} elif task_name == "rte": return {"acc": simple_accuracy(_lowercase , _lowercase )} elif task_name == "wnli": return {"acc": simple_accuracy(_lowercase , _lowercase )} elif task_name == "hans": return {"acc": simple_accuracy(_lowercase , _lowercase )} else: raise KeyError(_lowercase ) def A ( _lowercase , _lowercase , _lowercase ): warnings.warn(_lowercase , _lowercase ) requires_backends(_lowercase , '''sklearn''' ) if len(_lowercase ) != len(_lowercase ): raise ValueError(f"""Predictions and labels have mismatched lengths {len(_lowercase )} and {len(_lowercase )}""" ) if task_name == "xnli": return {"acc": simple_accuracy(_lowercase , _lowercase )} else: raise KeyError(_lowercase )
248
1
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") __snake_case : List[Any] = logging.getLogger(__name__) @dataclass class A : __UpperCAmelCase : str = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) __UpperCAmelCase : Optional[str] = field( default=a , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) __UpperCAmelCase : Optional[str] = field( default=a , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) __UpperCAmelCase : Optional[str] = field( default=a , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) __UpperCAmelCase : bool = field( default=a , metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} , ) __UpperCAmelCase : str = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) __UpperCAmelCase : bool = field( default=a , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) @dataclass class A : __UpperCAmelCase : Optional[str] = field(default=a , metadata={"""help""": """The input training data file (a text file)."""} ) __UpperCAmelCase : Optional[str] = field( default=a , metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""} , ) __UpperCAmelCase : bool = field( default=a , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) __UpperCAmelCase : Optional[int] = field( default=a , metadata={"""help""": """The number of processes to use for the preprocessing."""} , ) __UpperCAmelCase : Optional[int] = field( default=a , metadata={ """help""": ( """The maximum total input sequence length after tokenization. If passed, sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) __UpperCAmelCase : bool = field( default=a , metadata={ """help""": ( """Whether to pad all samples to the maximum sentence length. """ """If False, will pad the samples dynamically when batching to the maximum length in the batch. More """ """efficient on GPU but very bad for TPU.""" ) } , ) __UpperCAmelCase : Optional[int] = field( default=a , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) __UpperCAmelCase : Optional[int] = field( default=a , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) def __lowerCAmelCase ( self ) -> Optional[Any]: if self.train_file is not None: _a = self.train_file.split("." )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: _a = self.validation_file.split("." )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class A : __UpperCAmelCase : PreTrainedTokenizerBase __UpperCAmelCase : Union[bool, str, PaddingStrategy] = True __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Optional[int] = None def __call__( self , snake_case_ ) -> Dict: _a = "label" if "label" in features[0].keys() else "labels" _a = [feature.pop(snake_case_ ) for feature in features] _a = len(snake_case_ ) _a = len(features[0]["input_ids"] ) _a = [ [{k: v[i] for k, v in feature.items()} for i in range(snake_case_ )] for feature in features ] _a = list(chain(*snake_case_ ) ) _a = self.tokenizer.pad( snake_case_ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) # Un-flatten _a = {k: v.view(snake_case_ , snake_case_ , -1 ) for k, v in batch.items()} # Add back labels _a = torch.tensor(snake_case_ , dtype=torch.intaa ) return batch def _lowercase ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. _a = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) 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 = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _a , _a , _a = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_swag", lowerCamelCase__, lowerCamelCase__ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout )], ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _a = training_args.get_process_log_level() logger.setLevel(lowerCamelCase__ ) datasets.utils.logging.set_verbosity(lowerCamelCase__ ) transformers.utils.logging.set_verbosity(lowerCamelCase__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(F'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. _a = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _a = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: _a = {} if data_args.train_file is not None: _a = data_args.train_file if data_args.validation_file is not None: _a = data_args.validation_file _a = data_args.train_file.split("." )[-1] _a = load_dataset( lowerCamelCase__, data_files=lowerCamelCase__, cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, ) else: # Downloading and loading the swag dataset from the hub. _a = load_dataset( "swag", "regular", cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _a = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else 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, ) _a = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) _a = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path ), config=lowerCamelCase__, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) # When using your own dataset or a different dataset from swag, you will probably need to change this. _a = [F'''ending{i}''' for i in range(4 )] _a = "sent1" _a = "sent2" if data_args.max_seq_length is None: _a = tokenizer.model_max_length if max_seq_length > 1_024: logger.warning( "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" " override this default with `--block_size xxx`." ) _a = 1_024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( F'''The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the''' F'''model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.''' ) _a = min(data_args.max_seq_length, tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(lowerCamelCase__ : Tuple ): _a = [[context] * 4 for context in examples[context_name]] _a = examples[question_header_name] _a = [ [F'''{header} {examples[end][i]}''' for end in ending_names] for i, header in enumerate(lowerCamelCase__ ) ] # Flatten out _a = list(chain(*lowerCamelCase__ ) ) _a = list(chain(*lowerCamelCase__ ) ) # Tokenize _a = tokenizer( lowerCamelCase__, lowerCamelCase__, truncation=lowerCamelCase__, max_length=lowerCamelCase__, padding="max_length" if data_args.pad_to_max_length else False, ) # Un-flatten return {k: [v[i : i + 4] for i in range(0, len(lowerCamelCase__ ), 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset" ) _a = raw_datasets["train"] if data_args.max_train_samples is not None: _a = min(len(lowerCamelCase__ ), data_args.max_train_samples ) _a = train_dataset.select(range(lowerCamelCase__ ) ) with training_args.main_process_first(desc="train dataset map pre-processing" ): _a = train_dataset.map( lowerCamelCase__, batched=lowerCamelCase__, num_proc=data_args.preprocessing_num_workers, load_from_cache_file=not data_args.overwrite_cache, ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset" ) _a = raw_datasets["validation"] if data_args.max_eval_samples is not None: _a = min(len(lowerCamelCase__ ), data_args.max_eval_samples ) _a = eval_dataset.select(range(lowerCamelCase__ ) ) with training_args.main_process_first(desc="validation dataset map pre-processing" ): _a = eval_dataset.map( lowerCamelCase__, batched=lowerCamelCase__, num_proc=data_args.preprocessing_num_workers, load_from_cache_file=not data_args.overwrite_cache, ) # Data collator _a = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=lowerCamelCase__, pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(lowerCamelCase__ : int ): _a , _a = eval_predictions _a = np.argmax(lowerCamelCase__, axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer _a = Trainer( model=lowerCamelCase__, args=lowerCamelCase__, train_dataset=train_dataset if training_args.do_train else None, eval_dataset=eval_dataset if training_args.do_eval else None, tokenizer=lowerCamelCase__, data_collator=lowerCamelCase__, compute_metrics=lowerCamelCase__, ) # Training if training_args.do_train: _a = None if training_args.resume_from_checkpoint is not None: _a = training_args.resume_from_checkpoint elif last_checkpoint is not None: _a = last_checkpoint _a = trainer.train(resume_from_checkpoint=lowerCamelCase__ ) trainer.save_model() # Saves the tokenizer too for easy upload _a = train_result.metrics _a = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCamelCase__ ) ) _a = min(lowerCamelCase__, len(lowerCamelCase__ ) ) trainer.log_metrics("train", lowerCamelCase__ ) trainer.save_metrics("train", lowerCamelCase__ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) _a = trainer.evaluate() _a = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCamelCase__ ) _a = min(lowerCamelCase__, len(lowerCamelCase__ ) ) trainer.log_metrics("eval", lowerCamelCase__ ) trainer.save_metrics("eval", lowerCamelCase__ ) _a = { "finetuned_from": model_args.model_name_or_path, "tasks": "multiple-choice", "dataset_tags": "swag", "dataset_args": "regular", "dataset": "SWAG", "language": "en", } if training_args.push_to_hub: trainer.push_to_hub(**lowerCamelCase__ ) else: trainer.create_model_card(**lowerCamelCase__ ) def _lowercase ( lowerCamelCase__ : Optional[int] ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
691
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu __snake_case : List[Any] = [ "EAGER", "AOT_EAGER", "INDUCTOR", "NVFUSER", "AOT_NVFUSER", "AOT_CUDAGRAPHS", "OFI", "FX2TRT", "ONNXRT", "IPEX", ] def _lowercase ( lowerCamelCase__ : Union[str, Any], lowerCamelCase__ : Union[str, Any]=None, lowerCamelCase__ : Dict=None, lowerCamelCase__ : Optional[int]=None ): _a = True while ask_again: _a = input(lowerCamelCase__ ) try: if default is not None and len(lowerCamelCase__ ) == 0: return default return convert_value(lowerCamelCase__ ) if convert_value is not None else result except Exception: if error_message is not None: print(lowerCamelCase__ ) def _lowercase ( lowerCamelCase__ : Optional[Any], lowerCamelCase__ : Dict=[], lowerCamelCase__ : int=None, lowerCamelCase__ : Union[str, Any]=0 ): _a = BulletMenu(lowerCamelCase__, lowerCamelCase__ ) _a = menu.run(default_choice=lowerCamelCase__ ) return convert_value(lowerCamelCase__ ) if convert_value is not None else result def _lowercase ( lowerCamelCase__ : str ): _a = int(lowerCamelCase__ ) return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value] ) def _lowercase ( lowerCamelCase__ : str ): _a = int(lowerCamelCase__ ) return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value] ) def _lowercase ( lowerCamelCase__ : Dict ): _a = int(lowerCamelCase__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def _lowercase ( lowerCamelCase__ : List[Any] ): _a = int(lowerCamelCase__ ) return PrecisionType(["no", "fp16", "bf16", "fp8"][value] ) def _lowercase ( lowerCamelCase__ : str ): _a = int(lowerCamelCase__ ) return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value] ) def _lowercase ( lowerCamelCase__ : str ): return {"yes": True, "no": False}[value.lower()] class A ( argparse.RawDescriptionHelpFormatter ): def __lowerCAmelCase ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: _a = super()._format_usage(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) _a = usage.replace("<command> [<args>] " , "" ) return usage
691
1
"""simple docstring""" import inspect import unittest from transformers import DecisionTransformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import DecisionTransformerModel from transformers.models.decision_transformer.modeling_decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) class _UpperCAmelCase: def __init__( self , __a , __a=13 , __a=7 , __a=6 , __a=17 , __a=23 , __a=11 , __a=True , ) -> Optional[int]: '''simple docstring''' _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = act_dim _UpperCamelCase = state_dim _UpperCamelCase = hidden_size _UpperCamelCase = max_length _UpperCamelCase = is_training def UpperCAmelCase ( self) -> List[Any]: '''simple docstring''' _UpperCamelCase = floats_tensor((self.batch_size, self.seq_length, self.state_dim)) _UpperCamelCase = floats_tensor((self.batch_size, self.seq_length, self.act_dim)) _UpperCamelCase = floats_tensor((self.batch_size, self.seq_length, 1)) _UpperCamelCase = floats_tensor((self.batch_size, self.seq_length, 1)) _UpperCamelCase = ids_tensor((self.batch_size, self.seq_length) , vocab_size=10_00) _UpperCamelCase = random_attention_mask((self.batch_size, self.seq_length)) _UpperCamelCase = self.get_config() return ( config, states, actions, rewards, returns_to_go, timesteps, attention_mask, ) def UpperCAmelCase ( self) -> List[Any]: '''simple docstring''' return DecisionTransformerConfig( batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , ) def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a , ) -> List[str]: '''simple docstring''' _UpperCamelCase = DecisionTransformerModel(config=__a) model.to(__a) model.eval() _UpperCamelCase = model(__a , __a , __a , __a , __a , __a) self.parent.assertEqual(result.state_preds.shape , states.shape) self.parent.assertEqual(result.action_preds.shape , actions.shape) self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size)) # seq length *3 as there are 3 modelities: states, returns and actions def UpperCAmelCase ( self) -> Any: '''simple docstring''' _UpperCamelCase = self.prepare_config_and_inputs() ( ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ) = config_and_inputs _UpperCamelCase = { '''states''': states, '''actions''': actions, '''rewards''': rewards, '''returns_to_go''': returns_to_go, '''timesteps''': timesteps, '''attention_mask''': attention_mask, } return config, inputs_dict @require_torch class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase__ = (DecisionTransformerModel,) if is_torch_available() else () lowercase__ = () lowercase__ = {'feature-extraction': DecisionTransformerModel} if is_torch_available() else {} # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids lowercase__ = False # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False def UpperCAmelCase ( self) -> int: '''simple docstring''' _UpperCamelCase = DecisionTransformerModelTester(self) _UpperCamelCase = ConfigTester(self , config_class=__a , hidden_size=37) def UpperCAmelCase ( self) -> Dict: '''simple docstring''' self.config_tester.run_common_tests() def UpperCAmelCase ( self) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a) @slow def UpperCAmelCase ( self) -> Any: '''simple docstring''' for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCamelCase = DecisionTransformerModel.from_pretrained(__a) self.assertIsNotNone(__a) def UpperCAmelCase ( self) -> Optional[Any]: '''simple docstring''' _UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCamelCase = model_class(__a) _UpperCamelCase = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCamelCase = [*signature.parameters.keys()] _UpperCamelCase = [ '''states''', '''actions''', '''rewards''', '''returns_to_go''', '''timesteps''', '''attention_mask''', ] self.assertListEqual(arg_names[: len(__a)] , __a) @require_torch class _UpperCAmelCase( unittest.TestCase ): @slow def UpperCAmelCase ( self) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase = 2 # number of steps of autoregressive prediction we will perform _UpperCamelCase = 10 # defined by the RL environment, may be normalized _UpperCamelCase = DecisionTransformerModel.from_pretrained('''edbeeching/decision-transformer-gym-hopper-expert''') _UpperCamelCase = model.to(__a) _UpperCamelCase = model.config torch.manual_seed(0) _UpperCamelCase = torch.randn(1 , 1 , config.state_dim).to(device=__a , dtype=torch.floataa) # env.reset() _UpperCamelCase = torch.tensor( [[0.24_2793, -0.2869_3074, 0.874_2613], [0.6781_5274, -0.0810_1085, -0.1295_2147]] , device=__a) _UpperCamelCase = torch.tensor(__a , device=__a , dtype=torch.floataa).reshape(1 , 1 , 1) _UpperCamelCase = state _UpperCamelCase = torch.zeros(1 , 0 , config.act_dim , device=__a , dtype=torch.floataa) _UpperCamelCase = torch.zeros(1 , 0 , device=__a , dtype=torch.floataa) _UpperCamelCase = torch.tensor(0 , device=__a , dtype=torch.long).reshape(1 , 1) for step in range(__a): _UpperCamelCase = torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=__a)] , dim=1) _UpperCamelCase = torch.cat([rewards, torch.zeros(1 , 1 , device=__a)] , dim=1) _UpperCamelCase = torch.ones(1 , states.shape[1]).to(dtype=torch.long , device=states.device) with torch.no_grad(): _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = model( states=__a , actions=__a , rewards=__a , returns_to_go=__a , timesteps=__a , attention_mask=__a , return_dict=__a , ) self.assertEqual(action_pred.shape , actions.shape) self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1e-4)) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = ( # env.step(action) torch.randn(1 , 1 , config.state_dim).to(device=__a , dtype=torch.floataa), 1.0, False, {}, ) _UpperCamelCase = action_pred[0, -1] _UpperCamelCase = torch.cat([states, state] , dim=1) _UpperCamelCase = returns_to_go[0, -1] - reward _UpperCamelCase = torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1)] , dim=1) _UpperCamelCase = torch.cat( [timesteps, torch.ones((1, 1) , device=__a , dtype=torch.long) * (step + 1)] , dim=1)
19
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) A = { """configuration_trocr""": ["""TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TrOCRConfig"""], """processing_trocr""": ["""TrOCRProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = [ """TROCR_PRETRAINED_MODEL_ARCHIVE_LIST""", """TrOCRForCausalLM""", """TrOCRPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
77
0
'''simple docstring''' import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger _snake_case : Dict = get_logger(__name__) class A ( enum.Enum ): lowercase_ = 'all_checks' lowercase_ = 'basic_checks' lowercase_ = 'no_checks' class A ( _a ): pass class A ( _a ): pass class A ( _a ): pass class A ( _a ): pass def snake_case_ (UpperCamelCase : Optional[dict] , UpperCamelCase : dict , UpperCamelCase : List[str]=None ): '''simple docstring''' if expected_checksums is None: logger.info('''Unable to verify checksums.''' ) return if len(set(UpperCamelCase ) - set(UpperCamelCase ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(UpperCamelCase ) - set(UpperCamelCase ) ) ) if len(set(UpperCamelCase ) - set(UpperCamelCase ) ) > 0: raise UnexpectedDownloadedFile(str(set(UpperCamelCase ) - set(UpperCamelCase ) ) ) _a = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] _a = ''' for ''' + verification_name if verification_name is not None else '''''' if len(UpperCamelCase ) > 0: raise NonMatchingChecksumError( f'Checksums didn\'t match{for_verification_name}:\n' f'{bad_urls}\n' '''Set `verification_mode=\'no_checks\'` to skip checksums verification and ignore this error''' ) logger.info('''All the checksums matched successfully''' + for_verification_name ) class A ( _a ): pass class A ( _a ): pass class A ( _a ): pass class A ( _a ): pass def snake_case_ (UpperCamelCase : Optional[dict] , UpperCamelCase : dict ): '''simple docstring''' if expected_splits is None: logger.info('''Unable to verify splits sizes.''' ) return if len(set(UpperCamelCase ) - set(UpperCamelCase ) ) > 0: raise ExpectedMoreSplits(str(set(UpperCamelCase ) - set(UpperCamelCase ) ) ) if len(set(UpperCamelCase ) - set(UpperCamelCase ) ) > 0: raise UnexpectedSplits(str(set(UpperCamelCase ) - set(UpperCamelCase ) ) ) _a = [ {'''expected''': expected_splits[name], '''recorded''': recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(UpperCamelCase ) > 0: raise NonMatchingSplitsSizesError(str(UpperCamelCase ) ) logger.info('''All the splits matched successfully.''' ) def snake_case_ (UpperCamelCase : str , UpperCamelCase : bool = True ): '''simple docstring''' if record_checksum: _a = shaaaa() with open(UpperCamelCase , '''rb''' ) as f: for chunk in iter(lambda: f.read(1 << 20 ) , B'''''' ): m.update(UpperCamelCase ) _a = m.hexdigest() else: _a = None return {"num_bytes": os.path.getsize(UpperCamelCase ), "checksum": checksum} def snake_case_ (UpperCamelCase : List[Any] ): '''simple docstring''' if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
377
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin _snake_case : str = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right _snake_case : Union[str, Any] = 256047 _snake_case : Tuple = 256145 @require_sentencepiece @require_tokenizers class A ( _a ,unittest.TestCase ): lowercase_ = NllbTokenizer lowercase_ = NllbTokenizerFast lowercase_ = True lowercase_ = True lowercase_ = {} def __lowerCAmelCase ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing _a = NllbTokenizer(lowerCAmelCase_ , keep_accents=lowerCAmelCase_ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self : Tuple ) -> Union[str, Any]: """simple docstring""" _a = NllbTokenizer(lowerCAmelCase_ , keep_accents=lowerCAmelCase_ ) _a = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(lowerCAmelCase_ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) _a = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( lowerCAmelCase_ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) _a = tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) self.assertListEqual( lowerCAmelCase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) _a = tokenizer.convert_ids_to_tokens(lowerCAmelCase_ ) self.assertListEqual( lowerCAmelCase_ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) def __lowerCAmelCase ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" _a = (self.rust_tokenizer_class, '''hf-internal-testing/tiny-random-nllb''', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): _a = self.rust_tokenizer_class.from_pretrained(lowerCAmelCase_ , **lowerCAmelCase_ ) _a = self.tokenizer_class.from_pretrained(lowerCAmelCase_ , **lowerCAmelCase_ ) _a = tempfile.mkdtemp() _a = tokenizer_r.save_pretrained(lowerCAmelCase_ ) _a = tokenizer_p.save_pretrained(lowerCAmelCase_ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) ) _a = tuple(f for f in tokenizer_r_files if '''tokenizer.json''' not in f ) self.assertSequenceEqual(lowerCAmelCase_ , lowerCAmelCase_ ) # Checks everything loads correctly in the same way _a = tokenizer_r.from_pretrained(lowerCAmelCase_ ) _a = tokenizer_p.from_pretrained(lowerCAmelCase_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) shutil.rmtree(lowerCAmelCase_ ) # Save tokenizer rust, legacy_format=True _a = tempfile.mkdtemp() _a = tokenizer_r.save_pretrained(lowerCAmelCase_ , legacy_format=lowerCAmelCase_ ) _a = tokenizer_p.save_pretrained(lowerCAmelCase_ ) # Checks it save with the same files self.assertSequenceEqual(lowerCAmelCase_ , lowerCAmelCase_ ) # Checks everything loads correctly in the same way _a = tokenizer_r.from_pretrained(lowerCAmelCase_ ) _a = tokenizer_p.from_pretrained(lowerCAmelCase_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) shutil.rmtree(lowerCAmelCase_ ) # Save tokenizer rust, legacy_format=False _a = tempfile.mkdtemp() _a = tokenizer_r.save_pretrained(lowerCAmelCase_ , legacy_format=lowerCAmelCase_ ) _a = tokenizer_p.save_pretrained(lowerCAmelCase_ ) # Checks it saved the tokenizer.json file self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way _a = tokenizer_r.from_pretrained(lowerCAmelCase_ ) _a = tokenizer_p.from_pretrained(lowerCAmelCase_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) shutil.rmtree(lowerCAmelCase_ ) @require_torch def __lowerCAmelCase ( self : Union[str, Any] ) -> Dict: """simple docstring""" if not self.test_seqaseq: return _a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. _a = [ ''' UN Chief Says There Is No Military Solution in Syria''', ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for''' ''' Syria is that \'there is no military solution\' to the nearly five-year conflict and more weapons''' ''' will only worsen the violence and misery for millions of people.''', ] _a = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al''' ''' Rusiei pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi''' ''' că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''', ] try: _a = tokenizer.prepare_seqaseq_batch( src_texts=lowerCAmelCase_ , tgt_texts=lowerCAmelCase_ , max_length=3 , max_target_length=10 , return_tensors='''pt''' , src_lang='''eng_Latn''' , tgt_lang='''ron_Latn''' , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified _a = tokenizer.prepare_seqaseq_batch( lowerCAmelCase_ , tgt_texts=lowerCAmelCase_ , max_length=3 , return_tensors='''pt''' ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) _a = tokenizer.prepare_seqaseq_batch( src_texts=lowerCAmelCase_ , max_length=3 , max_target_length=10 , return_tensors='''pt''' ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn('''decoder_input_ids''' , lowerCAmelCase_ ) @unittest.skip('''Unfortunately way too slow to build a BPE with SentencePiece.''' ) def __lowerCAmelCase ( self : Dict ) -> Tuple: """simple docstring""" pass def __lowerCAmelCase ( self : List[Any] ) -> Optional[Any]: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): _a = [AddedToken('''<special>''' , lstrip=lowerCAmelCase_ )] _a = self.rust_tokenizer_class.from_pretrained( lowerCAmelCase_ , additional_special_tokens=lowerCAmelCase_ , **lowerCAmelCase_ ) _a = tokenizer_r.encode('''Hey this is a <special> token''' ) _a = tokenizer_r.encode('''<special>''' , add_special_tokens=lowerCAmelCase_ )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: _a = self.rust_tokenizer_class.from_pretrained( lowerCAmelCase_ , additional_special_tokens=lowerCAmelCase_ , **lowerCAmelCase_ , ) _a = self.tokenizer_class.from_pretrained( lowerCAmelCase_ , additional_special_tokens=lowerCAmelCase_ , **lowerCAmelCase_ ) _a = tokenizer_p.encode('''Hey this is a <special> token''' ) _a = tokenizer_cr.encode('''Hey this is a <special> token''' ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class A ( unittest.TestCase ): lowercase_ = 'facebook/nllb-200-distilled-600M' lowercase_ = [ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.', ] lowercase_ = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei' ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' ' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] lowercase_ = [ 25_6047, 1_6297, 13_4408, 8165, 24_8066, 1_4734, 950, 1135, 10_5721, 3573, 83, 2_7352, 108, 4_9486, 2, ] @classmethod def __lowerCAmelCase ( cls : Tuple ) -> Optional[int]: """simple docstring""" _a = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang='''eng_Latn''' , tgt_lang='''ron_Latn''' ) _a = 1 return cls def __lowerCAmelCase ( self : str ) -> Union[str, Any]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''ace_Arab'''] , 25_60_01 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''ace_Latn'''] , 25_60_02 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''fra_Latn'''] , 25_60_57 ) def __lowerCAmelCase ( self : Optional[Any] ) -> int: """simple docstring""" _a = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , lowerCAmelCase_ ) def __lowerCAmelCase ( self : int ) -> List[Any]: """simple docstring""" self.assertIn(lowerCAmelCase_ , self.tokenizer.all_special_ids ) # fmt: off _a = [RO_CODE, 42_54, 9_80_68, 11_29_23, 3_90_72, 39_09, 7_13, 10_27_67, 26, 1_73_14, 3_56_42, 1_46_83, 3_31_18, 20_22, 6_69_87, 2, 25_60_47] # fmt: on _a = self.tokenizer.decode(lowerCAmelCase_ , skip_special_tokens=lowerCAmelCase_ ) _a = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertNotIn(self.tokenizer.eos_token , lowerCAmelCase_ ) def __lowerCAmelCase ( self : Dict ) -> Union[str, Any]: """simple docstring""" _a = ['''this is gunna be a long sentence ''' * 20] assert isinstance(src_text[0] , lowerCAmelCase_ ) _a = 10 _a = self.tokenizer(lowerCAmelCase_ , max_length=lowerCAmelCase_ , truncation=lowerCAmelCase_ ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , lowerCAmelCase_ ) self.assertEqual(len(lowerCAmelCase_ ) , lowerCAmelCase_ ) def __lowerCAmelCase ( self : List[Any] ) -> Optional[int]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['''<mask>''', '''ar_AR'''] ) , [25_62_03, 3] ) def __lowerCAmelCase ( self : List[str] ) -> Tuple: """simple docstring""" _a = tempfile.mkdtemp() _a = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(lowerCAmelCase_ ) _a = NllbTokenizer.from_pretrained(lowerCAmelCase_ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , lowerCAmelCase_ ) @require_torch def __lowerCAmelCase ( self : str ) -> Optional[int]: """simple docstring""" _a = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=len(self.expected_src_tokens ) , return_tensors='''pt''' , ) _a = shift_tokens_right( batch['''labels'''] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id['''ron_Latn'''] ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) _a = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def __lowerCAmelCase ( self : Optional[Any] ) -> Any: """simple docstring""" _a = self.tokenizer(self.src_text , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=3 , return_tensors='''pt''' ) _a = self.tokenizer( text_target=self.tgt_text , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=10 , return_tensors='''pt''' ) _a = targets['''input_ids'''] _a = shift_tokens_right( lowerCAmelCase_ , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def __lowerCAmelCase ( self : List[Any] ) -> Optional[Any]: """simple docstring""" _a = self.tokenizer._build_translation_inputs( '''A test''' , return_tensors='''pt''' , src_lang='''eng_Latn''' , tgt_lang='''fra_Latn''' ) self.assertEqual( nested_simplify(lowerCAmelCase_ ) , { # A, test, EOS, en_XX '''input_ids''': [[25_60_47, 70, 73_56, 2]], '''attention_mask''': [[1, 1, 1, 1]], # ar_AR '''forced_bos_token_id''': 25_60_57, } , ) @require_torch def __lowerCAmelCase ( self : Any ) -> Tuple: """simple docstring""" _a = True _a = self.tokenizer( '''UN Chief says there is no military solution in Syria''' , src_lang='''eng_Latn''' , tgt_lang='''fra_Latn''' ) self.assertEqual( inputs.input_ids , [1_62_97, 13_44_08, 2_56_53, 63_70, 2_48, 2_54, 10_39_29, 9_49_95, 1_08, 4_94_86, 2, 25_60_47] ) _a = False _a = self.tokenizer( '''UN Chief says there is no military solution in Syria''' , src_lang='''eng_Latn''' , tgt_lang='''fra_Latn''' ) self.assertEqual( inputs.input_ids , [25_60_47, 1_62_97, 13_44_08, 2_56_53, 63_70, 2_48, 2_54, 10_39_29, 9_49_95, 1_08, 4_94_86, 2] )
377
1
"""simple docstring""" import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format='%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=os.environ.get('LOGLEVEL', 'INFO').upper(), stream=sys.stdout, ) lowerCAmelCase_ = logging.getLogger(__name__) lowerCAmelCase_ = {"facebook/bart-base": BartForConditionalGeneration} lowerCAmelCase_ = {"facebook/bart-base": BartTokenizer} def __UpperCAmelCase ( ) -> List[Any]: lowercase__ : str = argparse.ArgumentParser(description='''Export Bart model + Beam Search to ONNX graph.''' ) parser.add_argument( '''--validation_file''' , type=A__ , default=A__ , help='''A csv or a json file containing the validation data.''' ) parser.add_argument( '''--max_length''' , type=A__ , default=5 , help='''The maximum total input sequence length after tokenization.''' , ) parser.add_argument( '''--num_beams''' , type=A__ , default=A__ , help=( '''Number of beams to use for evaluation. This argument will be ''' '''passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.''' ) , ) parser.add_argument( '''--model_name_or_path''' , type=A__ , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=A__ , ) parser.add_argument( '''--config_name''' , type=A__ , default=A__ , help='''Pretrained config name or path if not the same as model_name''' , ) parser.add_argument( '''--device''' , type=A__ , default='''cpu''' , help='''Device where the model will be run''' , ) parser.add_argument('''--output_file_path''' , type=A__ , default=A__ , help='''Where to store the final ONNX file.''' ) lowercase__ : int = parser.parse_args() return args def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase="cpu" ) -> Optional[Any]: lowercase__ : Any = model_dict[model_name].from_pretrained(A__ ).to(A__ ) lowercase__ : List[Any] = tokenizer_dict[model_name].from_pretrained(A__ ) if model_name in ["facebook/bart-base"]: lowercase__ : Any = 0 lowercase__ : Tuple = None lowercase__ : Optional[Any] = 0 return huggingface_model, tokenizer def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: model.eval() lowercase__ : Dict = None lowercase__ : str = torch.jit.script(BARTBeamSearchGenerator(A__ ) ) with torch.no_grad(): lowercase__ : List[Any] = '''My friends are cool but they eat too many carbs.''' lowercase__ : Optional[Any] = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=10_24 , return_tensors='''pt''' ).to(model.device ) lowercase__ : Tuple = model.generate( inputs['''input_ids'''] , attention_mask=inputs['''attention_mask'''] , num_beams=A__ , max_length=A__ , early_stopping=A__ , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( A__ , ( inputs['''input_ids'''], inputs['''attention_mask'''], num_beams, max_length, model.config.decoder_start_token_id, ) , A__ , opset_version=14 , input_names=['''input_ids''', '''attention_mask''', '''num_beams''', '''max_length''', '''decoder_start_token_id'''] , output_names=['''output_ids'''] , dynamic_axes={ '''input_ids''': {0: '''batch''', 1: '''seq'''}, '''output_ids''': {0: '''batch''', 1: '''seq_out'''}, } , example_outputs=A__ , ) logger.info('''Model exported to {}'''.format(A__ ) ) lowercase__ : int = remove_dup_initializers(os.path.abspath(A__ ) ) logger.info('''Deduplicated and optimized model written to {}'''.format(A__ ) ) lowercase__ : List[Any] = onnxruntime.InferenceSession(A__ ) lowercase__ : int = ort_sess.run( A__ , { '''input_ids''': inputs['''input_ids'''].cpu().numpy(), '''attention_mask''': inputs['''attention_mask'''].cpu().numpy(), '''num_beams''': np.array(A__ ), '''max_length''': np.array(A__ ), '''decoder_start_token_id''': np.array(model.config.decoder_start_token_id ), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1E-3 , atol=1E-3 ) logger.info('''Model outputs from torch and ONNX Runtime are similar.''' ) logger.info('''Success.''' ) def __UpperCAmelCase ( ) -> Dict: lowercase__ : str = parse_args() lowercase__ : List[Any] = 5 lowercase__ : Dict = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO , ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() lowercase__ : Any = torch.device(args.device ) lowercase__ , lowercase__ : List[Any] = load_model_tokenizer(args.model_name_or_path , A__ ) if model.config.decoder_start_token_id is None: raise ValueError('''Make sure that `config.decoder_start_token_id` is correctly defined''' ) model.to(A__ ) if args.max_length: lowercase__ : int = args.max_length if args.num_beams: lowercase__ : List[Any] = args.num_beams if args.output_file_path: lowercase__ : Union[str, Any] = args.output_file_path else: lowercase__ : str = '''BART.onnx''' logger.info('''Exporting model to ONNX''' ) export_and_validate_model(A__ , A__ , A__ , A__ , A__ ) if __name__ == "__main__": main()
560
'''simple docstring''' from collections import deque class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[Any] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : int ): """simple docstring""" UpperCamelCase = process_name # process name UpperCamelCase = arrival_time # arrival time of the process # completion time of finished process or last interrupted time UpperCamelCase = arrival_time UpperCamelCase = burst_time # remaining burst time UpperCamelCase = 0 # total time of the process wait in ready queue UpperCamelCase = 0 # time from arrival time to completion time class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : str , UpperCamelCase__ : int , UpperCamelCase__ : list[int] , UpperCamelCase__ : deque[Process] , UpperCamelCase__ : int , ): """simple docstring""" UpperCamelCase = number_of_queues # time slice of queues that round robin algorithm applied UpperCamelCase = time_slices # unfinished process is in this ready_queue UpperCamelCase = queue # current time UpperCamelCase = current_time # finished process is in this sequence queue UpperCamelCase = deque() def A ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def A ( self : Optional[Any] , UpperCamelCase__ : list[Process] ): """simple docstring""" UpperCamelCase = [] for i in range(len(UpperCamelCase__ ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def A ( self : Dict , UpperCamelCase__ : list[Process] ): """simple docstring""" UpperCamelCase = [] for i in range(len(UpperCamelCase__ ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def A ( self : int , UpperCamelCase__ : list[Process] ): """simple docstring""" UpperCamelCase = [] for i in range(len(UpperCamelCase__ ) ): completion_times.append(queue[i].stop_time ) return completion_times def A ( self : Optional[int] , UpperCamelCase__ : deque[Process] ): """simple docstring""" return [q.burst_time for q in queue] def A ( self : Any , UpperCamelCase__ : Process ): """simple docstring""" process.waiting_time += self.current_time - process.stop_time return process.waiting_time def A ( self : Union[str, Any] , UpperCamelCase__ : deque[Process] ): """simple docstring""" UpperCamelCase = deque() # sequence deque of finished process while len(UpperCamelCase__ ) != 0: UpperCamelCase = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(UpperCamelCase__ ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 UpperCamelCase = 0 # set the process's turnaround time because it is finished UpperCamelCase = self.current_time - cp.arrival_time # set the completion time UpperCamelCase = self.current_time # add the process to queue that has finished queue finished.append(UpperCamelCase__ ) self.finish_queue.extend(UpperCamelCase__ ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def A ( self : Union[str, Any] , UpperCamelCase__ : deque[Process] , UpperCamelCase__ : int ): """simple docstring""" UpperCamelCase = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(UpperCamelCase__ ) ): UpperCamelCase = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(UpperCamelCase__ ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time UpperCamelCase = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(UpperCamelCase__ ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished UpperCamelCase = 0 # set the finish time UpperCamelCase = self.current_time # update the process' turnaround time because it is finished UpperCamelCase = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(UpperCamelCase__ ) self.finish_queue.extend(UpperCamelCase__ ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def A ( self : Any ): """simple docstring""" for i in range(self.number_of_queues - 1 ): UpperCamelCase , UpperCamelCase = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest _lowerCamelCase : Optional[Any] = Process("P1", 0, 53) _lowerCamelCase : List[str] = Process("P2", 0, 17) _lowerCamelCase : Optional[int] = Process("P3", 0, 68) _lowerCamelCase : Dict = Process("P4", 0, 24) _lowerCamelCase : Union[str, Any] = 3 _lowerCamelCase : int = [17, 25] _lowerCamelCase : List[Any] = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={"queue": deque([Pa, Pa, Pa, Pa])}) _lowerCamelCase : Dict = Process("P1", 0, 53) _lowerCamelCase : int = Process("P2", 0, 17) _lowerCamelCase : Union[str, Any] = Process("P3", 0, 68) _lowerCamelCase : str = Process("P4", 0, 24) _lowerCamelCase : Optional[Any] = 3 _lowerCamelCase : Any = [17, 25] _lowerCamelCase : str = deque([Pa, Pa, Pa, Pa]) _lowerCamelCase : List[Any] = MLFQ(number_of_queues, time_slices, queue, 0) _lowerCamelCase : int = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( f'''waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print completion times of processes(P1, P2, P3, P4) print( f'''completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print total turnaround times of processes(P1, P2, P3, P4) print( f'''turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print sequence of finished processes print( f'''sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}''' )
430
0
import pytest lowerCamelCase : Optional[int] = "__dummy_dataset1__" lowerCamelCase : Tuple = "\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = \"https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/\"\nURLS = {\"train\": REPO_URL + \"wikiann-bn-train.jsonl\", \"validation\": REPO_URL + \"wikiann-bn-validation.jsonl\"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n \"tokens\": datasets.Sequence(datasets.Value(\"string\")),\n \"ner_tags\": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n \"O\",\n \"B-PER\",\n \"I-PER\",\n \"B-ORG\",\n \"I-ORG\",\n \"B-LOC\",\n \"I-LOC\",\n ]\n )\n ),\n \"langs\": datasets.Sequence(datasets.Value(\"string\")),\n \"spans\": datasets.Sequence(datasets.Value(\"string\")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={\"filepath\": dl_path[\"train\"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={\"filepath\": dl_path[\"validation\"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, \"r\", encoding=\"utf-8\") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n" @pytest.fixture def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def _SCREAMING_SNAKE_CASE ( lowercase : Optional[Any] , lowercase : Optional[int] , lowercase : List[Any] ): '''simple docstring''' lowerCamelCase_ = dataset_loading_script_name lowerCamelCase_ = tmp_path / 'datasets' / script_name script_dir.mkdir(parents=lowercase ) lowerCamelCase_ = script_dir / f"""{script_name}.py""" with open(lowercase , 'w' ) as f: f.write(lowercase ) return str(lowercase )
716
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : str = logging.get_logger(__name__) lowerCamelCase : List[str] = { "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json", } class A( UpperCamelCase ): '''simple docstring''' UpperCamelCase = '''gpt_neox_japanese''' def __init__( self : int , A_ : Dict=32000 , A_ : List[Any]=2560 , A_ : Dict=32 , A_ : Union[str, Any]=32 , A_ : List[Any]=4 , A_ : List[str]="gelu" , A_ : Dict=1.00 , A_ : int=10000 , A_ : Dict=2048 , A_ : Dict=0.02 , A_ : Any=1E-5 , A_ : Union[str, Any]=True , A_ : int=31996 , A_ : List[str]=31999 , A_ : List[Any]=0.1 , A_ : List[Any]=0.0 , **A_ : Tuple , ) -> Dict: """simple docstring""" super().__init__(bos_token_id=A_ , eos_token_id=A_ , **A_ ) lowerCamelCase_ = vocab_size lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = hidden_size lowerCamelCase_ = num_hidden_layers lowerCamelCase_ = num_attention_heads lowerCamelCase_ = intermediate_multiple_size lowerCamelCase_ = hidden_act lowerCamelCase_ = rotary_pct lowerCamelCase_ = rotary_emb_base lowerCamelCase_ = initializer_range lowerCamelCase_ = layer_norm_eps lowerCamelCase_ = use_cache lowerCamelCase_ = attention_dropout lowerCamelCase_ = hidden_dropout
651
0
import math from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : Any = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'facebook/data2vec-base-960h': 'https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json', # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class UpperCamelCase_ ( __UpperCamelCase ): '''simple docstring''' UpperCamelCase_ = '''data2vec-audio''' def __init__( self , UpperCamelCase=32 , UpperCamelCase=7_68 , UpperCamelCase=12 , UpperCamelCase=12 , UpperCamelCase=30_72 , UpperCamelCase="gelu" , UpperCamelCase=0.1 , UpperCamelCase=0.1 , UpperCamelCase=0.1 , UpperCamelCase=0.0 , UpperCamelCase=0.1 , UpperCamelCase=0.1 , UpperCamelCase=0.02 , UpperCamelCase=1E-5 , UpperCamelCase="gelu" , UpperCamelCase=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) , UpperCamelCase=(5, 2, 2, 2, 2, 2, 2) , UpperCamelCase=(10, 3, 3, 3, 3, 2, 2) , UpperCamelCase=False , UpperCamelCase=16 , UpperCamelCase=19 , UpperCamelCase=5 , UpperCamelCase=0.05 , UpperCamelCase=10 , UpperCamelCase=2 , UpperCamelCase=0.0 , UpperCamelCase=10 , UpperCamelCase=0 , UpperCamelCase="sum" , UpperCamelCase=False , UpperCamelCase=False , UpperCamelCase=2_56 , UpperCamelCase=(5_12, 5_12, 5_12, 5_12, 15_00) , UpperCamelCase=(5, 3, 3, 1, 1) , UpperCamelCase=(1, 2, 3, 1, 1) , UpperCamelCase=5_12 , UpperCamelCase=0 , UpperCamelCase=1 , UpperCamelCase=2 , UpperCamelCase=False , UpperCamelCase=3 , UpperCamelCase=2 , UpperCamelCase=3 , UpperCamelCase=None , **UpperCamelCase , ) -> List[Any]: super().__init__(**_SCREAMING_SNAKE_CASE , pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE) UpperCamelCase__ : str = hidden_size UpperCamelCase__ : Union[str, Any] = feat_extract_activation UpperCamelCase__ : Tuple = list(_SCREAMING_SNAKE_CASE) UpperCamelCase__ : List[str] = list(_SCREAMING_SNAKE_CASE) UpperCamelCase__ : List[Any] = list(_SCREAMING_SNAKE_CASE) UpperCamelCase__ : Optional[Any] = conv_bias UpperCamelCase__ : Optional[Any] = num_conv_pos_embeddings UpperCamelCase__ : str = num_conv_pos_embedding_groups UpperCamelCase__ : Dict = conv_pos_kernel_size UpperCamelCase__ : Optional[int] = len(self.conv_dim) UpperCamelCase__ : Any = num_hidden_layers UpperCamelCase__ : Any = intermediate_size UpperCamelCase__ : Optional[Any] = hidden_act UpperCamelCase__ : Tuple = num_attention_heads UpperCamelCase__ : Any = hidden_dropout UpperCamelCase__ : Optional[int] = attention_dropout UpperCamelCase__ : Optional[Any] = activation_dropout UpperCamelCase__ : Dict = feat_proj_dropout UpperCamelCase__ : Optional[int] = final_dropout UpperCamelCase__ : str = layerdrop UpperCamelCase__ : List[str] = layer_norm_eps UpperCamelCase__ : Tuple = initializer_range UpperCamelCase__ : Optional[int] = vocab_size UpperCamelCase__ : Tuple = use_weighted_layer_sum if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' F""" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,""" F""" `len(config.conv_kernel) = {len(self.conv_kernel)}`.""") # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 UpperCamelCase__ : List[str] = mask_time_prob UpperCamelCase__ : Dict = mask_time_length UpperCamelCase__ : List[str] = mask_time_min_masks UpperCamelCase__ : Optional[Any] = mask_feature_prob UpperCamelCase__ : Dict = mask_feature_length UpperCamelCase__ : List[str] = mask_feature_min_masks # ctc loss UpperCamelCase__ : List[str] = ctc_loss_reduction UpperCamelCase__ : Optional[int] = ctc_zero_infinity # adapter UpperCamelCase__ : Optional[int] = add_adapter UpperCamelCase__ : Optional[Any] = adapter_kernel_size UpperCamelCase__ : Union[str, Any] = adapter_stride UpperCamelCase__ : Union[str, Any] = num_adapter_layers UpperCamelCase__ : List[str] = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. UpperCamelCase__ : Optional[Any] = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. UpperCamelCase__ : Dict = list(_SCREAMING_SNAKE_CASE) UpperCamelCase__ : Any = list(_SCREAMING_SNAKE_CASE) UpperCamelCase__ : str = list(_SCREAMING_SNAKE_CASE) UpperCamelCase__ : Tuple = xvector_output_dim @property def lowerCAmelCase__ ( self) -> int: return math.prod(self.conv_stride)
410
def A_ ( a ): """simple docstring""" if p < 2: raise ValueError('p should not be less than 2!' ) elif p == 2: return True SCREAMING_SNAKE_CASE_ : Tuple = 4 SCREAMING_SNAKE_CASE_ : List[str] = (1 << p) - 1 for _ in range(p - 2 ): SCREAMING_SNAKE_CASE_ : Optional[Any] = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
511
0
'''simple docstring''' import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class a__ ( UpperCAmelCase_ , unittest.TestCase ): _a : Dict = RobertaTokenizer _a : Union[str, Any] = RobertaTokenizerFast _a : List[str] = True _a : List[Any] = {'cls_token': '<s>'} def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __lowerCAmelCase = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', ] __lowerCAmelCase = dict(zip(_lowercase , range(len(_lowercase ) ) ) ) __lowerCAmelCase = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __lowerCAmelCase = {'unk_token': '<unk>'} __lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __lowerCAmelCase = 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(_lowercase ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(_lowercase ) ) def __SCREAMING_SNAKE_CASE( self , **_A ): """simple docstring""" kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **_lowercase ) def __SCREAMING_SNAKE_CASE( self , **_A ): """simple docstring""" kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **_lowercase ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = 'lower newer' __lowerCAmelCase = 'lower newer' return input_text, output_text def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) __lowerCAmelCase = 'lower newer' __lowerCAmelCase = ['l', 'o', 'w', 'er', '\u0120', 'n', 'e', 'w', 'er'] __lowerCAmelCase = tokenizer.tokenize(_lowercase ) # , add_prefix_space=True) self.assertListEqual(_lowercase , _lowercase ) __lowerCAmelCase = tokens + [tokenizer.unk_token] __lowerCAmelCase = [0, 1, 2, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowercase ) , _lowercase ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.get_tokenizer() self.assertListEqual(tokenizer.encode("Hello world!" , add_special_tokens=_lowercase ) , [0, 3_1_4_1_4, 2_3_2, 3_2_8, 2] ) self.assertListEqual( tokenizer.encode("Hello world! cécé herlolip 418" , add_special_tokens=_lowercase ) , [0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2] , ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.tokenizer_class.from_pretrained("roberta-base" ) __lowerCAmelCase = tokenizer.encode("sequence builders" , add_special_tokens=_lowercase ) __lowerCAmelCase = tokenizer.encode("multi-sequence build" , add_special_tokens=_lowercase ) __lowerCAmelCase = tokenizer.encode( "sequence builders" , add_special_tokens=_lowercase , add_prefix_space=_lowercase ) __lowerCAmelCase = tokenizer.encode( "sequence builders" , "multi-sequence build" , add_special_tokens=_lowercase , add_prefix_space=_lowercase ) __lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(_lowercase ) __lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(_lowercase , _lowercase ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = 'Encode this sequence.' __lowerCAmelCase = tokenizer.byte_encoder[' '.encode("utf-8" )[0]] # Testing encoder arguments __lowerCAmelCase = tokenizer.encode(_lowercase , add_special_tokens=_lowercase , add_prefix_space=_lowercase ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(_lowercase , _lowercase ) __lowerCAmelCase = tokenizer.encode(_lowercase , add_special_tokens=_lowercase , add_prefix_space=_lowercase ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(_lowercase , _lowercase ) tokenizer.add_special_tokens({"bos_token": "<s>"} ) __lowerCAmelCase = tokenizer.encode(_lowercase , add_special_tokens=_lowercase ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(_lowercase , _lowercase ) # Testing spaces after special tokens __lowerCAmelCase = '<mask>' tokenizer.add_special_tokens( {"mask_token": AddedToken(_lowercase , lstrip=_lowercase , rstrip=_lowercase )} ) # mask token has a left space __lowerCAmelCase = tokenizer.convert_tokens_to_ids(_lowercase ) __lowerCAmelCase = 'Encode <mask> sequence' __lowerCAmelCase = 'Encode <mask>sequence' __lowerCAmelCase = tokenizer.encode(_lowercase ) __lowerCAmelCase = encoded.index(_lowercase ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(_lowercase , _lowercase ) __lowerCAmelCase = tokenizer.encode(_lowercase ) __lowerCAmelCase = encoded.index(_lowercase ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(_lowercase , _lowercase ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __lowerCAmelCase = self.rust_tokenizer_class.from_pretrained(_lowercase , **_lowercase ) __lowerCAmelCase = self.tokenizer_class.from_pretrained(_lowercase , **_lowercase ) __lowerCAmelCase = 'A, <mask> AllenNLP sentence.' __lowerCAmelCase = tokenizer_r.encode_plus(_lowercase , add_special_tokens=_lowercase , return_token_type_ids=_lowercase ) __lowerCAmelCase = tokenizer_p.encode_plus(_lowercase , add_special_tokens=_lowercase , return_token_type_ids=_lowercase ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["token_type_ids"] ) , sum(tokens_p["token_type_ids"] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["attention_mask"] ) / len(tokens_r["attention_mask"] ) , sum(tokens_p["attention_mask"] ) / len(tokens_p["attention_mask"] ) , ) __lowerCAmelCase = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"] ) __lowerCAmelCase = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["input_ids"] , [0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] ) self.assertSequenceEqual(tokens_r["input_ids"] , [0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] ) self.assertSequenceEqual( _lowercase , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] ) self.assertSequenceEqual( _lowercase , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): __lowerCAmelCase = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) __lowerCAmelCase = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) __lowerCAmelCase = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["add_prefix_space"] , _lowercase ) self.assertEqual(post_processor_state["add_prefix_space"] , _lowercase ) self.assertEqual(post_processor_state["trim_offsets"] , _lowercase ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __lowerCAmelCase = 'hello' # `hello` is a token in the vocabulary of `pretrained_name` __lowerCAmelCase = f"""{text_of_1_token} {text_of_1_token}""" __lowerCAmelCase = self.rust_tokenizer_class.from_pretrained( _lowercase , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) __lowerCAmelCase = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_lowercase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_lowercase ) + 1, len(_lowercase ) + 1 + len(_lowercase )) , ) __lowerCAmelCase = self.rust_tokenizer_class.from_pretrained( _lowercase , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) __lowerCAmelCase = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_lowercase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_lowercase ) + 1, len(_lowercase ) + 1 + len(_lowercase )) , ) __lowerCAmelCase = self.rust_tokenizer_class.from_pretrained( _lowercase , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) __lowerCAmelCase = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_lowercase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_lowercase ), len(_lowercase ) + 1 + len(_lowercase )) , ) __lowerCAmelCase = self.rust_tokenizer_class.from_pretrained( _lowercase , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) __lowerCAmelCase = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_lowercase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_lowercase ), len(_lowercase ) + 1 + len(_lowercase )) , ) __lowerCAmelCase = f""" {text}""" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) __lowerCAmelCase = self.rust_tokenizer_class.from_pretrained( _lowercase , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) __lowerCAmelCase = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(_lowercase )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(_lowercase ) + 1, 1 + len(_lowercase ) + 1 + len(_lowercase )) , ) __lowerCAmelCase = self.rust_tokenizer_class.from_pretrained( _lowercase , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) __lowerCAmelCase = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(_lowercase )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(_lowercase ), 1 + len(_lowercase ) + 1 + len(_lowercase )) , ) __lowerCAmelCase = self.rust_tokenizer_class.from_pretrained( _lowercase , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) __lowerCAmelCase = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(_lowercase )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(_lowercase ), 1 + len(_lowercase ) + 1 + len(_lowercase )) , )
707
from __future__ import annotations from collections.abc import Iterator from typing import Any class a__ : def __init__( self , _A ): """simple docstring""" __lowerCAmelCase = data __lowerCAmelCase = None class a__ : def __init__( self ): """simple docstring""" __lowerCAmelCase = None __lowerCAmelCase = None def __iter__( self ): """simple docstring""" __lowerCAmelCase = self.head while self.head: yield node.data __lowerCAmelCase = node.next if node == self.head: break def __len__( self ): """simple docstring""" return sum(1 for _ in self ) def __repr__( self ): """simple docstring""" return "->".join(str(_A ) for item in iter(self ) ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" self.insert_nth(len(self ) , _A ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" self.insert_nth(0 , _A ) def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" if index < 0 or index > len(self ): raise IndexError("list index out of range." ) __lowerCAmelCase = Node(_A ) if self.head is None: __lowerCAmelCase = new_node # first node points itself __lowerCAmelCase = __lowerCAmelCase = new_node elif index == 0: # insert at head __lowerCAmelCase = self.head __lowerCAmelCase = __lowerCAmelCase = new_node else: __lowerCAmelCase = self.head for _ in range(index - 1 ): __lowerCAmelCase = temp.next __lowerCAmelCase = temp.next __lowerCAmelCase = new_node if index == len(self ) - 1: # insert at tail __lowerCAmelCase = new_node def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.delete_nth(0 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.delete_nth(len(self ) - 1 ) def __SCREAMING_SNAKE_CASE( self , _A = 0 ): """simple docstring""" if not 0 <= index < len(self ): raise IndexError("list index out of range." ) __lowerCAmelCase = self.head if self.head == self.tail: # just one node __lowerCAmelCase = __lowerCAmelCase = None elif index == 0: # delete head node __lowerCAmelCase = self.tail.next.next __lowerCAmelCase = self.head.next else: __lowerCAmelCase = self.head for _ in range(index - 1 ): __lowerCAmelCase = temp.next __lowerCAmelCase = temp.next __lowerCAmelCase = temp.next.next if index == len(self ) - 1: # delete at tail __lowerCAmelCase = temp return delete_node.data def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return len(self ) == 0 def _a ( ): __lowerCAmelCase = CircularLinkedList() assert len(SCREAMING_SNAKE_CASE_ ) == 0 assert circular_linked_list.is_empty() is True assert str(SCREAMING_SNAKE_CASE_ ) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1 ) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0 ) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5 ): assert len(SCREAMING_SNAKE_CASE_ ) == i circular_linked_list.insert_nth(SCREAMING_SNAKE_CASE_ , i + 1 ) assert str(SCREAMING_SNAKE_CASE_ ) == "->".join(str(SCREAMING_SNAKE_CASE_ ) for i in range(1 , 6 ) ) circular_linked_list.insert_tail(6 ) assert str(SCREAMING_SNAKE_CASE_ ) == "->".join(str(SCREAMING_SNAKE_CASE_ ) for i in range(1 , 7 ) ) circular_linked_list.insert_head(0 ) assert str(SCREAMING_SNAKE_CASE_ ) == "->".join(str(SCREAMING_SNAKE_CASE_ ) for i in range(0 , 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(SCREAMING_SNAKE_CASE_ ) == "->".join(str(SCREAMING_SNAKE_CASE_ ) for i in range(1 , 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2 , 3 ) assert str(SCREAMING_SNAKE_CASE_ ) == "->".join(str(SCREAMING_SNAKE_CASE_ ) for i in range(1 , 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
552
0
"""simple docstring""" def a ( __snake_case : int, __snake_case : int ): '''simple docstring''' while second != 0: UpperCAmelCase_ :Tuple = first & second first ^= second UpperCAmelCase_ :Optional[Any] = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() __lowerCamelCase = int(input("Enter the first number: ").strip()) __lowerCamelCase = int(input("Enter the second number: ").strip()) print(f'''{add(first, second) = }''')
608
'''simple docstring''' from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline _lowercase = logging.get_logger(__name__) @add_end_docstrings(_SCREAMING_SNAKE_CASE ) class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , **_lowercase ): """simple docstring""" super().__init__(**_lowercase ) if self.framework != "pt": raise ValueError(F'The {self.__class__} is only available in PyTorch.' ) # No specific FOR_XXX available yet def __call__( self , _lowercase , **_lowercase ): """simple docstring""" return super().__call__(_lowercase , **_lowercase ) def _lowercase ( self , **_lowercase ): """simple docstring""" _lowerCAmelCase = {} if "candidate_labels" in kwargs: _lowerCAmelCase = kwargs["""candidate_labels"""] if "hypothesis_template" in kwargs: _lowerCAmelCase = kwargs["""hypothesis_template"""] return preprocess_params, {}, {} def _lowercase ( self , _lowercase , _lowercase=None , _lowercase="This is a sound of {}." ): """simple docstring""" if isinstance(_lowercase , _lowercase ): if audio.startswith("""http://""" ) or audio.startswith("""https://""" ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png _lowerCAmelCase = requests.get(_lowercase ).content else: with open(_lowercase , """rb""" ) as f: _lowerCAmelCase = f.read() if isinstance(_lowercase , _lowercase ): _lowerCAmelCase = ffmpeg_read(_lowercase , self.feature_extractor.sampling_rate ) if not isinstance(_lowercase , np.ndarray ): raise ValueError("""We expect a numpy ndarray as input""" ) if len(audio.shape ) != 1: raise ValueError("""We expect a single channel audio input for ZeroShotAudioClassificationPipeline""" ) _lowerCAmelCase = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors="""pt""" ) _lowerCAmelCase = candidate_labels _lowerCAmelCase = [hypothesis_template.format(_lowercase ) for x in candidate_labels] _lowerCAmelCase = self.tokenizer(_lowercase , return_tensors=self.framework , padding=_lowercase ) _lowerCAmelCase = [text_inputs] return inputs def _lowercase ( self , _lowercase ): """simple docstring""" _lowerCAmelCase = model_inputs.pop("""candidate_labels""" ) _lowerCAmelCase = model_inputs.pop("""text_inputs""" ) if isinstance(text_inputs[0] , _lowercase ): _lowerCAmelCase = text_inputs[0] else: # Batching case. _lowerCAmelCase = text_inputs[0][0] _lowerCAmelCase = self.model(**_lowercase , **_lowercase ) _lowerCAmelCase = { """candidate_labels""": candidate_labels, """logits""": outputs.logits_per_audio, } return model_outputs def _lowercase ( self , _lowercase ): """simple docstring""" _lowerCAmelCase = model_outputs.pop("""candidate_labels""" ) _lowerCAmelCase = model_outputs["""logits"""][0] if self.framework == "pt": _lowerCAmelCase = logits.softmax(dim=0 ) _lowerCAmelCase = probs.tolist() else: raise ValueError("""`tf` framework not supported.""" ) _lowerCAmelCase = [ {"""score""": score, """label""": candidate_label} for score, candidate_label in sorted(zip(_lowercase , _lowercase ) , key=lambda _lowercase : -x[0] ) ] return result
5
0
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class _UpperCAmelCase ( lowerCAmelCase__): _lowerCAmelCase : torch.FloatTensor _lowerCAmelCase : Optional[torch.FloatTensor] = None def __lowercase ( _a , _a=0.999 , _a="cosine" , ): if alpha_transform_type == "cosine": def alpha_bar_fn(_a ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(_a ): return math.exp(t * -12.0 ) else: raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}" ) snake_case_ : Union[str, Any] = [] for i in range(_a ): snake_case_ : Union[str, Any] = i / num_diffusion_timesteps snake_case_ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(_a ) / alpha_bar_fn(_a ) , _a ) ) return torch.tensor(_a , dtype=torch.floataa ) class _UpperCAmelCase ( lowerCAmelCase__ , lowerCAmelCase__): _lowerCAmelCase : Union[str, Any] = 1 @register_to_config def __init__( self : Tuple , lowercase_ : int = 1000 , lowercase_ : float = 0.00_01 , lowercase_ : float = 0.02 , lowercase_ : str = "linear" , lowercase_ : Optional[Union[np.ndarray, List[float]]] = None , lowercase_ : bool = True , lowercase_ : bool = True , lowercase_ : int = 0 , lowercase_ : str = "epsilon" , lowercase_ : float = 1.0 , **lowercase_ : int , ): if kwargs.get('''set_alpha_to_one''' , lowercase_ ) is not None: snake_case_ : int = ( '''The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.''' ) deprecate('''set_alpha_to_one''' , '''1.0.0''' , lowercase_ , standard_warn=lowercase_ ) snake_case_ : Dict = kwargs['''set_alpha_to_one'''] if trained_betas is not None: snake_case_ : str = torch.tensor(lowercase_ , dtype=torch.floataa ) elif beta_schedule == "linear": snake_case_ : List[str] = torch.linspace(lowercase_ , lowercase_ , lowercase_ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. snake_case_ : Dict = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , lowercase_ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule snake_case_ : Tuple = betas_for_alpha_bar(lowercase_ ) else: raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}" ) snake_case_ : List[Any] = 1.0 - self.betas snake_case_ : Optional[Any] = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. snake_case_ : str = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution snake_case_ : str = 1.0 # setable values snake_case_ : Dict = None snake_case_ : Tuple = torch.from_numpy(np.arange(0 , lowercase_ ).copy().astype(np.intaa ) ) def _snake_case ( self : List[str] , lowercase_ : torch.FloatTensor , lowercase_ : Optional[int] = None ): return sample def _snake_case ( self : List[str] , lowercase_ : int , lowercase_ : Union[str, torch.device] = None ): if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:" f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle" f" maximal {self.config.num_train_timesteps} timesteps." ) snake_case_ : Optional[Any] = num_inference_steps snake_case_ : Union[str, Any] = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 snake_case_ : str = (np.arange(0 , lowercase_ ) * step_ratio).round().copy().astype(np.intaa ) snake_case_ : List[Any] = torch.from_numpy(lowercase_ ).to(lowercase_ ) self.timesteps += self.config.steps_offset def _snake_case ( self : Tuple , lowercase_ : torch.FloatTensor , lowercase_ : int , lowercase_ : torch.FloatTensor , lowercase_ : float = 0.0 , lowercase_ : bool = False , lowercase_ : Optional[torch.FloatTensor] = None , lowercase_ : bool = True , ): # 1. get previous step value (=t+1) snake_case_ : str = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process snake_case_ : str = self.alphas_cumprod[timestep] snake_case_ : Optional[Any] = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) snake_case_ : Dict = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": snake_case_ : Union[str, Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 snake_case_ : List[Any] = model_output elif self.config.prediction_type == "sample": snake_case_ : List[Any] = model_output snake_case_ : Dict = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": snake_case_ : Any = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output snake_case_ : Any = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or" ''' `v_prediction`''' ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: snake_case_ : List[Any] = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf snake_case_ : Optional[int] = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf snake_case_ : int = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=lowercase_ , pred_original_sample=lowercase_ ) def __len__( self : str ): return self.config.num_train_timesteps
485
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) 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 lowercase__ : Optional[Any] = 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-pretraining/requirements.txt''') @dataclass class _UpperCAmelCase : _lowerCAmelCase : Optional[str] = field( default="""cifar10""" , metadata={"""help""": """Name of a dataset from the datasets package"""}) _lowerCAmelCase : Optional[str] = field( default=lowerCAmelCase__ , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}) _lowerCAmelCase : Optional[str] = field( default=lowerCAmelCase__ , metadata={"""help""": """The column name of the images in the files."""}) _lowerCAmelCase : Optional[str] = field(default=lowerCAmelCase__ , metadata={"""help""": """A folder containing the training data."""}) _lowerCAmelCase : Optional[str] = field(default=lowerCAmelCase__ , metadata={"""help""": """A folder containing the validation data."""}) _lowerCAmelCase : Optional[float] = field( default=0.15 , metadata={"""help""": """Percent to split off of train for validation."""}) _lowerCAmelCase : Optional[int] = field( default=lowerCAmelCase__ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) _lowerCAmelCase : Optional[int] = field( default=lowerCAmelCase__ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) def _snake_case ( self : Union[str, Any] ): snake_case_ : List[Any] = {} if self.train_dir is not None: snake_case_ : str = self.train_dir if self.validation_dir is not None: snake_case_ : Union[str, Any] = self.validation_dir snake_case_ : Tuple = data_files if data_files else None @dataclass class _UpperCAmelCase : _lowerCAmelCase : str = field( default=lowerCAmelCase__ , metadata={ """help""": ( """The model checkpoint for weights initialization.Don't set if you want to train a model from scratch.""" ) } , ) _lowerCAmelCase : Optional[str] = field( default=lowerCAmelCase__ , metadata={"""help""": """Pretrained config name or path if not the same as model_name_or_path"""}) _lowerCAmelCase : Optional[str] = field( default=lowerCAmelCase__ , metadata={ """help""": ( """Override some existing default config settings when a model is trained from scratch. Example: """ """n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index""" ) } , ) _lowerCAmelCase : Optional[str] = field( default=lowerCAmelCase__ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from s3"""}) _lowerCAmelCase : str = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) _lowerCAmelCase : str = field(default=lowerCAmelCase__ , metadata={"""help""": """Name or path of preprocessor config."""}) _lowerCAmelCase : bool = field( default=lowerCAmelCase__ , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) _lowerCAmelCase : float = field( default=0.75 , metadata={"""help""": """The ratio of the number of masked tokens in the input sequence."""}) _lowerCAmelCase : bool = field( default=lowerCAmelCase__ , metadata={"""help""": """Whether or not to train with normalized pixel values as target."""}) @dataclass class _UpperCAmelCase ( lowerCAmelCase__): _lowerCAmelCase : float = field( default=1e-3 , metadata={"""help""": """Base learning rate: absolute_lr = base_lr * total_batch_size / 256."""}) def __lowercase ( _a ): snake_case_ : Tuple = torch.stack([example['''pixel_values'''] for example in examples] ) return {"pixel_values": pixel_values} def __lowercase ( ): # 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. snake_case_ : Optional[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) 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. snake_case_, snake_case_, snake_case_ : Optional[Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case_, snake_case_, snake_case_ : List[Any] = 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_mae''' , _a , _a ) # 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() snake_case_ : List[str] = training_args.get_process_log_level() logger.setLevel(_a ) transformers.utils.logging.set_verbosity(_a ) 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. snake_case_ : Any = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: snake_case_ : int = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Initialize our dataset. snake_case_ : Optional[int] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. snake_case_ : Optional[Any] = None if '''validation''' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , _a ) and data_args.train_val_split > 0.0: snake_case_ : List[Any] = ds['''train'''].train_test_split(data_args.train_val_split ) snake_case_ : Tuple = split['''train'''] snake_case_ : str = split['''test'''] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case_ : Optional[int] = { '''cache_dir''': model_args.cache_dir, '''revision''': model_args.model_revision, '''use_auth_token''': True if model_args.use_auth_token else None, } if model_args.config_name: snake_case_ : List[Any] = ViTMAEConfig.from_pretrained(model_args.config_name , **_a ) elif model_args.model_name_or_path: snake_case_ : Dict = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **_a ) else: snake_case_ : Optional[int] = ViTMAEConfig() logger.warning('''You are instantiating a new config instance from scratch.''' ) if model_args.config_overrides is not None: logger.info(f"Overriding config: {model_args.config_overrides}" ) config.update_from_string(model_args.config_overrides ) logger.info(f"New config: {config}" ) # adapt config config.update( { '''mask_ratio''': model_args.mask_ratio, '''norm_pix_loss''': model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: snake_case_ : Union[str, Any] = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **_a ) elif model_args.model_name_or_path: snake_case_ : Union[str, Any] = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **_a ) else: snake_case_ : Tuple = ViTImageProcessor() # create model if model_args.model_name_or_path: snake_case_ : Tuple = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=_a , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('''Training new model from scratch''' ) snake_case_ : Tuple = ViTMAEForPreTraining(_a ) if training_args.do_train: snake_case_ : List[str] = ds['''train'''].column_names else: snake_case_ : Optional[Any] = ds['''validation'''].column_names if data_args.image_column_name is not None: snake_case_ : Tuple = data_args.image_column_name elif "image" in column_names: snake_case_ : Tuple = '''image''' elif "img" in column_names: snake_case_ : str = '''img''' else: snake_case_ : Union[str, Any] = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: snake_case_ : str = image_processor.size['''shortest_edge'''] else: snake_case_ : Dict = (image_processor.size['''height'''], image_processor.size['''width''']) snake_case_ : str = Compose( [ Lambda(lambda _a : img.convert('''RGB''' ) if img.mode != "RGB" else img ), RandomResizedCrop(_a , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(_a ): snake_case_ : Tuple = [transforms(_a ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError('''--do_train requires a train dataset''' ) if data_args.max_train_samples is not None: snake_case_ : List[str] = ds['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(_a ) if training_args.do_eval: if "validation" not in ds: raise ValueError('''--do_eval requires a validation dataset''' ) if data_args.max_eval_samples is not None: snake_case_ : Optional[Any] = ( ds['''validation'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(_a ) # Compute absolute learning rate snake_case_ : Any = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: snake_case_ : Union[str, Any] = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer snake_case_ : str = Trainer( model=_a , args=_a , train_dataset=ds['''train'''] if training_args.do_train else None , eval_dataset=ds['''validation'''] if training_args.do_eval else None , tokenizer=_a , data_collator=_a , ) # Training if training_args.do_train: snake_case_ : Any = None if training_args.resume_from_checkpoint is not None: snake_case_ : Optional[int] = training_args.resume_from_checkpoint elif last_checkpoint is not None: snake_case_ : str = last_checkpoint snake_case_ : List[str] = trainer.train(resume_from_checkpoint=_a ) 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: snake_case_ : Any = trainer.evaluate() trainer.log_metrics('''eval''' , _a ) trainer.save_metrics('''eval''' , _a ) # Write model card and (optionally) push to hub snake_case_ : Optional[int] = { '''tasks''': '''masked-auto-encoding''', '''dataset''': data_args.dataset_name, '''tags''': ['''masked-auto-encoding'''], } if training_args.push_to_hub: trainer.push_to_hub(**_a ) else: trainer.create_model_card(**_a ) def __lowercase ( _a ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
485
1
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..utils import cached_file # docstyle-ignore A = ''' Human: <<task>> Assistant: ''' A = '''huggingface-tools/default-prompts''' A = {'''chat''': '''chat_prompt_template.txt''', '''run''': '''run_prompt_template.txt'''} def SCREAMING_SNAKE_CASE ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Dict , lowerCAmelCase__ : int="run") -> List[str]: '''simple docstring''' if prompt_or_repo_id is None: _lowercase : Any = DEFAULT_PROMPTS_REPO # prompt is considered a repo ID when it does not contain any kind of space if re.search('\\s' , lowerCAmelCase__) is not None: return prompt_or_repo_id _lowercase : List[str] = cached_file( lowerCAmelCase__ , PROMPT_FILES[mode] , repo_type='dataset' , user_agent={'agent': agent_name}) with open(lowerCAmelCase__ , 'r' , encoding='utf-8') as f: return f.read()
125
def __magic_name__ ( lowercase = 100 ) -> int: """simple docstring""" lowercase_ : Dict = (n * (n + 1) // 2) ** 2 lowercase_ : List[str] = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(F'''{solution() = }''')
458
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: a_ : Union[str, Any] = TFXLMRobertaModel.from_pretrained('''jplu/tf-xlm-roberta-base''' ) a_ : str = { '''input_ids''': tf.convert_to_tensor([[0, 2646, 1_0269, 83, 9_9942, 2]] , dtype=tf.intaa ), # "My dog is cute" '''attention_mask''': tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } a_ : str = model(__SCREAMING_SNAKE_CASE )['''last_hidden_state'''] a_ : Optional[int] = tf.TensorShape((1, 6, 768) ) self.assertEqual(output.shape , __SCREAMING_SNAKE_CASE ) # compare the actual values for a slice. a_ : Tuple = tf.convert_to_tensor( [ [ [0.068_1762, 0.1089_4451, 0.0677_2504], [-0.0642_3668, 0.0236_6615, 0.0432_9344], [-0.0605_7295, 0.0997_4135, -0.0007_0584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
666
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { 'configuration_git': ['GIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GitConfig', 'GitVisionConfig'], 'processing_git': ['GitProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ 'GIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'GitForCausalLM', 'GitModel', 'GitPreTrainedModel', 'GitVisionModel', ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
666
1
def __lowerCAmelCase ( __lowerCamelCase : list ) -> List[str]: __lowerCAmelCase =False while is_sorted is False: # Until all the indices are traversed keep looping __lowerCAmelCase =True for i in range(0 , len(_A ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: __lowerCAmelCase , __lowerCAmelCase =input_list[i + 1], input_list[i] # swapping if elements not in order __lowerCAmelCase =False for i in range(1 , len(_A ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: __lowerCAmelCase , __lowerCAmelCase =input_list[i + 1], input_list[i] # swapping if elements not in order __lowerCAmelCase =False return input_list if __name__ == "__main__": print('''Enter list to be sorted''') lowercase_ = [int(x) for x in input().split()] # inputing elements of the list in one line lowercase_ = odd_even_sort(input_list) print('''The sorted list is''') print(sorted_list)
354
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available _a : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Dict = ['GPTSw3Tokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys _a : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
479
0
'''simple docstring''' from math import ceil def UpperCAmelCase_ ( __lowercase : int = 1001 ) -> int: '''simple docstring''' _UpperCAmelCase = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): _UpperCAmelCase = 2 * i + 1 _UpperCAmelCase = 2 * i _UpperCAmelCase = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: __SCREAMING_SNAKE_CASE :Dict = int(sys.argv[1]) print(solution(n)) except ValueError: print('''Invalid entry - please enter a number''')
119
'''simple docstring''' import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def UpperCAmelCase_ ( __lowercase : str ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = fname.split(os.path.sep )[-1] return re.search(r"^(.*)_\d+\.jpg$" , __lowercase ).groups()[0] class A_ ( lowerCAmelCase_ ): def __init__( self : List[str] , snake_case_ : Union[str, Any] , snake_case_ : int=None , snake_case_ : List[Any]=None ): _UpperCAmelCase = file_names _UpperCAmelCase = image_transform _UpperCAmelCase = label_to_id def __len__( self : Union[str, Any] ): return len(self.file_names ) def __getitem__( self : Any , snake_case_ : Tuple ): _UpperCAmelCase = self.file_names[idx] _UpperCAmelCase = PIL.Image.open(snake_case_ ) _UpperCAmelCase = raw_image.convert("RGB" ) if self.image_transform is not None: _UpperCAmelCase = self.image_transform(snake_case_ ) _UpperCAmelCase = extract_label(snake_case_ ) if self.label_to_id is not None: _UpperCAmelCase = self.label_to_id[label] return {"image": image, "label": label} def UpperCAmelCase_ ( __lowercase : List[Any] , __lowercase : Dict ) -> Optional[int]: '''simple docstring''' if args.with_tracking: _UpperCAmelCase = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="all" , project_dir=args.project_dir ) else: _UpperCAmelCase = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _UpperCAmelCase = config["lr"] _UpperCAmelCase = int(config["num_epochs"] ) _UpperCAmelCase = int(config["seed"] ) _UpperCAmelCase = int(config["batch_size"] ) _UpperCAmelCase = config["image_size"] if not isinstance(__lowercase , (list, tuple) ): _UpperCAmelCase = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps , "isdigit" ): if args.checkpointing_steps == "epoch": _UpperCAmelCase = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): _UpperCAmelCase = int(args.checkpointing_steps ) else: raise ValueError( f'Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.' ) else: _UpperCAmelCase = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: _UpperCAmelCase = os.path.split(__lowercase )[-1].split("." )[0] accelerator.init_trackers(__lowercase , __lowercase ) # Grab all the image filenames _UpperCAmelCase = [os.path.join(args.data_dir , __lowercase ) for fname in os.listdir(args.data_dir ) if fname.endswith(".jpg" )] # Build the label correspondences _UpperCAmelCase = [extract_label(__lowercase ) for fname in file_names] _UpperCAmelCase = list(set(__lowercase ) ) id_to_label.sort() _UpperCAmelCase = {lbl: i for i, lbl in enumerate(__lowercase )} # Set the seed before splitting the data. np.random.seed(__lowercase ) torch.manual_seed(__lowercase ) torch.cuda.manual_seed_all(__lowercase ) # Split our filenames between train and validation _UpperCAmelCase = np.random.permutation(len(__lowercase ) ) _UpperCAmelCase = int(0.8 * len(__lowercase ) ) _UpperCAmelCase = random_perm[:cut] _UpperCAmelCase = random_perm[cut:] # For training we use a simple RandomResizedCrop _UpperCAmelCase = Compose([RandomResizedCrop(__lowercase , scale=(0.5, 1.0) ), ToTensor()] ) _UpperCAmelCase = PetsDataset( [file_names[i] for i in train_split] , image_transform=__lowercase , label_to_id=__lowercase ) # For evaluation, we use a deterministic Resize _UpperCAmelCase = Compose([Resize(__lowercase ), ToTensor()] ) _UpperCAmelCase = PetsDataset([file_names[i] for i in eval_split] , image_transform=__lowercase , label_to_id=__lowercase ) # Instantiate dataloaders. _UpperCAmelCase = DataLoader(__lowercase , shuffle=__lowercase , batch_size=__lowercase , num_workers=4 ) _UpperCAmelCase = DataLoader(__lowercase , shuffle=__lowercase , batch_size=__lowercase , num_workers=4 ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _UpperCAmelCase = create_model("resnet50d" , pretrained=__lowercase , num_classes=len(__lowercase ) ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _UpperCAmelCase = model.to(accelerator.device ) # Freezing the base model for param in model.parameters(): _UpperCAmelCase = False for param in model.get_classifier().parameters(): _UpperCAmelCase = True # We normalize the batches of images to be a bit faster. _UpperCAmelCase = torch.tensor(model.default_cfg["mean"] )[None, :, None, None].to(accelerator.device ) _UpperCAmelCase = torch.tensor(model.default_cfg["std"] )[None, :, None, None].to(accelerator.device ) # Instantiate optimizer _UpperCAmelCase = torch.optim.Adam(params=model.parameters() , lr=lr / 25 ) # Instantiate learning rate scheduler _UpperCAmelCase = OneCycleLR(optimizer=__lowercase , max_lr=__lowercase , epochs=__lowercase , steps_per_epoch=len(__lowercase ) ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = accelerator.prepare( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) # We need to keep track of how many total steps we have iterated over _UpperCAmelCase = 0 # We also need to keep track of the starting epoch so files are named properly _UpperCAmelCase = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(f'Resumed from checkpoint: {args.resume_from_checkpoint}' ) accelerator.load_state(args.resume_from_checkpoint ) _UpperCAmelCase = os.path.basename(args.resume_from_checkpoint ) else: # Get the most recent checkpoint _UpperCAmelCase = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()] dirs.sort(key=os.path.getctime ) _UpperCAmelCase = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` _UpperCAmelCase = os.path.splitext(__lowercase )[0] if "epoch" in training_difference: _UpperCAmelCase = int(training_difference.replace("epoch_" , "" ) ) + 1 _UpperCAmelCase = None else: _UpperCAmelCase = int(training_difference.replace("step_" , "" ) ) _UpperCAmelCase = resume_step // len(__lowercase ) resume_step -= starting_epoch * len(__lowercase ) # Now we train the model for epoch in range(__lowercase , __lowercase ): model.train() if args.with_tracking: _UpperCAmelCase = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step _UpperCAmelCase = accelerator.skip_first_batches(__lowercase , __lowercase ) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader _UpperCAmelCase = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. _UpperCAmelCase = {k: v.to(accelerator.device ) for k, v in batch.items()} _UpperCAmelCase = (batch["image"] - mean) / std _UpperCAmelCase = model(__lowercase ) _UpperCAmelCase = torch.nn.functional.cross_entropy(__lowercase , batch["label"] ) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(__lowercase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(__lowercase , __lowercase ): _UpperCAmelCase = f'step_{overall_step}' if overall_step % checkpointing_steps == 0: if args.output_dir is not None: _UpperCAmelCase = os.path.join(args.output_dir , __lowercase ) accelerator.save_state(__lowercase ) model.eval() _UpperCAmelCase = 0 _UpperCAmelCase = 0 for step, batch in enumerate(__lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. _UpperCAmelCase = {k: v.to(accelerator.device ) for k, v in batch.items()} _UpperCAmelCase = (batch["image"] - mean) / std with torch.no_grad(): _UpperCAmelCase = model(__lowercase ) _UpperCAmelCase = outputs.argmax(dim=-1 ) _UpperCAmelCase , _UpperCAmelCase = accelerator.gather_for_metrics((predictions, batch["label"]) ) _UpperCAmelCase = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() _UpperCAmelCase = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}: {100 * eval_metric:.2f}' ) if args.with_tracking: accelerator.log( { "accuracy": 100 * eval_metric, "train_loss": total_loss.item() / len(__lowercase ), "epoch": epoch, } , step=__lowercase , ) if checkpointing_steps == "epoch": _UpperCAmelCase = f'epoch_{epoch}' if args.output_dir is not None: _UpperCAmelCase = os.path.join(args.output_dir , __lowercase ) accelerator.save_state(__lowercase ) if args.with_tracking: accelerator.end_training() def UpperCAmelCase_ ( ) -> List[str]: '''simple docstring''' _UpperCAmelCase = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument("--data_dir" , required=__lowercase , help="The data folder on disk." ) parser.add_argument("--fp16" , action="store_true" , help="If passed, will use FP16 training." ) parser.add_argument( "--mixed_precision" , type=__lowercase , default=__lowercase , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) parser.add_argument( "--checkpointing_steps" , type=__lowercase , default=__lowercase , help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch." , ) parser.add_argument( "--output_dir" , type=__lowercase , default="." , help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory." , ) parser.add_argument( "--resume_from_checkpoint" , type=__lowercase , default=__lowercase , help="If the training should continue from a checkpoint folder." , ) parser.add_argument( "--with_tracking" , action="store_true" , help="Whether to load in all available experiment trackers from the environment and use them for logging." , ) parser.add_argument( "--project_dir" , type=__lowercase , default="logs" , help="Location on where to store experiment tracking logs` and relevent project information" , ) _UpperCAmelCase = parser.parse_args() _UpperCAmelCase = {"lr": 3E-2, "num_epochs": 3, "seed": 42, "batch_size": 64, "image_size": 224} training_function(__lowercase , __lowercase ) if __name__ == "__main__": main()
119
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) lowerCamelCase ={ "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"], "processing_trocr": ["TrOCRProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase =[ "TROCR_PRETRAINED_MODEL_ARCHIVE_LIST", "TrOCRForCausalLM", "TrOCRPreTrainedModel", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
285
# limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( "pipelines_utils", "0.22.0", "Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.", standard_warn=False, stacklevel=3, )
285
1
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = {"tokenizer_file": "tokenizer.json"} UpperCamelCase__ = { "tokenizer_file": { "bigscience/tokenizer": "https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json", "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json", "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json", "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json", "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json", "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json", "bigscience/bloom": "https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json", }, } class __SCREAMING_SNAKE_CASE ( _a ): snake_case : List[Any] = VOCAB_FILES_NAMES snake_case : Dict = PRETRAINED_VOCAB_FILES_MAP snake_case : Optional[int] = ["""input_ids""", """attention_mask"""] snake_case : List[Any] = None def __init__( self , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase="<unk>" , __lowerCAmelCase="<s>" , __lowerCAmelCase="</s>" , __lowerCAmelCase="<pad>" , __lowerCAmelCase=False , __lowerCAmelCase=False , **__lowerCAmelCase , ): super().__init__( __lowerCAmelCase , __lowerCAmelCase , tokenizer_file=__lowerCAmelCase , unk_token=__lowerCAmelCase , bos_token=__lowerCAmelCase , eos_token=__lowerCAmelCase , pad_token=__lowerCAmelCase , add_prefix_space=__lowerCAmelCase , clean_up_tokenization_spaces=__lowerCAmelCase , **__lowerCAmelCase , ) UpperCamelCase__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , __lowerCAmelCase ) != add_prefix_space: UpperCamelCase__ = getattr(__lowerCAmelCase , pre_tok_state.pop("""type""" ) ) UpperCamelCase__ = add_prefix_space UpperCamelCase__ = pre_tok_class(**__lowerCAmelCase ) UpperCamelCase__ = add_prefix_space def _lowerCamelCase ( self , *__lowerCAmelCase , **__lowerCAmelCase ): UpperCamelCase__ = kwargs.get("""is_split_into_words""" , __lowerCAmelCase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with""" """ pretokenized inputs.""" ) return super()._batch_encode_plus(*__lowerCAmelCase , **__lowerCAmelCase ) def _lowerCamelCase ( self , *__lowerCAmelCase , **__lowerCAmelCase ): UpperCamelCase__ = kwargs.get("""is_split_into_words""" , __lowerCAmelCase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with""" """ pretokenized inputs.""" ) return super()._encode_plus(*__lowerCAmelCase , **__lowerCAmelCase ) def _lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase = None ): UpperCamelCase__ = self._tokenizer.model.save(__lowerCAmelCase , name=__lowerCAmelCase ) return tuple(__lowerCAmelCase ) def _lowerCamelCase ( self , __lowerCAmelCase ): UpperCamelCase__ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) + [self.eos_token_id] ) if len(__lowerCAmelCase ) > self.model_max_length: UpperCamelCase__ = input_ids[-self.model_max_length :] return input_ids
700
import unittest from transformers import ( MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TextGenerationPipeline, logging, pipeline, ) from transformers.testing_utils import ( CaptureLogger, is_pipeline_test, require_accelerate, require_tf, require_torch, require_torch_gpu, require_torch_or_tf, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case : Union[str, Any] = MODEL_FOR_CAUSAL_LM_MAPPING snake_case : List[str] = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def _lowerCamelCase ( self ): UpperCamelCase__ = pipeline(task="""text-generation""" , model="""sshleifer/tiny-ctrl""" , framework="""pt""" ) # Using `do_sample=False` to force deterministic output UpperCamelCase__ = text_generator("""This is a test""" , do_sample=__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [ { """generated_text""": ( """This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.""" """ oscope. FiliFili@@""" ) } ] , ) UpperCamelCase__ = text_generator(["""This is a test""", """This is a second test"""] ) self.assertEqual( __lowerCAmelCase , [ [ { """generated_text""": ( """This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.""" """ oscope. FiliFili@@""" ) } ], [ { """generated_text""": ( """This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy""" """ oscope. oscope. FiliFili@@""" ) } ], ] , ) UpperCamelCase__ = text_generator("""This is a test""" , do_sample=__lowerCAmelCase , num_return_sequences=2 , return_tensors=__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [ {"""generated_token_ids""": ANY(__lowerCAmelCase )}, {"""generated_token_ids""": ANY(__lowerCAmelCase )}, ] , ) UpperCamelCase__ = text_generator.model.config.eos_token_id UpperCamelCase__ = """<pad>""" UpperCamelCase__ = text_generator( ["""This is a test""", """This is a second test"""] , do_sample=__lowerCAmelCase , num_return_sequences=2 , batch_size=2 , return_tensors=__lowerCAmelCase , ) self.assertEqual( __lowerCAmelCase , [ [ {"""generated_token_ids""": ANY(__lowerCAmelCase )}, {"""generated_token_ids""": ANY(__lowerCAmelCase )}, ], [ {"""generated_token_ids""": ANY(__lowerCAmelCase )}, {"""generated_token_ids""": ANY(__lowerCAmelCase )}, ], ] , ) @require_tf def _lowerCamelCase ( self ): UpperCamelCase__ = pipeline(task="""text-generation""" , model="""sshleifer/tiny-ctrl""" , framework="""tf""" ) # Using `do_sample=False` to force deterministic output UpperCamelCase__ = text_generator("""This is a test""" , do_sample=__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [ { """generated_text""": ( """This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵""" """ please,""" ) } ] , ) UpperCamelCase__ = text_generator(["""This is a test""", """This is a second test"""] , do_sample=__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [ [ { """generated_text""": ( """This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵""" """ please,""" ) } ], [ { """generated_text""": ( """This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes""" """ Cannes 閲閲Cannes Cannes Cannes 攵 please,""" ) } ], ] , ) def _lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): UpperCamelCase__ = TextGenerationPipeline(model=__lowerCAmelCase , tokenizer=__lowerCAmelCase ) return text_generator, ["This is a test", "Another test"] def _lowerCamelCase ( self ): UpperCamelCase__ = """Hello I believe in""" UpperCamelCase__ = pipeline("""text-generation""" , model="""hf-internal-testing/tiny-random-gpt2""" ) UpperCamelCase__ = text_generator(__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [{"""generated_text""": """Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe"""}] , ) UpperCamelCase__ = text_generator(__lowerCAmelCase , stop_sequence=""" fe""" ) self.assertEqual(__lowerCAmelCase , [{"""generated_text""": """Hello I believe in fe"""}] ) def _lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase ): UpperCamelCase__ = text_generator.model UpperCamelCase__ = text_generator.tokenizer UpperCamelCase__ = text_generator("""This is a test""" ) self.assertEqual(__lowerCAmelCase , [{"""generated_text""": ANY(__lowerCAmelCase )}] ) self.assertTrue(outputs[0]["""generated_text"""].startswith("""This is a test""" ) ) UpperCamelCase__ = text_generator("""This is a test""" , return_full_text=__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , [{"""generated_text""": ANY(__lowerCAmelCase )}] ) self.assertNotIn("""This is a test""" , outputs[0]["""generated_text"""] ) UpperCamelCase__ = pipeline(task="""text-generation""" , model=__lowerCAmelCase , tokenizer=__lowerCAmelCase , return_full_text=__lowerCAmelCase ) UpperCamelCase__ = text_generator("""This is a test""" ) self.assertEqual(__lowerCAmelCase , [{"""generated_text""": ANY(__lowerCAmelCase )}] ) self.assertNotIn("""This is a test""" , outputs[0]["""generated_text"""] ) UpperCamelCase__ = text_generator("""This is a test""" , return_full_text=__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , [{"""generated_text""": ANY(__lowerCAmelCase )}] ) self.assertTrue(outputs[0]["""generated_text"""].startswith("""This is a test""" ) ) UpperCamelCase__ = text_generator(["""This is great !""", """Something else"""] , num_return_sequences=2 , do_sample=__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [ [{"""generated_text""": ANY(__lowerCAmelCase )}, {"""generated_text""": ANY(__lowerCAmelCase )}], [{"""generated_text""": ANY(__lowerCAmelCase )}, {"""generated_text""": ANY(__lowerCAmelCase )}], ] , ) if text_generator.tokenizer.pad_token is not None: UpperCamelCase__ = text_generator( ["""This is great !""", """Something else"""] , num_return_sequences=2 , batch_size=2 , do_sample=__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [ [{"""generated_text""": ANY(__lowerCAmelCase )}, {"""generated_text""": ANY(__lowerCAmelCase )}], [{"""generated_text""": ANY(__lowerCAmelCase )}, {"""generated_text""": ANY(__lowerCAmelCase )}], ] , ) with self.assertRaises(__lowerCAmelCase ): UpperCamelCase__ = text_generator("""test""" , return_full_text=__lowerCAmelCase , return_text=__lowerCAmelCase ) with self.assertRaises(__lowerCAmelCase ): UpperCamelCase__ = text_generator("""test""" , return_full_text=__lowerCAmelCase , return_tensors=__lowerCAmelCase ) with self.assertRaises(__lowerCAmelCase ): UpperCamelCase__ = text_generator("""test""" , return_text=__lowerCAmelCase , return_tensors=__lowerCAmelCase ) # Empty prompt is slighly special # it requires BOS token to exist. # Special case for Pegasus which will always append EOS so will # work even without BOS. if ( text_generator.tokenizer.bos_token_id is not None or "Pegasus" in tokenizer.__class__.__name__ or "Git" in model.__class__.__name__ ): UpperCamelCase__ = text_generator("""""" ) self.assertEqual(__lowerCAmelCase , [{"""generated_text""": ANY(__lowerCAmelCase )}] ) else: with self.assertRaises((ValueError, AssertionError) ): UpperCamelCase__ = text_generator("""""" ) if text_generator.framework == "tf": # TF generation does not support max_new_tokens, and it's impossible # to control long generation with only max_length without # fancy calculation, dismissing tests for now. return # We don't care about infinite range models. # They already work. # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. UpperCamelCase__ = ["""RwkvForCausalLM""", """XGLMForCausalLM""", """GPTNeoXForCausalLM"""] if ( tokenizer.model_max_length < 10000 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS ): # Handling of large generations with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ): text_generator("""This is a test""" * 500 , max_new_tokens=20 ) UpperCamelCase__ = text_generator("""This is a test""" * 500 , handle_long_generation="""hole""" , max_new_tokens=20 ) # Hole strategy cannot work with self.assertRaises(__lowerCAmelCase ): text_generator( """This is a test""" * 500 , handle_long_generation="""hole""" , max_new_tokens=tokenizer.model_max_length + 10 , ) @require_torch @require_accelerate @require_torch_gpu def _lowerCamelCase ( self ): import torch # Classic `model_kwargs` UpperCamelCase__ = pipeline( model="""hf-internal-testing/tiny-random-bloom""" , model_kwargs={"""device_map""": """auto""", """torch_dtype""": torch.bfloataa} , ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) UpperCamelCase__ = pipe("""This is a test""" ) self.assertEqual( __lowerCAmelCase , [ { """generated_text""": ( """This is a test test test test test test test test test test test test test test test test""" """ test""" ) } ] , ) # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) UpperCamelCase__ = pipeline(model="""hf-internal-testing/tiny-random-bloom""" , device_map="""auto""" , torch_dtype=torch.bfloataa ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) UpperCamelCase__ = pipe("""This is a test""" ) self.assertEqual( __lowerCAmelCase , [ { """generated_text""": ( """This is a test test test test test test test test test test test test test test test test""" """ test""" ) } ] , ) # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602 UpperCamelCase__ = pipeline(model="""hf-internal-testing/tiny-random-bloom""" , device_map="""auto""" ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa ) UpperCamelCase__ = pipe("""This is a test""" ) self.assertEqual( __lowerCAmelCase , [ { """generated_text""": ( """This is a test test test test test test test test test test test test test test test test""" """ test""" ) } ] , ) @require_torch @require_torch_gpu def _lowerCamelCase ( self ): import torch UpperCamelCase__ = pipeline(model="""hf-internal-testing/tiny-random-bloom""" , device=0 , torch_dtype=torch.floataa ) pipe("""This is a test""" ) @require_torch @require_accelerate @require_torch_gpu def _lowerCamelCase ( self ): import torch UpperCamelCase__ = pipeline(model="""hf-internal-testing/tiny-random-bloom""" , device_map="""auto""" , torch_dtype=torch.floataa ) pipe("""This is a test""" , do_sample=__lowerCAmelCase , top_p=0.5 ) def _lowerCamelCase ( self ): UpperCamelCase__ = """Hello world""" UpperCamelCase__ = pipeline("""text-generation""" , model="""hf-internal-testing/tiny-random-gpt2""" ) if text_generator.model.framework == "tf": UpperCamelCase__ = logging.get_logger("""transformers.generation.tf_utils""" ) else: UpperCamelCase__ = logging.get_logger("""transformers.generation.utils""" ) UpperCamelCase__ = """Both `max_new_tokens`""" # The beggining of the message to be checked in this test # Both are set by the user -> log warning with CaptureLogger(__lowerCAmelCase ) as cl: UpperCamelCase__ = text_generator(__lowerCAmelCase , max_length=10 , max_new_tokens=1 ) self.assertIn(__lowerCAmelCase , cl.out ) # The user only sets one -> no warning with CaptureLogger(__lowerCAmelCase ) as cl: UpperCamelCase__ = text_generator(__lowerCAmelCase , max_new_tokens=1 ) self.assertNotIn(__lowerCAmelCase , cl.out ) with CaptureLogger(__lowerCAmelCase ) as cl: UpperCamelCase__ = text_generator(__lowerCAmelCase , max_length=10 ) self.assertNotIn(__lowerCAmelCase , cl.out )
548
0
"""simple docstring""" import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL a = version.parse(version.parse(torch.__version__).base_version) < version.parse('1.11') def lowercase (snake_case__ : Optional[Any] , snake_case__ : tuple , snake_case__ : Path , snake_case__ : List[str] , snake_case__ : Dict , snake_case__ : Union[str, Any] , snake_case__ : Dict , snake_case__ : Union[str, Any]=False , ) -> List[Any]: '''simple docstring''' output_path.parent.mkdir(parents=snake_case__ , exist_ok=snake_case__ ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( snake_case__ , snake_case__ , f=output_path.as_posix() , input_names=snake_case__ , output_names=snake_case__ , dynamic_axes=snake_case__ , do_constant_folding=snake_case__ , use_external_data_format=snake_case__ , enable_onnx_checker=snake_case__ , opset_version=snake_case__ , ) else: export( snake_case__ , snake_case__ , f=output_path.as_posix() , input_names=snake_case__ , output_names=snake_case__ , dynamic_axes=snake_case__ , do_constant_folding=snake_case__ , opset_version=snake_case__ , ) @torch.no_grad() def lowercase (snake_case__ : str , snake_case__ : str , snake_case__ : int , snake_case__ : bool = False ) -> Dict: '''simple docstring''' lowerCAmelCase = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): lowerCAmelCase = """cuda""" elif fpaa and not torch.cuda.is_available(): raise ValueError("""`float16` model export is only supported on GPUs with CUDA""" ) else: lowerCAmelCase = """cpu""" lowerCAmelCase = Path(snake_case__ ) # VAE DECODER lowerCAmelCase = AutoencoderKL.from_pretrained(model_path + """/vae""" ) lowerCAmelCase = vae_decoder.config.latent_channels # forward only through the decoder part lowerCAmelCase = vae_decoder.decode onnx_export( snake_case__ , model_args=( torch.randn(1 , snake_case__ , 25 , 25 ).to(device=snake_case__ , dtype=snake_case__ ), False, ) , output_path=output_path / """vae_decoder""" / """model.onnx""" , ordered_input_names=["""latent_sample""", """return_dict"""] , output_names=["""sample"""] , dynamic_axes={ """latent_sample""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""}, } , opset=snake_case__ , ) del vae_decoder if __name__ == "__main__": a = argparse.ArgumentParser() parser.add_argument( '--model_path', type=str, required=True, help='Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).', ) parser.add_argument('--output_path', type=str, required=True, help='Path to the output model.') parser.add_argument( '--opset', default=1_4, type=int, help='The version of the ONNX operator set to use.', ) parser.add_argument('--fp16', action='store_true', default=False, help='Export the models in `float16` mode') a = parser.parse_args() print(args.output_path) convert_models(args.model_path, args.output_path, args.opset, args.fpaa) print('SD: Done: ONNX')
169
"""simple docstring""" import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin a = get_tests_dir('fixtures/test_sentencepiece_with_bytefallback.model') @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE__ ( _a , unittest.TestCase ): _a = GPTSwaTokenizer _a = False _a = True _a = False def __lowercase ( self : Tuple ): super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase = GPTSwaTokenizer(lowerCAmelCase , eos_token="""<unk>""" , bos_token="""<unk>""" , pad_token="""<unk>""" ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase ( self : Union[str, Any] , lowerCAmelCase : Tuple ): lowerCAmelCase = """This is a test""" lowerCAmelCase = """This is a test""" return input_text, output_text def __lowercase ( self : List[Any] ): lowerCAmelCase = """<s>""" lowerCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase ) , lowerCAmelCase ) def __lowercase ( self : Any ): lowerCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<unk>""" ) self.assertEqual(vocab_keys[1] , """<s>""" ) self.assertEqual(vocab_keys[-1] , """j""" ) self.assertEqual(len(lowerCAmelCase ) , 2000 ) def __lowercase ( self : Tuple ): self.assertEqual(self.get_tokenizer().vocab_size , 2000 ) def __lowercase ( self : Union[str, Any] ): lowerCAmelCase = GPTSwaTokenizer(lowerCAmelCase ) lowerCAmelCase = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(lowerCAmelCase , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [465, 287, 265, 631, 842] ) lowerCAmelCase = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) # fmt: off self.assertListEqual( lowerCAmelCase , ["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""] , ) # fmt: on lowerCAmelCase = tokenizer.convert_tokens_to_ids(lowerCAmelCase ) self.assertListEqual( lowerCAmelCase , [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , ) lowerCAmelCase = tokenizer.convert_ids_to_tokens(lowerCAmelCase ) # fmt: off self.assertListEqual( lowerCAmelCase , ["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""] ) # fmt: on def __lowercase ( self : int ): lowerCAmelCase = GPTSwaTokenizer(lowerCAmelCase ) lowerCAmelCase = ["""This is a test""", """I was born in 92000, and this is falsé."""] lowerCAmelCase = [ [465, 287, 265, 631, 842], [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260], ] # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids for text, expected_ids in zip(lowerCAmelCase , lowerCAmelCase ): self.assertListEqual(tokenizer.encode_fast(lowerCAmelCase ) , lowerCAmelCase ) # Test that decode_fast returns the input text for text, token_ids in zip(lowerCAmelCase , lowerCAmelCase ): self.assertEqual(tokenizer.decode_fast(lowerCAmelCase ) , lowerCAmelCase ) @slow def __lowercase ( self : Any ): lowerCAmelCase = [ """<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')""", """Hey there, how are you doing this fine day?""", """This is a text with a trailing spaces followed by a dot .""", """Häj sväjs lillebrör! =)""", """Det är inget fel på Mr. Cool""", ] # fmt: off lowerCAmelCase = {"""input_ids""": [[6_3423, 5, 6811, 1_4954, 282, 816, 3821, 6_3466, 6_3425, 6_3462, 18, 6_3978, 678, 301, 1320, 6_3423, 6_3455, 6_3458, 18, 6_3982, 4246, 3940, 1901, 4_7789, 5547, 1_8994], [1_9630, 1100, 6_3446, 1342, 633, 544, 4488, 593, 5102, 2416, 6_3495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1652, 428, 268, 1936, 515, 268, 5_8593, 2_2413, 9106, 546, 268, 3_3213, 6_3979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5_5130, 6_3450, 924, 6_3449, 2249, 4062, 1558, 318, 6_3504, 2_1498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2827, 2559, 332, 6575, 6_3443, 2_6801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """token_type_ids""": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCAmelCase , model_name="""AI-Sweden/gpt-sw3-126m""" , sequences=lowerCAmelCase , )
169
1
"""simple docstring""" import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = (DEISMultistepScheduler,) _SCREAMING_SNAKE_CASE :List[Any] = (("""num_inference_steps""", 25),) def _a ( self , **_a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = { """num_train_timesteps""": 1_000, """beta_start""": 0.0_001, """beta_end""": 0.02, """beta_schedule""": """linear""", """solver_order""": 2, } config.update(**_a ) return config def _a ( self , _a=0 , **_a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE__ : Optional[Any] = kwargs.pop("""num_inference_steps""" , _a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.dummy_sample SCREAMING_SNAKE_CASE__ : str = 0.1 * sample SCREAMING_SNAKE_CASE__ : str = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_scheduler_config(**_a ) SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_a ) scheduler.set_timesteps(_a ) # copy over dummy past residuals SCREAMING_SNAKE_CASE__ : Any = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(_a ) SCREAMING_SNAKE_CASE__ : Tuple = scheduler_class.from_pretrained(_a ) new_scheduler.set_timesteps(_a ) # copy over dummy past residuals SCREAMING_SNAKE_CASE__ : str = dummy_past_residuals[: new_scheduler.config.solver_order] SCREAMING_SNAKE_CASE__ : Any = sample, sample for t in range(_a , time_step + scheduler.config.solver_order + 1 ): SCREAMING_SNAKE_CASE__ : str = scheduler.step(_a , _a , _a , **_a ).prev_sample SCREAMING_SNAKE_CASE__ : Any = new_scheduler.step(_a , _a , _a , **_a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _a ( self ) -> Tuple: """simple docstring""" pass def _a ( self , _a=0 , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE__ : int = kwargs.pop("""num_inference_steps""" , _a ) SCREAMING_SNAKE_CASE__ : Any = self.dummy_sample SCREAMING_SNAKE_CASE__ : Any = 0.1 * sample SCREAMING_SNAKE_CASE__ : Optional[int] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_a ) scheduler.set_timesteps(_a ) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE__ : Tuple = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(_a ) SCREAMING_SNAKE_CASE__ : Tuple = scheduler_class.from_pretrained(_a ) # copy over dummy past residuals new_scheduler.set_timesteps(_a ) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE__ : Any = dummy_past_residuals[: new_scheduler.config.solver_order] SCREAMING_SNAKE_CASE__ : List[Any] = scheduler.step(_a , _a , _a , **_a ).prev_sample SCREAMING_SNAKE_CASE__ : str = new_scheduler.step(_a , _a , _a , **_a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _a ( self , _a=None , **_a ) -> Union[str, Any]: """simple docstring""" if scheduler is None: SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Any = self.get_scheduler_config(**_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[Any] = self.get_scheduler_config(**_a ) SCREAMING_SNAKE_CASE__ : str = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : str = 10 SCREAMING_SNAKE_CASE__ : Optional[int] = self.dummy_model() SCREAMING_SNAKE_CASE__ : Dict = self.dummy_sample_deter scheduler.set_timesteps(_a ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : str = model(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = scheduler.step(_a , _a , _a ).prev_sample return sample def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE__ : List[str] = kwargs.pop("""num_inference_steps""" , _a ) for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE__ : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : str = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.dummy_sample SCREAMING_SNAKE_CASE__ : Optional[int] = 0.1 * sample if num_inference_steps is not None and hasattr(_a , """set_timesteps""" ): scheduler.set_timesteps(_a ) elif num_inference_steps is not None and not hasattr(_a , """set_timesteps""" ): SCREAMING_SNAKE_CASE__ : Optional[Any] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) SCREAMING_SNAKE_CASE__ : Optional[int] = [residual + 0.2, residual + 0.15, residual + 0.10] SCREAMING_SNAKE_CASE__ : List[Any] = dummy_past_residuals[: scheduler.config.solver_order] SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler.timesteps[5] SCREAMING_SNAKE_CASE__ : Any = scheduler.timesteps[6] SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler.step(_a , _a , _a , **_a ).prev_sample SCREAMING_SNAKE_CASE__ : str = scheduler.step(_a , _a , _a , **_a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DEISMultistepScheduler(**self.get_scheduler_config() ) SCREAMING_SNAKE_CASE__ : Tuple = self.full_loop(scheduler=_a ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.mean(torch.abs(_a ) ) assert abs(result_mean.item() - 0.23_916 ) < 1E-3 SCREAMING_SNAKE_CASE__ : Dict = DPMSolverSinglestepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE__ : Tuple = DPMSolverMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE__ : Tuple = UniPCMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE__ : str = DEISMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE__ : str = self.full_loop(scheduler=_a ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.mean(torch.abs(_a ) ) assert abs(result_mean.item() - 0.23_916 ) < 1E-3 def _a ( self ) -> List[str]: """simple docstring""" for timesteps in [25, 50, 100, 999, 1_000]: self.check_over_configs(num_train_timesteps=_a ) def _a ( self ) -> Dict: """simple docstring""" self.check_over_configs(thresholding=_a ) for order in [1, 2, 3]: for solver_type in ["logrho"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=_a , prediction_type=_a , sample_max_value=_a , algorithm_type="""deis""" , solver_order=_a , solver_type=_a , ) def _a ( self ) -> Any: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" for algorithm_type in ["deis"]: for solver_type in ["logrho"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=_a , solver_type=_a , prediction_type=_a , algorithm_type=_a , ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.full_loop( solver_order=_a , solver_type=_a , prediction_type=_a , algorithm_type=_a , ) assert not torch.isnan(_a ).any(), "Samples have nan numbers" def _a ( self ) -> int: """simple docstring""" self.check_over_configs(lower_order_final=_a ) self.check_over_configs(lower_order_final=_a ) def _a ( self ) -> str: """simple docstring""" for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1_000]: self.check_over_forward(num_inference_steps=_a , time_step=0 ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.full_loop() SCREAMING_SNAKE_CASE__ : Dict = torch.mean(torch.abs(_a ) ) assert abs(result_mean.item() - 0.23_916 ) < 1E-3 def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.full_loop(prediction_type="""v_prediction""" ) SCREAMING_SNAKE_CASE__ : List[str] = torch.mean(torch.abs(_a ) ) assert abs(result_mean.item() - 0.091 ) < 1E-3 def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[Any] = self.get_scheduler_config(thresholding=_a , dynamic_thresholding_ratio=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 10 SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_sample_deter.half() scheduler.set_timesteps(_a ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : List[Any] = model(_a , _a ) SCREAMING_SNAKE_CASE__ : int = scheduler.step(_a , _a , _a ).prev_sample assert sample.dtype == torch.floataa
716
"""simple docstring""" # 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 _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=0 ) -> Any: # Format the message. if name is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None else: SCREAMING_SNAKE_CASE__ : str = """.""" * max(0 , spaces - 2 ) + """# {:""" + str(50 - spaces ) + """s}""" SCREAMING_SNAKE_CASE__ : Dict = fmt.format(__lowerCAmelCase ) # Print and recurse (if needed). if isinstance(__lowerCAmelCase , __lowerCAmelCase ): if msg is not None: print(__lowerCAmelCase ) for k in val.keys(): recursive_print(__lowerCAmelCase , val[k] , spaces + 2 ) elif isinstance(__lowerCAmelCase , torch.Tensor ): print(__lowerCAmelCase , """:""" , val.size() ) else: print(__lowerCAmelCase , """:""" , __lowerCAmelCase ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: # 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. SCREAMING_SNAKE_CASE__ : Tuple = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] SCREAMING_SNAKE_CASE__ : int = (num_heads, hidden_size, num_splits) + input_shape[1:] SCREAMING_SNAKE_CASE__ : List[str] = param.view(*__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = param.transpose(0 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = param.transpose(1 , 2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] SCREAMING_SNAKE_CASE__ : List[str] = (num_heads, num_splits, hidden_size) + input_shape[1:] SCREAMING_SNAKE_CASE__ : Dict = param.view(*__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = param.transpose(0 , 1 ).contiguous() SCREAMING_SNAKE_CASE__ : Any = param.view(*__lowerCAmelCase ) return param def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: # The converted output model. SCREAMING_SNAKE_CASE__ : List[str] = {} # old versions did not store training args SCREAMING_SNAKE_CASE__ : List[str] = input_state_dict.get("""args""" , __lowerCAmelCase ) 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)) SCREAMING_SNAKE_CASE__ : List[Any] = ds_args.padded_vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = ds_args.max_position_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = ds_args.hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = ds_args.num_layers SCREAMING_SNAKE_CASE__ : Dict = ds_args.num_attention_heads SCREAMING_SNAKE_CASE__ : List[str] = ds_args.ffn_hidden_size # pprint(config) # The number of heads. SCREAMING_SNAKE_CASE__ : List[str] = config.n_head # The hidden_size per head. SCREAMING_SNAKE_CASE__ : str = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_state_dict["""checkpoint_version"""] else: SCREAMING_SNAKE_CASE__ : Tuple = 0.0 # The model. SCREAMING_SNAKE_CASE__ : Any = input_state_dict["""model"""] # The language model. SCREAMING_SNAKE_CASE__ : Any = model["""language_model"""] # The embeddings. SCREAMING_SNAKE_CASE__ : str = lm["""embedding"""] # The word embeddings. SCREAMING_SNAKE_CASE__ : int = embeddings["""word_embeddings"""]["""weight"""] # Truncate the embedding table to vocab_size rows. SCREAMING_SNAKE_CASE__ : Any = word_embeddings[: config.vocab_size, :] SCREAMING_SNAKE_CASE__ : Optional[int] = word_embeddings # The position embeddings. SCREAMING_SNAKE_CASE__ : Any = embeddings["""position_embeddings"""]["""weight"""] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] SCREAMING_SNAKE_CASE__ : Tuple = 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. SCREAMING_SNAKE_CASE__ : List[Any] = pos_embeddings # The transformer. SCREAMING_SNAKE_CASE__ : Union[str, Any] = lm["""transformer"""] if """transformer""" in lm.keys() else lm["""encoder"""] # The regex to extract layer names. SCREAMING_SNAKE_CASE__ : str = re.compile(r"""layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)""" ) # The simple map of names for "automated" rules. SCREAMING_SNAKE_CASE__ : Optional[int] = { """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. SCREAMING_SNAKE_CASE__ : str = layer_re.match(__lowerCAmelCase ) # Stop if that's not a layer if m is None: break # The index of the layer. SCREAMING_SNAKE_CASE__ : Dict = int(m.group(1 ) ) # The name of the operation. SCREAMING_SNAKE_CASE__ : Optional[Any] = m.group(2 ) # Is it a weight or a bias? SCREAMING_SNAKE_CASE__ : str = m.group(3 ) # The name of the layer. SCREAMING_SNAKE_CASE__ : List[Any] = F'''transformer.h.{layer_idx}''' # For layernorm(s), simply store the layer norm. if op_name.endswith("""layernorm""" ): SCREAMING_SNAKE_CASE__ : Dict = """ln_1""" if op_name.startswith("""input""" ) else """ln_2""" SCREAMING_SNAKE_CASE__ : List[Any] = 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. SCREAMING_SNAKE_CASE__ : Any = torch.tril(torch.ones((n_positions, n_positions) , dtype=torch.floataa ) ).view( 1 , 1 , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = causal_mask # Insert a "dummy" tensor for masked_bias. SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor(-1E4 , dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : List[str] = masked_bias SCREAMING_SNAKE_CASE__ : List[str] = fix_query_key_value_ordering(__lowerCAmelCase , __lowerCAmelCase , 3 , __lowerCAmelCase , __lowerCAmelCase ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. SCREAMING_SNAKE_CASE__ : str = out_val.transpose(0 , 1 ).contiguous() # Store. SCREAMING_SNAKE_CASE__ : Dict = 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": SCREAMING_SNAKE_CASE__ : Any = fix_query_key_value_ordering(__lowerCAmelCase , __lowerCAmelCase , 3 , __lowerCAmelCase , __lowerCAmelCase ) # Store. No change of shape. SCREAMING_SNAKE_CASE__ : str = out_val # Transpose the weights. elif weight_or_bias == "weight": SCREAMING_SNAKE_CASE__ : str = megatron_to_transformers[op_name] SCREAMING_SNAKE_CASE__ : int = val.transpose(0 , 1 ) # Copy the bias. elif weight_or_bias == "bias": SCREAMING_SNAKE_CASE__ : int = megatron_to_transformers[op_name] SCREAMING_SNAKE_CASE__ : Dict = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. SCREAMING_SNAKE_CASE__ : Union[str, Any] = transformer["""final_layernorm.weight"""] SCREAMING_SNAKE_CASE__ : str = transformer["""final_layernorm.bias"""] # For LM head, transformers' wants the matrix to weight embeddings. SCREAMING_SNAKE_CASE__ : Tuple = word_embeddings # It should be done! return output_state_dict def _lowercase ( ) -> List[Any]: # Create the argument parser. SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() parser.add_argument("""--print-checkpoint-structure""" , action="""store_true""" ) parser.add_argument( """path_to_checkpoint""" , type=__lowerCAmelCase , help="""Path to the checkpoint file (.zip archive or direct .pt file)""" , ) parser.add_argument( """--config_file""" , default="""""" , type=__lowerCAmelCase , help="""An optional config json file describing the pre-trained model.""" , ) SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args() # Extract the basename. SCREAMING_SNAKE_CASE__ : Optional[int] = 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: SCREAMING_SNAKE_CASE__ : List[Any] = torch.load(__lowerCAmelCase , map_location="""cpu""" ) else: SCREAMING_SNAKE_CASE__ : str = torch.load(args.path_to_checkpoint , map_location="""cpu""" ) SCREAMING_SNAKE_CASE__ : int = input_state_dict.get("""args""" , __lowerCAmelCase ) # 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: SCREAMING_SNAKE_CASE__ : Dict = """gelu_fast""" elif ds_args.openai_gelu: SCREAMING_SNAKE_CASE__ : Optional[Any] = """gelu_new""" else: SCREAMING_SNAKE_CASE__ : Optional[Any] = """gelu""" else: # in the very early days this used to be "gelu_new" SCREAMING_SNAKE_CASE__ : Any = """gelu_new""" # Spell out all parameters in case the defaults change. SCREAMING_SNAKE_CASE__ : Union[str, Any] = GPTaConfig( vocab_size=5_0257 , n_positions=1024 , n_embd=1024 , n_layer=24 , n_head=16 , n_inner=4096 , activation_function=__lowerCAmelCase , 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=__lowerCAmelCase , summary_activation=__lowerCAmelCase , summary_proj_to_labels=__lowerCAmelCase , summary_first_dropout=0.1 , scale_attn_weights=__lowerCAmelCase , use_cache=__lowerCAmelCase , bos_token_id=5_0256 , eos_token_id=5_0256 , ) else: SCREAMING_SNAKE_CASE__ : List[Any] = GPTaConfig.from_json_file(args.config_file ) SCREAMING_SNAKE_CASE__ : Tuple = ["""GPT2LMHeadModel"""] # Convert. print("""Converting""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = convert_megatron_checkpoint(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(__lowerCAmelCase , __lowerCAmelCase ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: SCREAMING_SNAKE_CASE__ : Tuple = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": SCREAMING_SNAKE_CASE__ : Any = """gpt2""" elif tokenizer_type == "PretrainedFromHF": SCREAMING_SNAKE_CASE__ : Any = ds_args.tokenizer_name_or_path else: raise ValueError(F'''Unrecognized tokenizer_type {tokenizer_type}''' ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """gpt2""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoTokenizer.from_pretrained(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = type(__lowerCAmelCase ).__name__ SCREAMING_SNAKE_CASE__ : Dict = tokenizer_class # Store the config to file. print("""Saving config""" ) config.save_pretrained(__lowerCAmelCase ) # Save tokenizer based on args print(F'''Adding {tokenizer_class} tokenizer files''' ) tokenizer.save_pretrained(__lowerCAmelCase ) # Store the state_dict to file. SCREAMING_SNAKE_CASE__ : Any = os.path.join(__lowerCAmelCase , """pytorch_model.bin""" ) print(F'''Saving checkpoint to "{output_checkpoint_file}"''' ) torch.save(__lowerCAmelCase , __lowerCAmelCase ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
12
0
from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class _UpperCamelCase : '''simple docstring''' a_ : int a_ : int class _UpperCamelCase : '''simple docstring''' def __init__( self : Tuple , _lowerCamelCase : int ): '''simple docstring''' __lowerCamelCase : list[list[Edge]] = [[] for _ in range(_lowerCamelCase )] __lowerCamelCase : List[str] = size def __getitem__( self : Any , _lowerCamelCase : int ): '''simple docstring''' return iter(self._graph[vertex] ) @property def _snake_case ( self : int ): '''simple docstring''' return self._size def _snake_case ( self : Union[str, Any] , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int ): '''simple docstring''' if weight not in (0, 1): raise ValueError("""Edge weight must be either 0 or 1.""" ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("""Vertex indexes must be in [0; size).""" ) self._graph[from_vertex].append(Edge(_lowerCamelCase , _lowerCamelCase ) ) def _snake_case ( self : List[Any] , _lowerCamelCase : int , _lowerCamelCase : int ): '''simple docstring''' __lowerCamelCase : Union[str, Any] = deque([start_vertex] ) __lowerCamelCase : list[int | None] = [None] * self.size __lowerCamelCase : Optional[int] = 0 while queue: __lowerCamelCase : Dict = queue.popleft() __lowerCamelCase : int = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: __lowerCamelCase : Dict = current_distance + edge.weight __lowerCamelCase : List[Any] = distances[edge.destination_vertex] if ( isinstance(_lowerCamelCase , _lowerCamelCase ) and new_distance >= dest_vertex_distance ): continue __lowerCamelCase : Dict = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("""No path from start_vertex to finish_vertex.""" ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
519
def _UpperCAmelCase ( UpperCAmelCase : int ): """simple docstring""" if n == 1 or not isinstance(UpperCAmelCase , UpperCAmelCase ): return 0 elif n == 2: return 1 else: __lowerCamelCase : Union[str, Any] = [0, 1] for i in range(2 , n + 1 ): sequence.append(sequence[i - 1] + sequence[i - 2] ) return sequence[n] def _UpperCAmelCase ( UpperCAmelCase : int ): """simple docstring""" __lowerCamelCase : Tuple = 0 __lowerCamelCase : Dict = 2 while digits < n: index += 1 __lowerCamelCase : str = len(str(fibonacci(UpperCAmelCase ) ) ) return index def _UpperCAmelCase ( UpperCAmelCase : int = 1_000 ): """simple docstring""" return fibonacci_digits_index(UpperCAmelCase ) if __name__ == "__main__": print(solution(int(str(input()).strip())))
519
1
'''simple docstring''' import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class UpperCAmelCase_ ( unittest.TestCase ): @slow def __UpperCAmelCase ( self : int ) -> Optional[Any]: lowerCAmelCase = AutoImageProcessor.from_pretrained('microsoft/dit-base-finetuned-rvlcdip' ) lowerCAmelCase = AutoModelForImageClassification.from_pretrained('microsoft/dit-base-finetuned-rvlcdip' ) model.to(UpperCAmelCase__ ) from datasets import load_dataset lowerCAmelCase = load_dataset('nielsr/rvlcdip-demo' ) lowerCAmelCase = dataset['train'][0]['image'].convert('RGB' ) lowerCAmelCase = image_processor(UpperCAmelCase__ , return_tensors='pt' ).to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): lowerCAmelCase = model(**UpperCAmelCase__ ) lowerCAmelCase = outputs.logits lowerCAmelCase = torch.Size((1, 1_6) ) self.assertEqual(logits.shape , UpperCAmelCase__ ) lowerCAmelCase = torch.tensor( [-0.4_158, -0.4_092, -0.4_347] , device=UpperCAmelCase__ , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , UpperCAmelCase__ , atol=1E-4 ) )
513
'''simple docstring''' from __future__ import annotations def a_ ( lowerCamelCase : list , lowerCamelCase : int ): # Checks if the entire collection has been sorted if len(lowerCamelCase ) <= 1 or n <= 1: return insert_next(lowerCamelCase , n - 1 ) rec_insertion_sort(lowerCamelCase , n - 1 ) def a_ ( lowerCamelCase : list , lowerCamelCase : int ): # Checks order between adjacent elements if index >= len(lowerCamelCase ) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order lowerCAmelCase , lowerCAmelCase = ( collection[index], collection[index - 1], ) insert_next(lowerCamelCase , index + 1 ) if __name__ == "__main__": __snake_case =input("""Enter integers separated by spaces: """) __snake_case =[int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
513
1
"""simple docstring""" UpperCamelCase = 0 # The first color of the flag. UpperCamelCase = 1 # The second color of the flag. UpperCamelCase = 2 # The third color of the flag. UpperCamelCase = (red, white, blue) def _lowerCamelCase ( UpperCAmelCase_ : list ) -> list: """simple docstring""" if not sequence: return [] if len(UpperCAmelCase_ ) == 1: return list(UpperCAmelCase_ ) A__ = 0 A__ = len(UpperCAmelCase_ ) - 1 A__ = 0 while mid <= high: if sequence[mid] == colors[0]: A__ , A__ = sequence[mid], sequence[low] low += 1 mid += 1 elif sequence[mid] == colors[1]: mid += 1 elif sequence[mid] == colors[2]: A__ , A__ = sequence[high], sequence[mid] high -= 1 else: A__ = F"""The elements inside the sequence must contains only {colors} values""" raise ValueError(UpperCAmelCase_ ) return sequence if __name__ == "__main__": import doctest doctest.testmod() UpperCamelCase = input("""Enter numbers separated by commas:\n""").strip() UpperCamelCase = [int(item.strip()) for item in user_input.split(""",""")] print(f'{dutch_national_flag_sort(unsorted)}')
104
"""simple docstring""" import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def snake_case__ ( self ) -> Dict: A__ = ["a", "b", "c"] # Defaults to last layer if both are None A__ , A__ = get_aligned_output_features_output_indices(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , ["c"] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , [2] ) # Out indices set to match out features A__ , A__ = get_aligned_output_features_output_indices(["a", "c"] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , ["a", "c"] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , [0, 2] ) # Out features set to match out indices A__ , A__ = get_aligned_output_features_output_indices(SCREAMING_SNAKE_CASE__ , [0, 2] , SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , ["a", "c"] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , [0, 2] ) # Out features selected from negative indices A__ , A__ = get_aligned_output_features_output_indices(SCREAMING_SNAKE_CASE__ , [-3, -1] , SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , ["a", "c"] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , [-3, -1] ) def snake_case__ ( self ) -> Dict: # Stage names must be set with self.assertRaises(SCREAMING_SNAKE_CASE__ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , SCREAMING_SNAKE_CASE__ ) # Out features must be a list with self.assertRaises(SCREAMING_SNAKE_CASE__ ): verify_out_features_out_indices(("a", "b") , (0, 1) , ["a", "b"] ) # Out features must be a subset of stage names with self.assertRaises(SCREAMING_SNAKE_CASE__ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , ["a"] ) # Out indices must be a list or tuple with self.assertRaises(SCREAMING_SNAKE_CASE__ ): verify_out_features_out_indices(SCREAMING_SNAKE_CASE__ , 0 , ["a", "b"] ) # Out indices must be a subset of stage names with self.assertRaises(SCREAMING_SNAKE_CASE__ ): verify_out_features_out_indices(SCREAMING_SNAKE_CASE__ , (0, 1) , ["a"] ) # Out features and out indices must be the same length with self.assertRaises(SCREAMING_SNAKE_CASE__ ): verify_out_features_out_indices(["a", "b"] , (0,) , ["a", "b", "c"] ) # Out features should match out indices with self.assertRaises(SCREAMING_SNAKE_CASE__ ): verify_out_features_out_indices(["a", "b"] , (0, 2) , ["a", "b", "c"] ) # Out features and out indices should be in order with self.assertRaises(SCREAMING_SNAKE_CASE__ ): verify_out_features_out_indices(["b", "a"] , (0, 1) , ["a", "b"] ) # Check passes with valid inputs verify_out_features_out_indices(["a", "b", "d"] , (0, 1, -1) , ["a", "b", "c", "d"] ) def snake_case__ ( self ) -> List[Any]: A__ = BackboneMixin() A__ = ["a", "b", "c"] A__ = ["a", "c"] A__ = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly A__ = ["a", "b"] self.assertEqual(backbone.out_features , ["a", "b"] ) self.assertEqual(backbone.out_indices , [0, 1] ) A__ = [-3, -1] self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [-3, -1] )
104
1
'''simple docstring''' import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py __A = '''\ @INPROCEEDINGS{Papineni02bleu:a, author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu}, title = {BLEU: a Method for Automatic Evaluation of Machine Translation}, booktitle = {}, year = {2002}, pages = {311--318} } @inproceedings{lin-och-2004-orange, title = "{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation", author = "Lin, Chin-Yew and Och, Franz Josef", booktitle = "{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics", month = "aug 23{--}aug 27", year = "2004", address = "Geneva, Switzerland", publisher = "COLING", url = "https://www.aclweb.org/anthology/C04-1072", pages = "501--507", } ''' __A = '''\ BLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another. Quality is considered to be the correspondence between a machine\'s output and that of a human: "the closer a machine translation is to a professional human translation, the better it is" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and remains one of the most popular automated and inexpensive metrics. Scores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations. Those scores are then averaged over the whole corpus to reach an estimate of the translation\'s overall quality. Intelligibility or grammatical correctness are not taken into account[citation needed]. BLEU\'s output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1 representing more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the reference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional reference translations will increase the BLEU score. ''' __A = ''' Computes BLEU score of translated segments against one or more references. Args: predictions: list of translations to score. Each translation should be tokenized into a list of tokens. references: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. max_order: Maximum n-gram order to use when computing BLEU score. smooth: Whether or not to apply Lin et al. 2004 smoothing. Returns: \'bleu\': bleu score, \'precisions\': geometric mean of n-gram precisions, \'brevity_penalty\': brevity penalty, \'length_ratio\': ratio of lengths, \'translation_length\': translation_length, \'reference_length\': reference_length Examples: >>> predictions = [ ... ["hello", "there", "general", "kenobi"], # tokenized prediction of the first sample ... ["foo", "bar", "foobar"] # tokenized prediction of the second sample ... ] >>> references = [ ... [["hello", "there", "general", "kenobi"], ["hello", "there", "!"]], # tokenized references for the first sample (2 references) ... [["foo", "bar", "foobar"]] # tokenized references for the second sample (1 reference) ... ] >>> bleu = datasets.load_metric("bleu") >>> results = bleu.compute(predictions=predictions, references=references) >>> print(results["bleu"]) 1.0 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string' , id='token') , id='sequence'), 'references': datasets.Sequence( datasets.Sequence(datasets.Value('string' , id='token') , id='sequence') , id='references'), }) , codebase_urls=['https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py'] , reference_urls=[ 'https://en.wikipedia.org/wiki/BLEU', 'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213', ] , ) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a=4 , __a=False) -> Any: """simple docstring""" __snake_case : Dict = compute_bleu( reference_corpus=__a , translation_corpus=__a , max_order=__a , smooth=__a) ((__snake_case) ,(__snake_case) ,(__snake_case) ,(__snake_case) ,(__snake_case) ,(__snake_case)) : Dict = score return { "bleu": bleu, "precisions": precisions, "brevity_penalty": bp, "length_ratio": ratio, "translation_length": translation_length, "reference_length": reference_length, }
61
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( A : float , A : list[float] ) -> float: """simple docstring""" if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __snake_case : List[str] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(A ) ) return round(A , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
61
1
'''simple docstring''' def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> float: if mass < 0: raise ValueError('The mass of a body cannot be negative' ) return 0.5 * mass * abs(lowerCAmelCase_ ) * abs(lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
358
'''simple docstring''' def __lowerCamelCase ( lowerCAmelCase_ = 1000000 ) -> int: _a : Optional[int] = set(range(3 , lowerCAmelCase_ , 2 ) ) primes.add(2 ) for p in range(3 , lowerCAmelCase_ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , lowerCAmelCase_ , lowerCAmelCase_ ) ) ) _a : Tuple = [float(lowerCAmelCase_ ) for n in range(limit + 1 )] for p in primes: for n in range(lowerCAmelCase_ , limit + 1 , lowerCAmelCase_ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(f"""{solution() = }""")
358
1
from random import randint, random def __lowerCamelCase ( A__ : int , A__ : int , A__ : int , A__ : bool = False , A__ : bool = False , A__ : int = 5 , ) -> list: lowerCamelCase_ : int = [[-1] * number_of_cells] # Create a highway without any car lowerCamelCase_ : List[Any] = 0 lowerCamelCase_ : int = max(A__ , 0 ) while i < number_of_cells: lowerCamelCase_ : Union[str, Any] = ( randint(0 , A__ ) if random_speed else initial_speed ) # Place the cars i += ( randint(1 , max_speed * 2 ) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def __lowerCamelCase ( A__ : list , A__ : int ) -> int: lowerCamelCase_ : Dict = 0 lowerCamelCase_ : Optional[Any] = highway_now[car_index + 1 :] for cell in range(len(A__ ) ): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(A__ , -1 ) def __lowerCamelCase ( A__ : list , A__ : float , A__ : int ) -> list: lowerCamelCase_ : Dict = len(A__ ) # Beforce calculations, the highway is empty lowerCamelCase_ : int = [-1] * number_of_cells for car_index in range(A__ ): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed lowerCamelCase_ : List[Any] = min(highway_now[car_index] + 1 , A__ ) # Number of empty cell before the next car lowerCamelCase_ : Optional[Any] = get_distance(A__ , A__ ) - 1 # We can't have the car causing an accident lowerCamelCase_ : Any = min(next_highway[car_index] , A__ ) if random() < probability: # Randomly, a driver will slow down lowerCamelCase_ : Tuple = max(next_highway[car_index] - 1 , 0 ) return next_highway def __lowerCamelCase ( A__ : list , A__ : int , A__ : float , A__ : int ) -> list: lowerCamelCase_ : List[Any] = len(highway[0] ) for i in range(A__ ): lowerCamelCase_ : List[Any] = update(highway[i] , A__ , A__ ) lowerCamelCase_ : Optional[Any] = [-1] * number_of_cells for car_index in range(A__ ): lowerCamelCase_ : Union[str, Any] = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) lowerCamelCase_ : Dict = (car_index + speed) % number_of_cells # Commit the change of position lowerCamelCase_ : Tuple = speed highway.append(A__ ) return highway if __name__ == "__main__": import doctest doctest.testmod()
171
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __lowerCamelCase ( A__ : Dict=None ) -> Tuple: if subparsers is not None: lowerCamelCase_ : List[str] = subparsers.add_parser("""test""" ) else: lowerCamelCase_ : Optional[int] = argparse.ArgumentParser("""Accelerate test command""" ) parser.add_argument( """--config_file""" , default=A__ , help=( """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """ """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """ """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """ """with 'huggingface'.""" ) , ) if subparsers is not None: parser.set_defaults(func=A__ ) return parser def __lowerCamelCase ( A__ : int ) -> int: lowerCamelCase_ : Optional[int] = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["""test_utils""", """scripts""", """test_script.py"""] ) if args.config_file is None: lowerCamelCase_ : Dict = script_name else: lowerCamelCase_ : List[Any] = f'''--config_file={args.config_file} {script_name}''' lowerCamelCase_ : Any = ["""accelerate-launch"""] + test_args.split() lowerCamelCase_ : Optional[int] = execute_subprocess_async(A__ , env=os.environ.copy() ) if result.returncode == 0: print("""Test is a success! You are ready for your distributed training!""" ) def __lowerCamelCase ( ) -> int: lowerCamelCase_ : Dict = test_command_parser() lowerCamelCase_ : Optional[Any] = parser.parse_args() test_command(A__ ) if __name__ == "__main__": main()
171
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer a_ = logging.get_logger(__name__) a_ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} # See all BART models at https://huggingface.co/models?filter=bart a_ = { '''vocab_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/vocab.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/vocab.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json''', }, '''merges_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/merges.txt''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/merges.txt''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json''', }, } a_ = { '''facebook/bart-base''': 1024, '''facebook/bart-large''': 1024, '''facebook/bart-large-mnli''': 1024, '''facebook/bart-large-cnn''': 1024, '''facebook/bart-large-xsum''': 1024, '''yjernite/bart_eli5''': 1024, } class __lowercase ( _UpperCAmelCase): """simple docstring""" _A : Optional[Any] = VOCAB_FILES_NAMES _A : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _A : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A : List[Any] = ["""input_ids""", """attention_mask"""] _A : List[Any] = BartTokenizer def __init__(self , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__="replace" , lowercase__="<s>" , lowercase__="</s>" , lowercase__="</s>" , lowercase__="<s>" , lowercase__="<unk>" , lowercase__="<pad>" , lowercase__="<mask>" , lowercase__=False , lowercase__=True , **lowercase__ , ): super().__init__( lowercase__ , lowercase__ , tokenizer_file=lowercase__ , errors=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , sep_token=lowercase__ , cls_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , mask_token=lowercase__ , add_prefix_space=lowercase__ , trim_offsets=lowercase__ , **lowercase__ , ) snake_case_ : List[Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , lowercase__ ) != add_prefix_space: snake_case_ : Union[str, Any] = getattr(lowercase__ , pre_tok_state.pop("""type""" ) ) snake_case_ : Union[str, Any] = add_prefix_space snake_case_ : Optional[Any] = pre_tok_class(**lowercase__ ) snake_case_ : List[Any] = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` snake_case_ : Dict = """post_processor""" snake_case_ : Tuple = getattr(self.backend_tokenizer , lowercase__ , lowercase__ ) if tokenizer_component_instance: snake_case_ : Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: snake_case_ : Tuple = tuple(state["""sep"""] ) if "cls" in state: snake_case_ : int = tuple(state["""cls"""] ) snake_case_ : Optional[int] = False if state.get("""add_prefix_space""" , lowercase__ ) != add_prefix_space: snake_case_ : Union[str, Any] = add_prefix_space snake_case_ : Any = True if state.get("""trim_offsets""" , lowercase__ ) != trim_offsets: snake_case_ : List[Any] = trim_offsets snake_case_ : List[str] = True if changes_to_apply: snake_case_ : Dict = getattr(lowercase__ , state.pop("""type""" ) ) snake_case_ : Optional[int] = component_class(**lowercase__ ) setattr(self.backend_tokenizer , lowercase__ , lowercase__ ) @property def __UpperCamelCase (self ): if self._mask_token is None: if self.verbose: logger.error("""Using mask_token, but it is not set yet.""" ) return None return str(self._mask_token ) @mask_token.setter def __UpperCamelCase (self , lowercase__ ): snake_case_ : Dict = AddedToken(lowercase__ , lstrip=lowercase__ , rstrip=lowercase__ ) if isinstance(lowercase__ , lowercase__ ) else value snake_case_ : List[str] = value def __UpperCamelCase (self , *lowercase__ , **lowercase__ ): snake_case_ : List[Any] = kwargs.get("""is_split_into_words""" , lowercase__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' """to use it with pretokenized inputs.""" ) return super()._batch_encode_plus(*lowercase__ , **lowercase__ ) def __UpperCamelCase (self , *lowercase__ , **lowercase__ ): snake_case_ : int = kwargs.get("""is_split_into_words""" , lowercase__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' """to use it with pretokenized inputs.""" ) return super()._encode_plus(*lowercase__ , **lowercase__ ) def __UpperCamelCase (self , lowercase__ , lowercase__ = None ): snake_case_ : Union[str, Any] = self._tokenizer.model.save(lowercase__ , name=lowercase__ ) return tuple(lowercase__ ) def __UpperCamelCase (self , lowercase__ , lowercase__=None ): snake_case_ : Optional[int] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __UpperCamelCase (self , lowercase__ , lowercase__ = None ): snake_case_ : List[Any] = [self.sep_token_id] snake_case_ : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
480
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) a_ = { '''configuration_trocr''': ['''TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TrOCRConfig'''], '''processing_trocr''': ['''TrOCRProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ '''TROCR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TrOCRForCausalLM''', '''TrOCRPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys a_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
480
1
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, ) else: from .modeling_text_unet import UNetFlatConditionModel from .pipeline_versatile_diffusion import VersatileDiffusionPipeline from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
579
"""simple docstring""" from timeit import timeit def A__ ( A__ ) -> int: '''simple docstring''' if number < 0: raise ValueError("the value of input must not be negative" ) _UpperCAmelCase = 0 while number: number &= number - 1 result += 1 return result def A__ ( A__ ) -> int: '''simple docstring''' if number < 0: raise ValueError("the value of input must not be negative" ) _UpperCAmelCase = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def A__ ( ) -> None: '''simple docstring''' def do_benchmark(A__ ) -> None: _UpperCAmelCase = "import __main__ as z" print(F"""Benchmark when {number = }:""" ) print(F"""{get_set_bits_count_using_modulo_operator(A__ ) = }""" ) _UpperCAmelCase = timeit("z.get_set_bits_count_using_modulo_operator(25)" , setup=A__ ) print(F"""timeit() runs in {timing} seconds""" ) print(F"""{get_set_bits_count_using_brian_kernighans_algorithm(A__ ) = }""" ) _UpperCAmelCase = timeit( "z.get_set_bits_count_using_brian_kernighans_algorithm(25)" , setup=A__ , ) print(F"""timeit() runs in {timing} seconds""" ) for number in (25, 37, 58, 0): do_benchmark(A__ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
579
1
from __future__ import annotations import os from typing import Any import requests UpperCamelCase_ = 'https://api.github.com' # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user UpperCamelCase_ = BASE_URL + '/user' # https://github.com/settings/tokens UpperCamelCase_ = os.environ.get('USER_TOKEN', '') def _UpperCAmelCase ( A ): '''simple docstring''' UpperCAmelCase__ ={ "Authorization": F"""token {auth_token}""", "Accept": "application/vnd.github.v3+json", } return requests.get(A , headers=A ).json() if __name__ == "__main__": # pragma: no cover if USER_TOKEN: for key, value in fetch_github_info(USER_TOKEN).items(): print(f"""{key}: {value}""") else: raise ValueError('\'USER_TOKEN\' field cannot be empty.')
625
from math import factorial def _UpperCAmelCase ( A = 20 ): '''simple docstring''' UpperCAmelCase__ =2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... UpperCAmelCase__ =n // 2 return int(factorial(A ) / (factorial(A ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: UpperCamelCase_ = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
625
1
def _lowerCAmelCase ( _lowerCAmelCase = 1 , _lowerCAmelCase = 1000 ) -> int: '''simple docstring''' __snake_case = 1 __snake_case = 0 for divide_by_number in range(_lowerCAmelCase , digit + 1 ): __snake_case = [] __snake_case = numerator for _ in range(1 , digit + 1 ): if now_divide in has_been_divided: if longest_list_length < len(_lowerCAmelCase ): __snake_case = len(_lowerCAmelCase ) __snake_case = divide_by_number else: has_been_divided.append(_lowerCAmelCase ) __snake_case = now_divide * 10 % divide_by_number return the_digit # Tests if __name__ == "__main__": import doctest doctest.testmod()
473
import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class UpperCamelCase( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : str ) -> Dict: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[Any]: '''simple docstring''' __snake_case = 1 __snake_case = 3 __snake_case = (3_2, 3_2) __snake_case = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE ) return image @property def SCREAMING_SNAKE_CASE_ ( self : int ) -> Any: '''simple docstring''' torch.manual_seed(0 ) __snake_case = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=3_2 , ) return model @property def SCREAMING_SNAKE_CASE_ ( self : Any ) -> str: '''simple docstring''' torch.manual_seed(0 ) __snake_case = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: '''simple docstring''' torch.manual_seed(0 ) __snake_case = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModel(SCREAMING_SNAKE_CASE ) @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: '''simple docstring''' def extract(*SCREAMING_SNAKE_CASE : List[str] , **SCREAMING_SNAKE_CASE : List[Any] ): class UpperCamelCase: def __init__( self : Dict ) -> Union[str, Any]: '''simple docstring''' __snake_case = torch.ones([0] ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: '''simple docstring''' self.pixel_values.to(SCREAMING_SNAKE_CASE ) return self return Out() return extract def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Dict: '''simple docstring''' __snake_case = "cpu" # ensure determinism for the device-dependent torch.Generator __snake_case = self.dummy_cond_unet __snake_case = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) __snake_case = self.dummy_vae __snake_case = self.dummy_text_encoder __snake_case = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk __snake_case = StableDiffusionPipeline( unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , vae=SCREAMING_SNAKE_CASE , text_encoder=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , safety_checker=SCREAMING_SNAKE_CASE , feature_extractor=self.dummy_extractor , ) __snake_case = sd_pipe.to(SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) __snake_case = "A painting of a squirrel eating a burger" __snake_case = torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(0 ) __snake_case = sd_pipe([prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) __snake_case = output.images __snake_case = torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(0 ) __snake_case = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=SCREAMING_SNAKE_CASE , )[0] __snake_case = image[0, -3:, -3:, -1] __snake_case = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __snake_case = np.array([0.5756, 0.6118, 0.5005, 0.5041, 0.5471, 0.4726, 0.4976, 0.4865, 0.4864] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case = "cpu" # ensure determinism for the device-dependent torch.Generator __snake_case = self.dummy_cond_unet __snake_case = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE ) __snake_case = self.dummy_vae __snake_case = self.dummy_text_encoder __snake_case = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk __snake_case = StableDiffusionPipeline( unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , vae=SCREAMING_SNAKE_CASE , text_encoder=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , safety_checker=SCREAMING_SNAKE_CASE , feature_extractor=self.dummy_extractor , ) __snake_case = sd_pipe.to(SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) __snake_case = "A painting of a squirrel eating a burger" __snake_case = torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(0 ) __snake_case = sd_pipe([prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) __snake_case = output.images __snake_case = torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(0 ) __snake_case = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=SCREAMING_SNAKE_CASE , )[0] __snake_case = image[0, -3:, -3:, -1] __snake_case = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __snake_case = np.array([0.5125, 0.5716, 0.4828, 0.5060, 0.5650, 0.4768, 0.5185, 0.4895, 0.4993] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[Any]: '''simple docstring''' __snake_case = StableDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-lms-pipe" , safety_checker=SCREAMING_SNAKE_CASE ) assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) assert isinstance(pipe.scheduler , SCREAMING_SNAKE_CASE ) assert pipe.safety_checker is None __snake_case = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(SCREAMING_SNAKE_CASE ) __snake_case = StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE ) # sanity check that the pipeline still works assert pipe.safety_checker is None __snake_case = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: '''simple docstring''' __snake_case = self.dummy_cond_unet __snake_case = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE ) __snake_case = self.dummy_vae __snake_case = self.dummy_text_encoder __snake_case = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # put models in fp16 __snake_case = unet.half() __snake_case = vae.half() __snake_case = bert.half() # make sure here that pndm scheduler skips prk __snake_case = StableDiffusionPipeline( unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , vae=SCREAMING_SNAKE_CASE , text_encoder=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , safety_checker=SCREAMING_SNAKE_CASE , feature_extractor=self.dummy_extractor , ) __snake_case = sd_pipe.to(SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) __snake_case = "A painting of a squirrel eating a burger" __snake_case = sd_pipe([prompt] , num_inference_steps=2 , output_type="np" ).images assert image.shape == (1, 6_4, 6_4, 3) @nightly @require_torch_gpu class UpperCamelCase( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=SCREAMING_SNAKE_CASE ) __snake_case = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) __snake_case = sd_pipe.to(SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) __snake_case = ( "portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle" " coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with" " anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and" " children from bahnhof zoo, detailed " ) __snake_case = 4_0_0_3_6_6_0_3_4_6 __snake_case = 7 # without safety guidance (sld_guidance_scale = 0) __snake_case = torch.manual_seed(SCREAMING_SNAKE_CASE ) __snake_case = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=SCREAMING_SNAKE_CASE , num_inference_steps=5_0 , output_type="np" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __snake_case = output.images __snake_case = image[0, -3:, -3:, -1] __snake_case = [0.2278, 0.2231, 0.2249, 0.2333, 0.2303, 0.1885, 0.2273, 0.2144, 0.2176] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 # without safety guidance (strong configuration) __snake_case = torch.manual_seed(SCREAMING_SNAKE_CASE ) __snake_case = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=SCREAMING_SNAKE_CASE , num_inference_steps=5_0 , output_type="np" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __snake_case = output.images __snake_case = image[0, -3:, -3:, -1] __snake_case = [0.2383, 0.2276, 0.236, 0.2192, 0.2186, 0.2053, 0.1971, 0.1901, 0.1719] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[str]: '''simple docstring''' __snake_case = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=SCREAMING_SNAKE_CASE ) __snake_case = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) __snake_case = sd_pipe.to(SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) __snake_case = "padme amidala taking a bath artwork, safe for work, no nudity" __snake_case = 2_7_3_4_9_7_1_7_5_5 __snake_case = 7 __snake_case = torch.manual_seed(SCREAMING_SNAKE_CASE ) __snake_case = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=SCREAMING_SNAKE_CASE , num_inference_steps=5_0 , output_type="np" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __snake_case = output.images __snake_case = image[0, -3:, -3:, -1] __snake_case = [0.3502, 0.3622, 0.3396, 0.3642, 0.3478, 0.3318, 0.35, 0.3348, 0.3297] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 __snake_case = torch.manual_seed(SCREAMING_SNAKE_CASE ) __snake_case = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=SCREAMING_SNAKE_CASE , num_inference_steps=5_0 , output_type="np" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __snake_case = output.images __snake_case = image[0, -3:, -3:, -1] __snake_case = [0.5531, 0.5206, 0.4895, 0.5156, 0.5182, 0.4751, 0.4802, 0.4803, 0.4443] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> int: '''simple docstring''' __snake_case = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" ) __snake_case = sd_pipe.to(SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) __snake_case = ( "the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c." " leyendecker" ) __snake_case = 1_0_4_4_3_5_5_2_3_4 __snake_case = 1_2 __snake_case = torch.manual_seed(SCREAMING_SNAKE_CASE ) __snake_case = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=SCREAMING_SNAKE_CASE , num_inference_steps=5_0 , output_type="np" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __snake_case = output.images __snake_case = image[0, -3:, -3:, -1] __snake_case = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-7 __snake_case = torch.manual_seed(SCREAMING_SNAKE_CASE ) __snake_case = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=SCREAMING_SNAKE_CASE , num_inference_steps=5_0 , output_type="np" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __snake_case = output.images __snake_case = image[0, -3:, -3:, -1] __snake_case = np.array([0.5818, 0.6285, 0.6835, 0.6019, 0.625, 0.6754, 0.6096, 0.6334, 0.6561] ) assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
473
1
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def a__ ( lowerCAmelCase__=None ) -> List[Any]: if subparsers is not None: UpperCAmelCase__ : Union[str, Any] = subparsers.add_parser('''test''' ) else: UpperCAmelCase__ : List[Any] = argparse.ArgumentParser('''Accelerate test command''' ) parser.add_argument( '''--config_file''' , default=lowerCAmelCase__ , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase__ ) return parser def a__ ( lowerCAmelCase__ ) -> Union[str, Any]: UpperCAmelCase__ : str = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ['''test_utils''', '''scripts''', '''test_script.py'''] ) if args.config_file is None: UpperCAmelCase__ : Dict = script_name else: UpperCAmelCase__ : Optional[Any] = F"""--config_file={args.config_file} {script_name}""" UpperCAmelCase__ : Any = ['''accelerate-launch'''] + test_args.split() UpperCAmelCase__ : List[str] = execute_subprocess_async(lowerCAmelCase__ , env=os.environ.copy() ) if result.returncode == 0: print('''Test is a success! You are ready for your distributed training!''' ) def a__ ( ) -> Union[str, Any]: UpperCAmelCase__ : str = test_command_parser() UpperCAmelCase__ : Tuple = parser.parse_args() test_command(lowerCAmelCase__ ) if __name__ == "__main__": main()
75
'''simple docstring''' import random from typing import Any def a__ ( lowerCAmelCase__ ) -> list[Any]: for _ in range(len(lowerCAmelCase__ ) ): UpperCAmelCase__ : int = random.randint(0 , len(lowerCAmelCase__ ) - 1 ) UpperCAmelCase__ : Optional[int] = random.randint(0 , len(lowerCAmelCase__ ) - 1 ) UpperCAmelCase__ , UpperCAmelCase__ : List[str] = data[b], data[a] return data if __name__ == "__main__": UpperCamelCase__ = [0, 1, 2, 3, 4, 5, 6, 7] UpperCamelCase__ = ['''python''', '''says''', '''hello''', '''!'''] print('''Fisher-Yates Shuffle:''') print('''List''', integers, strings) print('''FY Shuffle''', fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
75
1
import sys UpperCamelCase__ = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def __magic_name__( __UpperCAmelCase ) -> int: '''simple docstring''' _lowerCamelCase = 1 for digit in s: product *= int(UpperCAmelCase__ ) return product def __magic_name__( __UpperCAmelCase = N ) -> int: '''simple docstring''' _lowerCamelCase = -sys.maxsize - 1 _lowerCamelCase = n[:13] _lowerCamelCase = 13 while cur_index < len(UpperCAmelCase__ ) - 13: if int(n[cur_index] ) >= int(substr[0] ): _lowerCamelCase = substr[1:] + n[cur_index] cur_index += 1 else: _lowerCamelCase = max(UpperCAmelCase__ , str_eval(UpperCAmelCase__ ) ) _lowerCamelCase = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(f'''{solution() = }''')
708
import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available from ..wavaveca.test_feature_extraction_wavaveca import floats_list if is_pyctcdecode_available(): from huggingface_hub import snapshot_download from pyctcdecode import BeamSearchDecoderCTC from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput if is_torch_available(): from transformers import WavaVecaForCTC @require_pyctcdecode class UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" _lowerCamelCase = '''| <pad> <unk> <s> </s> a b c d e f g h i j k'''.split() _lowerCamelCase = dict(zip(A_ , range(len(A_ ) ) ) ) _lowerCamelCase = { '''unk_token''': '''<unk>''', '''bos_token''': '''<s>''', '''eos_token''': '''</s>''', } _lowerCamelCase = { '''feature_size''': 1, '''padding_value''': 0.0, '''sampling_rate''': 1_60_00, '''return_attention_mask''': False, '''do_normalize''': True, } _lowerCamelCase = tempfile.mkdtemp() _lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _lowerCamelCase = os.path.join(self.tmpdirname , A_ ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(A_ ) + '''\n''' ) with open(self.feature_extraction_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(A_ ) + '''\n''' ) # load decoder from hub _lowerCamelCase = '''hf-internal-testing/ngram-beam-search-decoder''' def UpperCamelCase_ ( self , **A_ ) -> str: """simple docstring""" _lowerCamelCase = self.add_kwargs_tokens_map.copy() kwargs.update(A_ ) return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname , **A_ ) def UpperCamelCase_ ( self , **A_ ) -> Optional[Any]: """simple docstring""" return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname , **A_ ) def UpperCamelCase_ ( self , **A_ ) -> int: """simple docstring""" return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name , **A_ ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) processor.save_pretrained(self.tmpdirname ) _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname ) # tokenizer self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , A_ ) # feature extractor self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , A_ ) # decoder self.assertEqual(processor.decoder._alphabet.labels , decoder._alphabet.labels ) self.assertEqual( processor.decoder.model_container[decoder._model_key]._unigram_set , decoder.model_container[decoder._model_key]._unigram_set , ) self.assertIsInstance(processor.decoder , A_ ) def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" _lowerCamelCase = WavaVecaProcessorWithLM( tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) processor.save_pretrained(self.tmpdirname ) # make sure that error is thrown when decoder alphabet doesn't match _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained( self.tmpdirname , alpha=5.0 , beta=3.0 , score_boundary=-7.0 , unk_score_offset=3 ) # decoder self.assertEqual(processor.language_model.alpha , 5.0 ) self.assertEqual(processor.language_model.beta , 3.0 ) self.assertEqual(processor.language_model.score_boundary , -7.0 ) self.assertEqual(processor.language_model.unk_score_offset , 3 ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" _lowerCamelCase = self.get_tokenizer() # add token to trigger raise tokenizer.add_tokens(['''xx'''] ) with self.assertRaisesRegex(A_ , '''include''' ): WavaVecaProcessorWithLM( tokenizer=A_ , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = floats_list((3, 10_00) ) _lowerCamelCase = feature_extractor(A_ , return_tensors='''np''' ) _lowerCamelCase = processor(A_ , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = '''This is a test string''' _lowerCamelCase = processor(text=A_ ) _lowerCamelCase = tokenizer(A_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCamelCase_ ( self , A_=(2, 10, 16) , A_=77 ) -> Optional[Any]: """simple docstring""" np.random.seed(A_ ) return np.random.rand(*A_ ) def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = self._get_dummy_logits(shape=(10, 16) , seed=13 ) _lowerCamelCase = processor.decode(A_ ) _lowerCamelCase = decoder.decode_beams(A_ )[0] self.assertEqual(decoded_decoder[0] , decoded_processor.text ) self.assertEqual('''</s> <s> </s>''' , decoded_processor.text ) self.assertEqual(decoded_decoder[-2] , decoded_processor.logit_score ) self.assertEqual(decoded_decoder[-1] , decoded_processor.lm_score ) @parameterized.expand([[None], ['''fork'''], ['''spawn''']] ) def UpperCamelCase_ ( self , A_ ) -> int: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = self._get_dummy_logits() # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM. # otherwise, the LM won't be available to the pool's sub-processes. # manual logic used to allow parameterized test for both pool=None and pool=Pool(...) if pool_context is None: _lowerCamelCase = processor.batch_decode(A_ ) else: with get_context(A_ ).Pool() as pool: _lowerCamelCase = processor.batch_decode(A_ , A_ ) _lowerCamelCase = list(A_ ) with get_context('''fork''' ).Pool() as p: _lowerCamelCase = decoder.decode_beams_batch(A_ , A_ ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = [], [], [] for beams in decoded_beams: texts_decoder.append(beams[0][0] ) logit_scores_decoder.append(beams[0][-2] ) lm_scores_decoder.append(beams[0][-1] ) self.assertListEqual(A_ , decoded_processor.text ) self.assertListEqual(['''<s> <s> </s>''', '''<s> <s> <s>'''] , decoded_processor.text ) self.assertListEqual(A_ , decoded_processor.logit_score ) self.assertListEqual(A_ , decoded_processor.lm_score ) def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = self._get_dummy_logits() _lowerCamelCase = 15 _lowerCamelCase = -20.0 _lowerCamelCase = -4.0 _lowerCamelCase = processor.batch_decode( A_ , beam_width=A_ , beam_prune_logp=A_ , token_min_logp=A_ , ) _lowerCamelCase = decoded_processor_out.text _lowerCamelCase = list(A_ ) with get_context('''fork''' ).Pool() as pool: _lowerCamelCase = decoder.decode_beams_batch( A_ , A_ , beam_width=A_ , beam_prune_logp=A_ , token_min_logp=A_ , ) _lowerCamelCase = [d[0][0] for d in decoded_decoder_out] _lowerCamelCase = [d[0][2] for d in decoded_decoder_out] _lowerCamelCase = [d[0][3] for d in decoded_decoder_out] self.assertListEqual(A_ , A_ ) self.assertListEqual(['''</s> <s> <s>''', '''<s> <s> <s>'''] , A_ ) self.assertTrue(np.array_equal(A_ , decoded_processor_out.logit_score ) ) self.assertTrue(np.allclose([-20.054, -18.447] , A_ , atol=1E-3 ) ) self.assertTrue(np.array_equal(A_ , decoded_processor_out.lm_score ) ) self.assertTrue(np.allclose([-15.554, -13.9474] , A_ , atol=1E-3 ) ) def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = self._get_dummy_logits() _lowerCamelCase = 2.0 _lowerCamelCase = 5.0 _lowerCamelCase = -20.0 _lowerCamelCase = True _lowerCamelCase = processor.batch_decode( A_ , alpha=A_ , beta=A_ , unk_score_offset=A_ , lm_score_boundary=A_ , ) _lowerCamelCase = decoded_processor_out.text _lowerCamelCase = list(A_ ) decoder.reset_params( alpha=A_ , beta=A_ , unk_score_offset=A_ , lm_score_boundary=A_ , ) with get_context('''fork''' ).Pool() as pool: _lowerCamelCase = decoder.decode_beams_batch( A_ , A_ , ) _lowerCamelCase = [d[0][0] for d in decoded_decoder_out] self.assertListEqual(A_ , A_ ) self.assertListEqual(['''<s> </s> <s> </s> </s>''', '''</s> </s> <s> </s> </s>'''] , A_ ) _lowerCamelCase = processor.decoder.model_container[processor.decoder._model_key] self.assertEqual(lm_model.alpha , 2.0 ) self.assertEqual(lm_model.beta , 5.0 ) self.assertEqual(lm_model.unk_score_offset , -20.0 ) self.assertEqual(lm_model.score_boundary , A_ ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = processor.decoder.model_container[processor.decoder._model_key] _lowerCamelCase = Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute() _lowerCamelCase = os.listdir(A_ ) _lowerCamelCase = ['''alphabet.json''', '''language_model'''] downloaded_decoder_files.sort() expected_decoder_files.sort() # test that only decoder relevant files from # https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main # are downloaded and none of the rest (e.g. README.md, ...) self.assertListEqual(A_ , A_ ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" _lowerCamelCase = snapshot_download('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained(A_ ) _lowerCamelCase = processor.decoder.model_container[processor.decoder._model_key] _lowerCamelCase = Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute() _lowerCamelCase = os.listdir(A_ ) _lowerCamelCase = os.listdir(A_ ) local_decoder_files.sort() expected_decoder_files.sort() # test that both decoder form hub and local files in cache are the same self.assertListEqual(A_ , A_ ) def UpperCamelCase_ ( self ) -> int: """simple docstring""" _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = AutoProcessor.from_pretrained('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = floats_list((3, 10_00) ) _lowerCamelCase = processor_wavaveca(A_ , return_tensors='''np''' ) _lowerCamelCase = processor_auto(A_ , return_tensors='''np''' ) for key in input_wavaveca.keys(): self.assertAlmostEqual(input_wavaveca[key].sum() , input_auto[key].sum() , delta=1E-2 ) _lowerCamelCase = self._get_dummy_logits() _lowerCamelCase = processor_wavaveca.batch_decode(A_ ) _lowerCamelCase = processor_auto.batch_decode(A_ ) self.assertListEqual(decoded_wavaveca.text , decoded_auto.text ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) self.assertListEqual( processor.model_input_names , feature_extractor.model_input_names , msg='''`processor` and `feature_extractor` model input names do not match''' , ) @staticmethod def UpperCamelCase_ ( A_ , A_ ) -> str: """simple docstring""" _lowerCamelCase = [d[key] for d in offsets] return retrieved_list def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = self._get_dummy_logits()[0] _lowerCamelCase = processor.decode(A_ , output_word_offsets=A_ ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue('''text''' in outputs ) self.assertTrue('''word_offsets''' in outputs ) self.assertTrue(isinstance(A_ , A_ ) ) self.assertEqual(''' '''.join(self.get_from_offsets(outputs['''word_offsets'''] , '''word''' ) ) , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''word''' ) , ['''<s>''', '''<s>''', '''</s>'''] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''start_offset''' ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''end_offset''' ) , [1, 3, 5] ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = self._get_dummy_logits() _lowerCamelCase = processor.batch_decode(A_ , output_word_offsets=A_ ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue('''text''' in outputs ) self.assertTrue('''word_offsets''' in outputs ) self.assertTrue(isinstance(A_ , A_ ) ) self.assertListEqual( [''' '''.join(self.get_from_offsets(A_ , '''word''' ) ) for o in outputs['''word_offsets''']] , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''word''' ) , ['''<s>''', '''<s>''', '''</s>'''] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''start_offset''' ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''end_offset''' ) , [1, 3, 5] ) @slow @require_torch @require_torchaudio def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" import torch _lowerCamelCase = load_dataset('''common_voice''' , '''en''' , split='''train''' , streaming=A_ ) _lowerCamelCase = ds.cast_column('''audio''' , datasets.Audio(sampling_rate=1_60_00 ) ) _lowerCamelCase = iter(A_ ) _lowerCamelCase = next(A_ ) _lowerCamelCase = AutoProcessor.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' ) _lowerCamelCase = WavaVecaForCTC.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' ) # compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train _lowerCamelCase = processor(sample['''audio''']['''array'''] , return_tensors='''pt''' ).input_values with torch.no_grad(): _lowerCamelCase = model(A_ ).logits.cpu().numpy() _lowerCamelCase = processor.decode(logits[0] , output_word_offsets=A_ ) _lowerCamelCase = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate _lowerCamelCase = [ { '''start_time''': d['''start_offset'''] * time_offset, '''end_time''': d['''end_offset'''] * time_offset, '''word''': d['''word'''], } for d in output['''word_offsets'''] ] _lowerCamelCase = '''WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL''' # output words self.assertEqual(''' '''.join(self.get_from_offsets(A_ , '''word''' ) ) , A_ ) self.assertEqual(''' '''.join(self.get_from_offsets(A_ , '''word''' ) ) , output.text ) # output times _lowerCamelCase = torch.tensor(self.get_from_offsets(A_ , '''start_time''' ) ) _lowerCamelCase = torch.tensor(self.get_from_offsets(A_ , '''end_time''' ) ) # fmt: off _lowerCamelCase = torch.tensor([1.4199, 1.6599, 2.2599, 3.0, 3.24, 3.5999, 3.7999, 4.0999, 4.26, 4.94, 5.28, 5.6599, 5.78, 5.94, 6.32, 6.5399, 6.6599] ) _lowerCamelCase = torch.tensor([1.5399, 1.8999, 2.9, 3.16, 3.5399, 3.72, 4.0199, 4.1799, 4.76, 5.1599, 5.5599, 5.6999, 5.86, 6.1999, 6.38, 6.6199, 6.94] ) # fmt: on self.assertTrue(torch.allclose(A_ , A_ , atol=0.01 ) ) self.assertTrue(torch.allclose(A_ , A_ , atol=0.01 ) )
638
0
'''simple docstring''' import unittest from knapsack import greedy_knapsack as kp class snake_case__ ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : Tuple ) -> Tuple: """simple docstring""" snake_case : str = [10, 20, 30, 40, 50, 60] snake_case : Any = [2, 4, 6, 8, 10, 12] snake_case : Optional[Any] = 100 self.assertEqual(kp.calc_profit(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) , 210 ) def lowerCAmelCase ( self : List[Any] ) -> Any: """simple docstring""" self.assertRaisesRegex(UpperCamelCase__ , '''max_weight must greater than zero.''' ) def lowerCAmelCase ( self : List[str] ) -> Optional[int]: """simple docstring""" self.assertRaisesRegex(UpperCamelCase__ , '''Weight can not be negative.''' ) def lowerCAmelCase ( self : Optional[int] ) -> int: """simple docstring""" self.assertRaisesRegex(UpperCamelCase__ , '''Profit can not be negative.''' ) def lowerCAmelCase ( self : str ) -> Dict: """simple docstring""" self.assertRaisesRegex(UpperCamelCase__ , '''max_weight must greater than zero.''' ) def lowerCAmelCase ( self : Any ) -> Union[str, Any]: """simple docstring""" self.assertRaisesRegex( UpperCamelCase__ , '''The length of profit and weight must be same.''' ) if __name__ == "__main__": unittest.main()
638
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase__ = {"configuration_encoder_decoder": ["EncoderDecoderConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = ["EncoderDecoderModel"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = ["TFEncoderDecoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = ["FlaxEncoderDecoderModel"] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys lowercase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
638
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class snake_case__ ( metaclass=lowercase__ ): """simple docstring""" _SCREAMING_SNAKE_CASE = ["""torch""", """scipy"""] def __init__( self : List[Any], *_snake_case : int, **_snake_case : Dict ) ->Dict: requires_backends(self, ['torch', 'scipy'] ) @classmethod def lowercase_ ( cls : Optional[int], *_snake_case : Union[str, Any], **_snake_case : str ) ->int: requires_backends(cls, ['torch', 'scipy'] ) @classmethod def lowercase_ ( cls : Any, *_snake_case : List[Any], **_snake_case : Optional[Any] ) ->List[str]: requires_backends(cls, ['torch', 'scipy'] )
700
import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def lowercase_ (A : Optional[int] , A : Tuple , A : List[Any] , A : List[str]="attention" ): snake_case__ : str = params[F'''{prefix}/layers_{i}/{layer_name}/key/kernel'''] snake_case__ : List[str] = params[F'''{prefix}/layers_{i}/{layer_name}/out/kernel'''] snake_case__ : Optional[int] = params[F'''{prefix}/layers_{i}/{layer_name}/query/kernel'''] snake_case__ : Union[str, Any] = params[F'''{prefix}/layers_{i}/{layer_name}/value/kernel'''] return k, o, q, v def lowercase_ (A : Tuple , A : Union[str, Any] , A : int , A : Any=False ): if split_mlp_wi: snake_case__ : Dict = params[F'''{prefix}/layers_{i}/mlp/wi_0/kernel'''] snake_case__ : List[str] = params[F'''{prefix}/layers_{i}/mlp/wi_1/kernel'''] snake_case__ : Optional[Any] = (wi_a, wi_a) else: snake_case__ : Optional[Any] = params[F'''{prefix}/layers_{i}/mlp/wi/kernel'''] snake_case__ : Tuple = params[F'''{prefix}/layers_{i}/mlp/wo/kernel'''] return wi, wo def lowercase_ (A : Optional[int] , A : Dict , A : Any , A : List[str] ): return params[F'''{prefix}/layers_{i}/{layer_name}/scale'''] def lowercase_ (A : dict , *, A : int , A : bool ): snake_case__ : Dict = traverse_util.flatten_dict(variables['target'] ) snake_case__ : Union[str, Any] = {'/'.join(A ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi snake_case__ : Union[str, Any] = 'encoder/layers_0/mlp/wi_0/kernel' in old print('Split MLP:' , A ) snake_case__ : int = collections.OrderedDict() # Shared embeddings. snake_case__ : Dict = old['token_embedder/embedding'] # Encoder. for i in range(A ): # Block i, layer 0 (Self Attention). snake_case__ : Dict = tax_layer_norm_lookup(A , A , 'encoder' , 'pre_attention_layer_norm' ) snake_case__ , snake_case__ , snake_case__ , snake_case__ : Dict = tax_attention_lookup(A , A , 'encoder' , 'attention' ) snake_case__ : Optional[Any] = layer_norm snake_case__ : Union[str, Any] = k.T snake_case__ : List[Any] = o.T snake_case__ : Any = q.T snake_case__ : Union[str, Any] = v.T # Block i, layer 1 (MLP). snake_case__ : List[str] = tax_layer_norm_lookup(A , A , 'encoder' , 'pre_mlp_layer_norm' ) snake_case__ , snake_case__ : Dict = tax_mlp_lookup(A , A , 'encoder' , A ) snake_case__ : Optional[int] = layer_norm if split_mlp_wi: snake_case__ : Union[str, Any] = wi[0].T snake_case__ : int = wi[1].T else: snake_case__ : Optional[int] = wi.T snake_case__ : Tuple = wo.T snake_case__ : Optional[int] = old[ 'encoder/relpos_bias/rel_embedding' ].T snake_case__ : str = old['encoder/encoder_norm/scale'] if not is_encoder_only: # Decoder. for i in range(A ): # Block i, layer 0 (Self Attention). snake_case__ : List[str] = tax_layer_norm_lookup(A , A , 'decoder' , 'pre_self_attention_layer_norm' ) snake_case__ , snake_case__ , snake_case__ , snake_case__ : List[str] = tax_attention_lookup(A , A , 'decoder' , 'self_attention' ) snake_case__ : int = layer_norm snake_case__ : List[Any] = k.T snake_case__ : Tuple = o.T snake_case__ : Any = q.T snake_case__ : List[str] = v.T # Block i, layer 1 (Cross Attention). snake_case__ : List[str] = tax_layer_norm_lookup(A , A , 'decoder' , 'pre_cross_attention_layer_norm' ) snake_case__ , snake_case__ , snake_case__ , snake_case__ : int = tax_attention_lookup(A , A , 'decoder' , 'encoder_decoder_attention' ) snake_case__ : List[Any] = layer_norm snake_case__ : Union[str, Any] = k.T snake_case__ : List[str] = o.T snake_case__ : List[str] = q.T snake_case__ : List[Any] = v.T # Block i, layer 2 (MLP). snake_case__ : Any = tax_layer_norm_lookup(A , A , 'decoder' , 'pre_mlp_layer_norm' ) snake_case__ , snake_case__ : Tuple = tax_mlp_lookup(A , A , 'decoder' , A ) snake_case__ : List[str] = layer_norm if split_mlp_wi: snake_case__ : Any = wi[0].T snake_case__ : str = wi[1].T else: snake_case__ : Optional[int] = wi.T snake_case__ : int = wo.T snake_case__ : Dict = old['decoder/decoder_norm/scale'] snake_case__ : int = old[ 'decoder/relpos_bias/rel_embedding' ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: snake_case__ : int = old['decoder/logits_dense/kernel'].T return new def lowercase_ (A : List[Any] , A : bool ): snake_case__ : Dict = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: snake_case__ : Any = state_dict['shared.weight'] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: snake_case__ : Optional[int] = state_dict['shared.weight'] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('Using shared word embeddings as lm_head.' ) snake_case__ : List[Any] = state_dict['shared.weight'] return state_dict def lowercase_ (A : Union[str, Any] , A : Any , A : Union[str, Any] , A : Tuple ): snake_case__ : Optional[Any] = checkpoints.load_tax_checkpoint(A ) snake_case__ : List[str] = convert_tax_to_pytorch(A , num_layers=config.num_layers , is_encoder_only=A ) snake_case__ : Optional[int] = make_state_dict(A , A ) model.load_state_dict(A , strict=A ) def lowercase_ (A : List[str] , A : Union[str, Any] , A : Optional[Any] , A : bool = False ): snake_case__ : str = TaConfig.from_json_file(A ) print(F'''Building PyTorch model from configuration: {config}''' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: snake_case__ : List[str] = TaEncoderModel(A ) else: snake_case__ : str = TaForConditionalGeneration(A ) # Load weights from tf checkpoint load_tax_weights_in_ta(A , A , A , A ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(A ) # Verify that we can load the checkpoint. model.from_pretrained(A ) print('Done' ) if __name__ == "__main__": a_ :Tuple = argparse.ArgumentParser(description="Converts a native T5X checkpoint into a PyTorch checkpoint.") # Required parameters parser.add_argument( "--t5x_checkpoint_path", default=None, type=str, required=True, help="Path to the T5X checkpoint." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_encoder_only", action="store_true", help="Check if the model is encoder-decoder model", default=False ) a_ :List[Any] = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
243
0
import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class _UpperCAmelCase ( unittest.TestCase , _UpperCamelCase ): """simple docstring""" def lowercase ( self : Optional[int] ) -> Optional[int]: __lowerCAmelCase = load_tool('text-to-speech' ) self.tool.setup() def lowercase ( self : Union[str, Any] ) -> Dict: # SpeechT5 isn't deterministic torch.manual_seed(0 ) __lowerCAmelCase = self.tool('hey' ) __lowerCAmelCase = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_00_59_66_66_88_32_11_58_29, -0.0_00_36_57_64_01_90_79_50_64, -0.00_01_34_39_50_27_99_88_34_85] ) , ) ) def lowercase ( self : Union[str, Any] ) -> Any: # SpeechT5 isn't deterministic torch.manual_seed(0 ) __lowerCAmelCase = self.tool('hey' ) __lowerCAmelCase = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_00_59_66_66_88_32_11_58_29, -0.0_00_36_57_64_01_90_79_50_64, -0.00_01_34_39_50_27_99_88_34_85] ) , ) )
53
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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class lowerCamelCase__ ( unittest.TestCase ): def __init__( self : List[str] , lowercase__ : Any , lowercase__ : List[Any]=7 , lowercase__ : List[str]=3 , lowercase__ : str=18 , lowercase__ : List[Any]=30 , lowercase__ : Optional[int]=4_00 , lowercase__ : Dict=True , lowercase__ : List[str]=None , lowercase__ : int=True , lowercase__ : Tuple=None , lowercase__ : int=True , lowercase__ : Tuple=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] , lowercase__ : Optional[int]=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] , lowercase__ : Any=True , ): _lowerCAmelCase = size if size is not None else {'height': 2_24, 'width': 2_24} _lowerCAmelCase = crop_size if crop_size is not None else {'height': 18, 'width': 18} _lowerCAmelCase = parent _lowerCAmelCase = batch_size _lowerCAmelCase = num_channels _lowerCAmelCase = image_size _lowerCAmelCase = min_resolution _lowerCAmelCase = max_resolution _lowerCAmelCase = do_resize _lowerCAmelCase = size _lowerCAmelCase = do_center_crop _lowerCAmelCase = crop_size _lowerCAmelCase = do_normalize _lowerCAmelCase = image_mean _lowerCAmelCase = image_std _lowerCAmelCase = do_convert_rgb def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def SCREAMING_SNAKE_CASE__ ( self : List[str] , lowercase__ : Tuple=False , lowercase__ : List[Any]=False , lowercase__ : str=False ): assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: _lowerCAmelCase = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 2_55 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: _lowerCAmelCase = [] for i in range(self.batch_size ): _lowerCAmelCase , _lowerCAmelCase = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(2_55 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension _lowerCAmelCase = [Image.fromarray(np.moveaxis(lowercase__ , 0 , -1 ) ) for x in image_inputs] if torchify: _lowerCAmelCase = [torch.from_numpy(lowercase__ ) for x in image_inputs] return image_inputs @require_torch @require_vision class lowerCamelCase__ ( UpperCAmelCase ,unittest.TestCase ): UpperCamelCase__ =ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ ( self : Tuple ): _lowerCAmelCase = ChineseCLIPImageProcessingTester(self , do_center_crop=lowercase__ ) @property def SCREAMING_SNAKE_CASE__ ( self : Any ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ ( self : Tuple ): _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , 'do_resize' ) ) self.assertTrue(hasattr(lowercase__ , 'size' ) ) self.assertTrue(hasattr(lowercase__ , 'do_center_crop' ) ) self.assertTrue(hasattr(lowercase__ , 'center_crop' ) ) self.assertTrue(hasattr(lowercase__ , 'do_normalize' ) ) self.assertTrue(hasattr(lowercase__ , 'image_mean' ) ) self.assertTrue(hasattr(lowercase__ , 'image_std' ) ) self.assertTrue(hasattr(lowercase__ , 'do_convert_rgb' ) ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): _lowerCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 2_24, 'width': 2_24} ) self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18} ) _lowerCAmelCase = 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 SCREAMING_SNAKE_CASE__ ( self : List[Any] ): pass def SCREAMING_SNAKE_CASE__ ( self : str ): # Initialize image_processing _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _lowerCAmelCase = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input _lowerCAmelCase = 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 _lowerCAmelCase = image_processing(lowercase__ , 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 SCREAMING_SNAKE_CASE__ ( self : Any ): # Initialize image_processing _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _lowerCAmelCase = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , numpify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , np.ndarray ) # Test not batched input _lowerCAmelCase = 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 _lowerCAmelCase = image_processing(lowercase__ , 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 SCREAMING_SNAKE_CASE__ ( self : int ): # Initialize image_processing _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _lowerCAmelCase = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , torchify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , torch.Tensor ) # Test not batched input _lowerCAmelCase = 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 _lowerCAmelCase = image_processing(lowercase__ , 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'], ) , ) @require_torch @require_vision class lowerCamelCase__ ( UpperCAmelCase ,unittest.TestCase ): UpperCamelCase__ =ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): _lowerCAmelCase = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=lowercase__ ) _lowerCAmelCase = 3 @property def SCREAMING_SNAKE_CASE__ ( self : Tuple ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , 'do_resize' ) ) self.assertTrue(hasattr(lowercase__ , 'size' ) ) self.assertTrue(hasattr(lowercase__ , 'do_center_crop' ) ) self.assertTrue(hasattr(lowercase__ , 'center_crop' ) ) self.assertTrue(hasattr(lowercase__ , 'do_normalize' ) ) self.assertTrue(hasattr(lowercase__ , 'image_mean' ) ) self.assertTrue(hasattr(lowercase__ , 'image_std' ) ) self.assertTrue(hasattr(lowercase__ , 'do_convert_rgb' ) ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): pass def SCREAMING_SNAKE_CASE__ ( self : Dict ): # Initialize image_processing _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _lowerCAmelCase = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input _lowerCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _lowerCAmelCase = image_processing(lowercase__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
192
0
from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
719
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roberta import RobertaTokenizer _A : int = logging.get_logger(__name__) _A : int = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} _A : Optional[int] = { 'vocab_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/vocab.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/vocab.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/vocab.json', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json', 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json' ), }, 'merges_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/merges.txt', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/merges.txt', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/merges.txt', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt', 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt' ), }, 'tokenizer_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/tokenizer.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/tokenizer.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json', 'roberta-base-openai-detector': ( 'https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json' ), 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json' ), }, } _A : Any = { 'roberta-base': 5_12, 'roberta-large': 5_12, 'roberta-large-mnli': 5_12, 'distilroberta-base': 5_12, 'roberta-base-openai-detector': 5_12, 'roberta-large-openai-detector': 5_12, } class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): _UpperCAmelCase : str = VOCAB_FILES_NAMES _UpperCAmelCase : str = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : int = ["input_ids", "attention_mask"] _UpperCAmelCase : List[str] = RobertaTokenizer def __init__( self : List[str] , A : List[str]=None , A : List[Any]=None , A : Optional[int]=None , A : Tuple="replace" , A : int="<s>" , A : Any="</s>" , A : Optional[int]="</s>" , A : Tuple="<s>" , A : int="<unk>" , A : Optional[int]="<pad>" , A : Tuple="<mask>" , A : Optional[Any]=False , A : Optional[int]=True , **A : Optional[int] , ) ->Dict: super().__init__( A , A , tokenizer_file=A , errors=A , bos_token=A , eos_token=A , sep_token=A , cls_token=A , unk_token=A , pad_token=A , mask_token=A , add_prefix_space=A , trim_offsets=A , **A , ) lowerCamelCase__ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , A ) != add_prefix_space: lowerCamelCase__ : Union[str, Any] = getattr(A , pre_tok_state.pop('''type''' ) ) lowerCamelCase__ : Optional[int] = add_prefix_space lowerCamelCase__ : List[str] = pre_tok_class(**A ) lowerCamelCase__ : Any = add_prefix_space lowerCamelCase__ : Any = '''post_processor''' lowerCamelCase__ : str = getattr(self.backend_tokenizer , A , A ) if tokenizer_component_instance: lowerCamelCase__ : str = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: lowerCamelCase__ : Any = tuple(state['''sep'''] ) if "cls" in state: lowerCamelCase__ : Tuple = tuple(state['''cls'''] ) lowerCamelCase__ : Tuple = False if state.get('''add_prefix_space''' , A ) != add_prefix_space: lowerCamelCase__ : Optional[Any] = add_prefix_space lowerCamelCase__ : Optional[Any] = True if state.get('''trim_offsets''' , A ) != trim_offsets: lowerCamelCase__ : Tuple = trim_offsets lowerCamelCase__ : str = True if changes_to_apply: lowerCamelCase__ : Optional[int] = getattr(A , state.pop('''type''' ) ) lowerCamelCase__ : str = component_class(**A ) setattr(self.backend_tokenizer , A , A ) @property def __lowerCamelCase ( self : List[str] ) ->str: if self._mask_token is None: if self.verbose: logger.error('''Using mask_token, but it is not set yet.''' ) return None return str(self._mask_token ) @mask_token.setter def __lowerCamelCase ( self : int , A : List[Any] ) ->List[Any]: lowerCamelCase__ : Union[str, Any] = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else value lowerCamelCase__ : int = value def __lowerCamelCase ( self : Tuple , *A : List[Any] , **A : Optional[Any] ) ->BatchEncoding: lowerCamelCase__ : Dict = kwargs.get('''is_split_into_words''' , A ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*A , **A ) def __lowerCamelCase ( self : Tuple , *A : List[Any] , **A : Tuple ) ->BatchEncoding: lowerCamelCase__ : Optional[Any] = kwargs.get('''is_split_into_words''' , A ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*A , **A ) def __lowerCamelCase ( self : List[str] , A : str , A : Optional[str] = None ) ->Tuple[str]: lowerCamelCase__ : List[str] = self._tokenizer.model.save(A , name=A ) return tuple(A ) def __lowerCamelCase ( self : Dict , A : List[str] , A : List[Any]=None ) ->List[str]: lowerCamelCase__ : List[Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __lowerCamelCase ( self : Optional[int] , A : List[int] , A : Optional[List[int]] = None ) ->List[int]: lowerCamelCase__ : int = [self.sep_token_id] lowerCamelCase__ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
130
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() lowercase : str = logging.get_logger(__name__) def lowerCAmelCase__ ( _a : List[Any] , _a : List[Any]=False , _a : int=False , _a : Optional[Any]=False ): snake_case_ : Any = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''transformer.blocks.{i}.norm1.weight''', F'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''transformer.blocks.{i}.norm1.bias''', F'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (F'''transformer.blocks.{i}.attn.proj.weight''', F'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (F'''transformer.blocks.{i}.attn.proj.bias''', F'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((F'''transformer.blocks.{i}.norm2.weight''', F'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''transformer.blocks.{i}.norm2.bias''', F'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (F'''transformer.blocks.{i}.mlp.fc1.weight''', F'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((F'''transformer.blocks.{i}.mlp.fc1.bias''', F'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((F'''transformer.blocks.{i}.mlp.fc2.weight''', F'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''transformer.blocks.{i}.mlp.fc2.bias''', F'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ("text_embeddings.word_embeddings.weight", "vilt.embeddings.text_embeddings.word_embeddings.weight"), ( "text_embeddings.position_embeddings.weight", "vilt.embeddings.text_embeddings.position_embeddings.weight", ), ("text_embeddings.position_ids", "vilt.embeddings.text_embeddings.position_ids"), ( "text_embeddings.token_type_embeddings.weight", "vilt.embeddings.text_embeddings.token_type_embeddings.weight", ), ("text_embeddings.LayerNorm.weight", "vilt.embeddings.text_embeddings.LayerNorm.weight"), ("text_embeddings.LayerNorm.bias", "vilt.embeddings.text_embeddings.LayerNorm.bias"), # patch embeddings ("transformer.cls_token", "vilt.embeddings.cls_token"), ("transformer.patch_embed.proj.weight", "vilt.embeddings.patch_embeddings.projection.weight"), ("transformer.patch_embed.proj.bias", "vilt.embeddings.patch_embeddings.projection.bias"), ("transformer.pos_embed", "vilt.embeddings.position_embeddings"), # token type embeddings ("token_type_embeddings.weight", "vilt.embeddings.token_type_embeddings.weight"), ] ) # final layernorm + pooler rename_keys.extend( [ ("transformer.norm.weight", "vilt.layernorm.weight"), ("transformer.norm.bias", "vilt.layernorm.bias"), ("pooler.dense.weight", "vilt.pooler.dense.weight"), ("pooler.dense.bias", "vilt.pooler.dense.bias"), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ("vqa_classifier.0.weight", "classifier.0.weight"), ("vqa_classifier.0.bias", "classifier.0.bias"), ("vqa_classifier.1.weight", "classifier.1.weight"), ("vqa_classifier.1.bias", "classifier.1.bias"), ("vqa_classifier.3.weight", "classifier.3.weight"), ("vqa_classifier.3.bias", "classifier.3.bias"), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ("nlvr2_classifier.0.weight", "classifier.0.weight"), ("nlvr2_classifier.0.bias", "classifier.0.bias"), ("nlvr2_classifier.1.weight", "classifier.1.weight"), ("nlvr2_classifier.1.bias", "classifier.1.bias"), ("nlvr2_classifier.3.weight", "classifier.3.weight"), ("nlvr2_classifier.3.bias", "classifier.3.bias"), ] ) else: pass return rename_keys def lowerCAmelCase__ ( _a : Union[str, Any] , _a : List[str] ): for i in range(config.num_hidden_layers ): snake_case_ : List[Any] = "vilt." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case_ : int = state_dict.pop(F'''transformer.blocks.{i}.attn.qkv.weight''' ) snake_case_ : Optional[int] = state_dict.pop(F'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict snake_case_ : str = in_proj_weight[ : config.hidden_size, : ] snake_case_ : str = in_proj_bias[: config.hidden_size] snake_case_ : Optional[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case_ : int = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case_ : List[Any] = in_proj_weight[ -config.hidden_size :, : ] snake_case_ : str = in_proj_bias[-config.hidden_size :] def lowerCAmelCase__ ( _a : List[str] ): snake_case_ : Union[str, Any] = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(_a , _a ) def lowerCAmelCase__ ( _a : Optional[Any] , _a : Union[str, Any] , _a : Optional[Any] ): snake_case_ : str = dct.pop(_a ) snake_case_ : Tuple = val @torch.no_grad() def lowerCAmelCase__ ( _a : Tuple , _a : Dict ): snake_case_ : Union[str, Any] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=_a ) snake_case_ : Union[str, Any] = False snake_case_ : Union[str, Any] = False snake_case_ : Tuple = False snake_case_ : Optional[Any] = False if "vqa" in checkpoint_url: snake_case_ : int = True snake_case_ : Union[str, Any] = 31_29 snake_case_ : int = "huggingface/label-files" snake_case_ : List[str] = "vqa2-id2label.json" snake_case_ : List[Any] = json.load(open(hf_hub_download(_a , _a , repo_type="dataset" ) , "r" ) ) snake_case_ : int = {int(_a ): v for k, v in idalabel.items()} snake_case_ : Any = idalabel snake_case_ : Any = {v: k for k, v in idalabel.items()} snake_case_ : List[str] = ViltForQuestionAnswering(_a ) elif "nlvr" in checkpoint_url: snake_case_ : int = True snake_case_ : Optional[int] = 2 snake_case_ : Optional[int] = {0: "False", 1: "True"} snake_case_ : List[Any] = {v: k for k, v in config.idalabel.items()} snake_case_ : Any = 3 snake_case_ : Any = ViltForImagesAndTextClassification(_a ) elif "irtr" in checkpoint_url: snake_case_ : str = True snake_case_ : Union[str, Any] = ViltForImageAndTextRetrieval(_a ) elif "mlm_itm" in checkpoint_url: snake_case_ : str = True snake_case_ : Dict = ViltForMaskedLM(_a ) else: raise ValueError("Unknown model type" ) # load state_dict of original model, remove and rename some keys snake_case_ : List[str] = torch.hub.load_state_dict_from_url(_a , map_location="cpu" )["state_dict"] snake_case_ : Tuple = create_rename_keys(_a , _a , _a , _a ) for src, dest in rename_keys: rename_key(_a , _a , _a ) read_in_q_k_v(_a , _a ) if mlm_model or irtr_model: snake_case_ : str = ["itm_score.fc.weight", "itm_score.fc.bias"] for k in ignore_keys: state_dict.pop(_a , _a ) # load state dict into HuggingFace model model.eval() if mlm_model: snake_case_ , snake_case_ : Union[str, Any] = model.load_state_dict(_a , strict=_a ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(_a ) # Define processor snake_case_ : List[Any] = ViltImageProcessor(size=3_84 ) snake_case_ : str = BertTokenizer.from_pretrained("bert-base-uncased" ) snake_case_ : List[str] = ViltProcessor(_a , _a ) # Forward pass on example inputs (image + text) if nlvr_model: snake_case_ : List[str] = Image.open(requests.get("https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg" , stream=_a ).raw ) snake_case_ : Union[str, Any] = Image.open(requests.get("https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg" , stream=_a ).raw ) snake_case_ : Optional[Any] = ( "The left image contains twice the number of dogs as the right image, and at least two dogs in total are" " standing." ) snake_case_ : Union[str, Any] = processor(_a , _a , return_tensors="pt" ) snake_case_ : str = processor(_a , _a , return_tensors="pt" ) snake_case_ : Union[str, Any] = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: snake_case_ : Any = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg" , stream=_a ).raw ) if mlm_model: snake_case_ : Optional[int] = "a bunch of [MASK] laying on a [MASK]." else: snake_case_ : List[str] = "How many cats are there?" snake_case_ : int = processor(_a , _a , return_tensors="pt" ) snake_case_ : str = model(**_a ) # Verify outputs if mlm_model: snake_case_ : Tuple = torch.Size([1, 11, 3_05_22] ) snake_case_ : List[Any] = torch.tensor([-12.5_061, -12.5_123, -12.5_174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , _a , atol=1E-4 ) # verify masked token prediction equals "cats" snake_case_ : int = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: snake_case_ : Dict = torch.Size([1, 31_29] ) snake_case_ : Tuple = torch.tensor([-15.9_495, -18.1_472, -10.3_041] ) assert torch.allclose(outputs.logits[0, :3] , _a , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , _a , atol=1E-4 ) # verify vqa prediction equals "2" snake_case_ : str = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: snake_case_ : Optional[Any] = torch.Size([1, 2] ) snake_case_ : Any = torch.tensor([-2.8_721, 2.1_291] ) assert torch.allclose(outputs.logits[0, :3] , _a , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(_a ).mkdir(exist_ok=_a ) print(F'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(_a ) processor.save_pretrained(_a ) if __name__ == "__main__": lowercase : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt''', type=str, help='''URL of the checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) lowercase : int = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
568
import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser lowercase : List[Any] = re.compile(r'''\s+''') def lowerCAmelCase__ ( _a : int ): return {"hash": hashlib.mda(re.sub(_a , "" , example["content"] ).encode("utf-8" ) ).hexdigest()} def lowerCAmelCase__ ( _a : Optional[int] ): snake_case_ : Optional[int] = [len(_a ) for line in example["content"].splitlines()] return {"line_mean": np.mean(_a ), "line_max": max(_a )} def lowerCAmelCase__ ( _a : Optional[int] ): snake_case_ : str = np.mean([c.isalnum() for c in example["content"]] ) return {"alpha_frac": alpha_frac} def lowerCAmelCase__ ( _a : str , _a : Tuple ): if example["hash"] in uniques: uniques.remove(example["hash"] ) return True else: return False def lowerCAmelCase__ ( _a : Tuple , _a : Any=5 ): snake_case_ : Union[str, Any] = ["auto-generated", "autogenerated", "automatically generated"] snake_case_ : Union[str, Any] = example["content"].splitlines() for _, line in zip(range(_a ) , _a ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def lowerCAmelCase__ ( _a : List[str] , _a : Dict=5 , _a : Union[str, Any]=0.05 ): snake_case_ : Optional[Any] = ["unit tests", "test file", "configuration file"] snake_case_ : Optional[Any] = example["content"].splitlines() snake_case_ : List[str] = 0 snake_case_ : List[Any] = 0 # first test for _, line in zip(range(_a ) , _a ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test snake_case_ : List[str] = example["content"].count("\n" ) snake_case_ : Any = int(coeff * nlines ) for line in lines: count_config += line.lower().count("config" ) count_test += line.lower().count("test" ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def lowerCAmelCase__ ( _a : Optional[Any] ): snake_case_ : Optional[int] = ["def ", "class ", "for ", "while "] snake_case_ : Optional[Any] = example["content"].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def lowerCAmelCase__ ( _a : List[Any] , _a : Tuple=4 ): snake_case_ : List[Any] = example["content"].splitlines() snake_case_ : Tuple = 0 for line in lines: counter += line.lower().count("=" ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def lowerCAmelCase__ ( _a : Optional[Any] ): snake_case_ : Dict = tokenizer(example["content"] , truncation=_a )["input_ids"] snake_case_ : Dict = len(example["content"] ) / len(_a ) return {"ratio": ratio} def lowerCAmelCase__ ( _a : Dict ): snake_case_ : Any = {} results.update(get_hash(_a ) ) results.update(line_stats(_a ) ) results.update(alpha_stats(_a ) ) results.update(char_token_ratio(_a ) ) results.update(is_autogenerated(_a ) ) results.update(is_config_or_test(_a ) ) results.update(has_no_keywords(_a ) ) results.update(has_few_assignments(_a ) ) return results def lowerCAmelCase__ ( _a : Union[str, Any] , _a : Dict , _a : Any ): if not check_uniques(_a , _a ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def lowerCAmelCase__ ( _a : Optional[int] ): with open(_a , "rb" ) as f_in: with gzip.open(str(_a ) + ".gz" , "wb" , compresslevel=6 ) as f_out: shutil.copyfileobj(_a , _a ) os.unlink(_a ) # Settings lowercase : Union[str, Any] = HfArgumentParser(PreprocessingArguments) lowercase : List[Any] = parser.parse_args() if args.num_workers is None: lowercase : str = multiprocessing.cpu_count() lowercase : int = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset lowercase : Any = time.time() lowercase : Dict = load_dataset(args.dataset_name, split='''train''') print(F"""Time to load dataset: {time.time()-t_start:.2f}""") # Run preprocessing lowercase : str = time.time() lowercase : List[Any] = ds.map(preprocess, num_proc=args.num_workers) print(F"""Time to preprocess dataset: {time.time()-t_start:.2f}""") # Deduplicate hashes lowercase : Optional[int] = set(ds.unique('''hash''')) lowercase : List[str] = len(uniques) / len(ds) print(F"""Fraction of duplicates: {1-frac:.2%}""") # Deduplicate data and apply heuristics lowercase : str = time.time() lowercase : List[str] = ds.filter(filter, fn_kwargs={'''uniques''': uniques, '''args''': args}) print(F"""Time to filter dataset: {time.time()-t_start:.2f}""") print(F"""Size of filtered dataset: {len(ds_filter)}""") # Deduplicate with minhash and jaccard similarity if args.near_deduplication: lowercase : Dict = time.time() lowercase ,lowercase : Any = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F"""Time to deduplicate dataset: {time.time()-t_start:.2f}""") print(F"""Size of deduplicate dataset: {len(ds_filter)}""") # Save data in batches of samples_per_file lowercase : Dict = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / '''duplicate_clusters.json''', '''w''') as f: json.dump(duplicate_clusters, f) lowercase : str = output_dir / '''data''' data_dir.mkdir(exist_ok=True) lowercase : Optional[int] = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): lowercase : Optional[int] = str(data_dir / F"""file-{file_number+1:012}.json""") lowercase : int = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F"""Time to save dataset: {time.time()-t_start:.2f}""")
568
1
"""simple docstring""" from typing import Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING UpperCAmelCase: Optional[int] = logging.get_logger(__name__) @add_end_docstrings(__a ) class UpperCamelCase ( __a ): def __init__( self ,*UpperCAmelCase_ ,**UpperCAmelCase_ ): super().__init__(*lowerCAmelCase_ ,**lowerCAmelCase_ ) self.check_model_type(lowerCAmelCase_ ) def lowerCamelCase__ ( self ,UpperCAmelCase_=None ,UpperCAmelCase_=None ,UpperCAmelCase_=None ,**UpperCAmelCase_ ): _lowercase , _lowercase : Union[str, Any] = {}, {} if padding is not None: _lowercase : Dict = padding if truncation is not None: _lowercase : Union[str, Any] = truncation if top_k is not None: _lowercase : Union[str, Any] = top_k return preprocess_params, {}, postprocess_params def __call__( self ,UpperCAmelCase_ ,UpperCAmelCase_ = None ,**UpperCAmelCase_ ): if isinstance(lowerCAmelCase_ ,(Image.Image, str) ) and isinstance(lowerCAmelCase_ ,lowerCAmelCase_ ): _lowercase : int = {"""image""": image, """question""": question} else: _lowercase : Optional[Any] = image _lowercase : str = super().__call__(lowerCAmelCase_ ,**lowerCAmelCase_ ) return results def lowerCamelCase__ ( self ,UpperCAmelCase_ ,UpperCAmelCase_=False ,UpperCAmelCase_=False ): _lowercase : str = load_image(inputs["""image"""] ) _lowercase : List[Any] = self.tokenizer( inputs["""question"""] ,return_tensors=self.framework ,padding=lowerCAmelCase_ ,truncation=lowerCAmelCase_ ) _lowercase : str = self.image_processor(images=lowerCAmelCase_ ,return_tensors=self.framework ) model_inputs.update(lowerCAmelCase_ ) return model_inputs def lowerCamelCase__ ( self ,UpperCAmelCase_ ): _lowercase : Union[str, Any] = self.model(**lowerCAmelCase_ ) return model_outputs def lowerCamelCase__ ( self ,UpperCAmelCase_ ,UpperCAmelCase_=5 ): if top_k > self.model.config.num_labels: _lowercase : Dict = self.model.config.num_labels if self.framework == "pt": _lowercase : int = model_outputs.logits.sigmoid()[0] _lowercase , _lowercase : List[str] = probs.topk(lowerCAmelCase_ ) else: raise ValueError(f"""Unsupported framework: {self.framework}""" ) _lowercase : Optional[Any] = scores.tolist() _lowercase : str = ids.tolist() return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(lowerCAmelCase_ ,lowerCAmelCase_ )]
719
"""simple docstring""" import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class UpperCamelCase ( unittest.TestCase ): """simple docstring""" def lowerCamelCase__ ( self ): _lowercase : Dict = inspect.getfile(accelerate.test_utils ) _lowercase : List[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_script.py"""] ) _lowercase : List[Any] = os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] ) @require_tpu def lowerCamelCase__ ( self ): _lowercase : Union[str, Any] = f""" {self.test_dir}/xla_spawn.py --num_cores 8 {self.test_file_path} """.split() _lowercase : Any = [sys.executable] + distributed_args execute_subprocess_async(UpperCAmelCase_ ,env=os.environ.copy() )
600
0
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy UpperCAmelCase_ : Dict = logging.get_logger(__name__) class __A ( UpperCamelCase__ ): def __init__( self :List[str] , __snake_case :int , __snake_case :int , __snake_case :float , **__snake_case :Optional[Any] ): '''simple docstring''' __magic_name__ : List[Any] =feature_size __magic_name__ : Union[str, Any] =sampling_rate __magic_name__ : List[Any] =padding_value __magic_name__ : List[str] =kwargs.pop("""padding_side""" , """right""" ) __magic_name__ : Tuple =kwargs.pop("""return_attention_mask""" , __snake_case ) super().__init__(**__snake_case ) def A__ ( self :Any , __snake_case :Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , __snake_case :Union[bool, str, PaddingStrategy] = True , __snake_case :Optional[int] = None , __snake_case :bool = False , __snake_case :Optional[int] = None , __snake_case :Optional[bool] = None , __snake_case :Optional[Union[str, TensorType]] = None , ): '''simple docstring''' if isinstance(__snake_case , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): __magic_name__ : Union[str, Any] ={ key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( """You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`""" f" to this method that includes {self.model_input_names[0]}, but you provided" f" {list(processed_features.keys() )}" ) __magic_name__ : int =processed_features[self.model_input_names[0]] __magic_name__ : Union[str, Any] =( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(__snake_case ) == 0: if return_attention_mask: __magic_name__ : List[str] =[] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __magic_name__ : Optional[int] =required_input[0] if isinstance(__snake_case , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __magic_name__ : Optional[Any] =0 while len(required_input[index] ) == 0: index += 1 if index < len(__snake_case ): __magic_name__ : List[str] =required_input[index][0] if return_tensors is None: if is_tf_tensor(__snake_case ): __magic_name__ : int ="""tf""" elif is_torch_tensor(__snake_case ): __magic_name__ : str ="""pt""" elif isinstance(__snake_case , (int, float, list, tuple, np.ndarray) ): __magic_name__ : List[Any] ="""np""" else: raise ValueError( f"type of {first_element} unknown: {type(__snake_case )}. " """Should be one of a python, numpy, pytorch or tensorflow object.""" ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): __magic_name__ : List[str] =to_numpy(__snake_case ) else: __magic_name__ : str =[to_numpy(__snake_case ) for v in value] # Convert padding_strategy in PaddingStrategy __magic_name__ : Dict =self._get_padding_strategies(padding=__snake_case , max_length=__snake_case ) __magic_name__ : Optional[Any] =processed_features[self.model_input_names[0]] __magic_name__ : Dict =len(__snake_case ) if not all(len(__snake_case ) == batch_size for v in processed_features.values() ): raise ValueError("""Some items in the output dictionary have a different batch size than others.""" ) __magic_name__ : Optional[int] =[] for i in range(__snake_case ): __magic_name__ : Any ={k: v[i] for k, v in processed_features.items()} # truncation __magic_name__ : List[str] =self._truncate( __snake_case , max_length=__snake_case , pad_to_multiple_of=__snake_case , truncation=__snake_case , ) truncated_inputs.append(__snake_case ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __magic_name__ : Optional[int] =max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) __magic_name__ : Tuple =PaddingStrategy.MAX_LENGTH __magic_name__ : str ={} for i in range(__snake_case ): # padding __magic_name__ : List[str] =self._pad( truncated_inputs[i] , max_length=__snake_case , padding_strategy=__snake_case , pad_to_multiple_of=__snake_case , return_attention_mask=__snake_case , ) for key, value in outputs.items(): if key not in batch_outputs: __magic_name__ : Dict =[] if value.dtype is np.dtype(np.floataa ): __magic_name__ : Optional[int] =value.astype(np.floataa ) batch_outputs[key].append(__snake_case ) return BatchFeature(__snake_case , tensor_type=__snake_case ) def A__ ( self :Any , __snake_case :Union[Dict[str, np.ndarray], BatchFeature] , __snake_case :Optional[int] = None , __snake_case :PaddingStrategy = PaddingStrategy.DO_NOT_PAD , __snake_case :Optional[int] = None , __snake_case :Optional[bool] = None , ): '''simple docstring''' __magic_name__ : Dict =processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __magic_name__ : Any =len(__snake_case ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __magic_name__ : Dict =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __magic_name__ : List[Any] =padding_strategy != PaddingStrategy.DO_NOT_PAD and len(__snake_case ) < max_length if return_attention_mask and "attention_mask" not in processed_features: __magic_name__ : int =np.ones(len(__snake_case ) , dtype=np.intaa ) if needs_to_be_padded: __magic_name__ : List[Any] =max_length - len(__snake_case ) if self.padding_side == "right": if return_attention_mask: __magic_name__ : str =np.pad( processed_features["""attention_mask"""] , (0, difference) ) __magic_name__ : Tuple =((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __magic_name__ : str =np.pad( __snake_case , __snake_case , """constant""" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: __magic_name__ : str =np.pad( processed_features["""attention_mask"""] , (difference, 0) ) __magic_name__ : Optional[int] =((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __magic_name__ : List[Any] =np.pad( __snake_case , __snake_case , """constant""" , constant_values=self.padding_value ) else: raise ValueError("""Invalid padding strategy:""" + str(self.padding_side ) ) return processed_features def A__ ( self :Optional[Any] , __snake_case :Union[Dict[str, np.ndarray], BatchFeature] , __snake_case :Optional[int] = None , __snake_case :Optional[int] = None , __snake_case :Optional[bool] = None , ): '''simple docstring''' if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("""When setting ``truncation=True``, make sure that ``max_length`` is defined.""" ) __magic_name__ : Union[str, Any] =processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __magic_name__ : List[str] =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __magic_name__ : Any =len(__snake_case ) > max_length if needs_to_be_truncated: __magic_name__ : List[Any] =processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __magic_name__ : List[str] =processed_features["""attention_mask"""][:max_length] return processed_features def A__ ( self :List[Any] , __snake_case :str=False , __snake_case :Optional[int]=None ): '''simple docstring''' if padding is not False: if padding is True: __magic_name__ : Union[str, Any] =PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(__snake_case , __snake_case ): __magic_name__ : Optional[int] =PaddingStrategy(__snake_case ) elif isinstance(__snake_case , __snake_case ): __magic_name__ : Any =padding else: __magic_name__ : Any =PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f"When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( """Asking to pad but the feature_extractor does not have a padding value. Please select a value to use""" """ as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.""" ) return padding_strategy
21
import gc import unittest from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline from diffusers.utils import is_flax_available, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class lowercase_ ( unittest.TestCase ): def UpperCamelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def UpperCamelCase ( self ): _snake_case ,_snake_case : Union[str, Any] = FlaxStableDiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-2" , revision="bf16" , dtype=jnp.bfloataa , ) _snake_case : List[Any] = "A painting of a squirrel eating a burger" _snake_case : Union[str, Any] = jax.device_count() _snake_case : List[Any] = num_samples * [prompt] _snake_case : Tuple = sd_pipe.prepare_inputs(lowercase_ ) _snake_case : str = replicate(lowercase_ ) _snake_case : Dict = shard(lowercase_ ) _snake_case : List[Any] = jax.random.PRNGKey(0 ) _snake_case : List[Any] = jax.random.split(lowercase_ , jax.device_count() ) _snake_case : Tuple = sd_pipe(lowercase_ , lowercase_ , lowercase_ , num_inference_steps=25 , jit=lowercase_ )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) _snake_case : List[Any] = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) _snake_case : str = images[0, 253:256, 253:256, -1] _snake_case : Tuple = jnp.asarray(jax.device_get(image_slice.flatten() ) ) _snake_case : Optional[Any] = jnp.array([0.4_238, 0.4_414, 0.4_395, 0.4_453, 0.4_629, 0.4_590, 0.4_531, 0.45_508, 0.4_512] ) print(f"""output_slice: {output_slice}""" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2 def UpperCamelCase ( self ): _snake_case : Optional[Any] = "stabilityai/stable-diffusion-2" _snake_case ,_snake_case : List[Any] = FlaxDPMSolverMultistepScheduler.from_pretrained(lowercase_ , subfolder="scheduler" ) _snake_case ,_snake_case : int = FlaxStableDiffusionPipeline.from_pretrained( lowercase_ , scheduler=lowercase_ , revision="bf16" , dtype=jnp.bfloataa , ) _snake_case : str = scheduler_params _snake_case : Dict = "A painting of a squirrel eating a burger" _snake_case : Dict = jax.device_count() _snake_case : Optional[int] = num_samples * [prompt] _snake_case : List[str] = sd_pipe.prepare_inputs(lowercase_ ) _snake_case : Optional[int] = replicate(lowercase_ ) _snake_case : Union[str, Any] = shard(lowercase_ ) _snake_case : List[Any] = jax.random.PRNGKey(0 ) _snake_case : Union[str, Any] = jax.random.split(lowercase_ , jax.device_count() ) _snake_case : str = sd_pipe(lowercase_ , lowercase_ , lowercase_ , num_inference_steps=25 , jit=lowercase_ )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) _snake_case : List[str] = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) _snake_case : List[str] = images[0, 253:256, 253:256, -1] _snake_case : Union[str, Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) _snake_case : Dict = jnp.array([0.4_336, 0.42_969, 0.4_453, 0.4_199, 0.4_297, 0.4_531, 0.4_434, 0.4_434, 0.4_297] ) print(f"""output_slice: {output_slice}""" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
670
0
"""simple docstring""" import random def lowerCamelCase__ ( _lowerCamelCase : Dict , _lowerCamelCase : Tuple , _lowerCamelCase : Tuple ) -> Tuple: lowerCamelCase_ = a[left_index] lowerCamelCase_ = left_index + 1 for j in range(left_index + 1 , _lowerCamelCase ): if a[j] < pivot: lowerCamelCase_ , lowerCamelCase_ = a[i], a[j] i += 1 lowerCamelCase_ , lowerCamelCase_ = a[i - 1], a[left_index] return i - 1 def lowerCamelCase__ ( _lowerCamelCase : List[Any] , _lowerCamelCase : str , _lowerCamelCase : Tuple ) -> List[Any]: if left < right: lowerCamelCase_ = random.randint(_lowerCamelCase , right - 1 ) lowerCamelCase_ , lowerCamelCase_ = ( a[left], a[pivot], ) # switches the pivot with the left most bound lowerCamelCase_ = partition(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) quick_sort_random( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # recursive quicksort to the left of the pivot point quick_sort_random( _lowerCamelCase , pivot_index + 1 , _lowerCamelCase ) # recursive quicksort to the right of the pivot point def lowerCamelCase__ ( ) -> Dict: lowerCamelCase_ = input('Enter numbers separated by a comma:\n' ).strip() lowerCamelCase_ = [int(_lowerCamelCase ) for item in user_input.split(',' )] quick_sort_random(_lowerCamelCase , 0 , len(_lowerCamelCase ) ) print(_lowerCamelCase ) if __name__ == "__main__": main()
705
"""simple docstring""" def lowerCamelCase__ ( _lowerCamelCase : str ) -> bool: lowerCamelCase_ = 0 for ch in input_str: lowerCamelCase_ = ord(_lowerCamelCase ) lowerCamelCase_ = pow(2 , _lowerCamelCase ) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
137
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = {"""ctrl""": """https://huggingface.co/ctrl/resolve/main/config.json"""} class _UpperCAmelCase ( _lowerCamelCase ): a = '''ctrl''' a = ['''past_key_values'''] a = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a__=246534 , a__=256 , a__=1280 , a__=8192 , a__=48 , a__=16 , a__=0.1 , a__=0.1 , a__=1E-6 , a__=0.02 , a__=True , **a__ , ): A_ : List[Any] = vocab_size A_ : Tuple = n_positions A_ : int = n_embd A_ : Optional[int] = n_layer A_ : Any = n_head A_ : List[str] = dff A_ : Dict = resid_pdrop A_ : int = embd_pdrop A_ : Union[str, Any] = layer_norm_epsilon A_ : Optional[int] = initializer_range A_ : Tuple = use_cache super().__init__(**a__ )
569
def _lowerCAmelCase ( _lowerCAmelCase ): '''simple docstring''' if not nums: # Makes sure that the list is not empty raise ValueError("""List is empty""" ) A_ : List[Any] = sum(_lowerCAmelCase ) / len(_lowerCAmelCase ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(_lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
569
1
'''simple docstring''' import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def __UpperCamelCase ( a : Optional[Any] ) ->str: snake_case = torch.exp(a ) snake_case = torch.sum(a , dim=1 ) # sum of exp(x_i) snake_case = torch.sum(x * exp_x , dim=1 ) # sum of x_i * exp(x_i) return torch.log(a ) - B / A class _lowercase ( nn.Module ): def __init__( self , A__ ) -> Any: super().__init__() snake_case = config.output_attentions snake_case = config.output_hidden_states snake_case = nn.ModuleList([BertLayer(A__ ) for _ in range(config.num_hidden_layers )] ) snake_case = nn.ModuleList([BertHighway(A__ ) for _ in range(config.num_hidden_layers )] ) snake_case = [-1 for _ in range(config.num_hidden_layers )] def UpperCamelCase ( self , A__ ) -> Union[str, Any]: if (type(A__ ) is float) or (type(A__ ) is int): for i in range(len(self.early_exit_entropy ) ): snake_case = x else: snake_case = x def UpperCamelCase ( self , A__ ) -> Optional[Any]: snake_case = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name] ) def UpperCamelCase ( self , A__ , A__=None , A__=None , A__=None , A__=None , ) -> int: snake_case = () snake_case = () snake_case = () for i, layer_module in enumerate(self.layer ): if self.output_hidden_states: snake_case = all_hidden_states + (hidden_states,) snake_case = layer_module( A__ , A__ , head_mask[i] , A__ , A__ ) snake_case = layer_outputs[0] if self.output_attentions: snake_case = all_attentions + (layer_outputs[1],) snake_case = (hidden_states,) if self.output_hidden_states: snake_case = current_outputs + (all_hidden_states,) if self.output_attentions: snake_case = current_outputs + (all_attentions,) snake_case = self.highway[i](A__ ) # logits, pooled_output if not self.training: snake_case = highway_exit[0] snake_case = entropy(A__ ) snake_case = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy snake_case = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: snake_case = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(A__ , i + 1 ) else: snake_case = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: snake_case = all_hidden_states + (hidden_states,) snake_case = (hidden_states,) if self.output_hidden_states: snake_case = outputs + (all_hidden_states,) if self.output_attentions: snake_case = outputs + (all_attentions,) snake_case = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( '''The Bert Model transformer with early exiting (DeeBERT). ''' , __a , ) class _lowercase ( __a ): def __init__( self , A__ ) -> str: super().__init__(A__ ) snake_case = config snake_case = BertEmbeddings(A__ ) snake_case = DeeBertEncoder(A__ ) snake_case = BertPooler(A__ ) self.init_weights() def UpperCamelCase ( self ) -> Dict: self.encoder.init_highway_pooler(self.pooler ) def UpperCamelCase ( self ) -> str: return self.embeddings.word_embeddings def UpperCamelCase ( self , A__ ) -> Any: snake_case = value def UpperCamelCase ( self , A__ ) -> Union[str, Any]: for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(A__ ) @add_start_docstrings_to_model_forward(A__ ) def UpperCamelCase ( self , A__=None , A__=None , A__=None , A__=None , A__=None , A__=None , A__=None , A__=None , ) -> str: if input_ids is not None and inputs_embeds is not None: raise ValueError('''You cannot specify both input_ids and inputs_embeds at the same time''' ) elif input_ids is not None: snake_case = input_ids.size() elif inputs_embeds is not None: snake_case = inputs_embeds.size()[:-1] else: raise ValueError('''You have to specify either input_ids or inputs_embeds''' ) snake_case = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: snake_case = torch.ones(A__ , device=A__ ) if encoder_attention_mask is None: snake_case = torch.ones(A__ , device=A__ ) if token_type_ids is None: snake_case = torch.zeros(A__ , dtype=torch.long , device=A__ ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. snake_case = self.get_extended_attention_mask(A__ , A__ , A__ ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: snake_case = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: snake_case = encoder_attention_mask[:, None, None, :] snake_case = encoder_extended_attention_mask.to( dtype=next(self.parameters() ).dtype ) # fp16 compatibility snake_case = (1.0 - encoder_extended_attention_mask) * -1_0_0_0_0.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] snake_case = self.get_head_mask(A__ , self.config.num_hidden_layers ) snake_case = self.embeddings( input_ids=A__ , position_ids=A__ , token_type_ids=A__ , inputs_embeds=A__ ) snake_case = self.encoder( A__ , attention_mask=A__ , head_mask=A__ , encoder_hidden_states=A__ , encoder_attention_mask=A__ , ) snake_case = encoder_outputs[0] snake_case = self.pooler(A__ ) snake_case = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class _lowercase ( __a ): def __init__( self , A__ , A__ ) -> Any: snake_case = message snake_case = exit_layer # start from 1! class _lowercase ( nn.Module ): def __init__( self , A__ ) -> str: super().__init__() snake_case = BertPooler(A__ ) snake_case = nn.Dropout(config.hidden_dropout_prob ) snake_case = nn.Linear(config.hidden_size , config.num_labels ) def UpperCamelCase ( self , A__ ) -> Optional[Any]: # Pooler snake_case = encoder_outputs[0] snake_case = self.pooler(A__ ) # "return" pooler_output # BertModel snake_case = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification snake_case = bmodel_output[1] snake_case = self.dropout(A__ ) snake_case = self.classifier(A__ ) return logits, pooled_output @add_start_docstrings( '''Bert Model (with early exiting - DeeBERT) with a classifier on top, also takes care of multi-layer training. ''' , __a , ) class _lowercase ( __a ): def __init__( self , A__ ) -> Union[str, Any]: super().__init__(A__ ) snake_case = config.num_labels snake_case = config.num_hidden_layers snake_case = DeeBertModel(A__ ) snake_case = nn.Dropout(config.hidden_dropout_prob ) snake_case = nn.Linear(config.hidden_size , self.config.num_labels ) self.init_weights() @add_start_docstrings_to_model_forward(A__ ) def UpperCamelCase ( self , A__=None , A__=None , A__=None , A__=None , A__=None , A__=None , A__=None , A__=-1 , A__=False , ) -> Tuple: snake_case = self.num_layers try: snake_case = self.bert( A__ , attention_mask=A__ , token_type_ids=A__ , position_ids=A__ , head_mask=A__ , inputs_embeds=A__ , ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits snake_case = outputs[1] snake_case = self.dropout(A__ ) snake_case = self.classifier(A__ ) snake_case = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: snake_case = e.message snake_case = e.exit_layer snake_case = outputs[0] if not self.training: snake_case = entropy(A__ ) snake_case = [] snake_case = [] if labels is not None: if self.num_labels == 1: # We are doing regression snake_case = MSELoss() snake_case = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: snake_case = CrossEntropyLoss() snake_case = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits snake_case = [] for highway_exit in outputs[-1]: snake_case = highway_exit[0] if not self.training: highway_logits_all.append(A__ ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression snake_case = MSELoss() snake_case = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: snake_case = CrossEntropyLoss() snake_case = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(A__ ) if train_highway: snake_case = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: snake_case = (loss,) + outputs if not self.training: snake_case = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: snake_case = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
44
'''simple docstring''' from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class _lowercase ( yaml.SafeLoader ): def UpperCamelCase ( self , A__ ) -> List[str]: snake_case = [self.constructed_objects[key_node] for key_node, _ in node.value] snake_case = [tuple(A__ ) if isinstance(A__ , A__ ) else key for key in keys] snake_case = Counter(A__ ) snake_case = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F"""Got duplicate yaml keys: {duplicate_keys}""" ) def UpperCamelCase ( self , A__ , A__=False ) -> List[Any]: snake_case = super().construct_mapping(A__ , deep=A__ ) self._check_no_duplicates_on_constructed_node(A__ ) return mapping def __UpperCamelCase ( a : str ) ->Tuple[Optional[str], str]: snake_case = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: snake_case = full_content[1:].index('''---''' ) + 1 snake_case = '''\n'''.join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(a ) class _lowercase ( __a ): # class attributes _UpperCAmelCase = {'''train_eval_index'''} # train-eval-index in the YAML metadata @classmethod def UpperCamelCase ( cls , A__ ) -> "DatasetMetadata": with open(A__ , encoding='''utf-8''' ) as readme_file: snake_case , snake_case = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(A__ ) else: return cls() def UpperCamelCase ( self , A__ ) -> str: if path.exists(): with open(A__ , encoding='''utf-8''' ) as readme_file: snake_case = readme_file.read() else: snake_case = None snake_case = self._to_readme(A__ ) with open(A__ , '''w''' , encoding='''utf-8''' ) as readme_file: readme_file.write(A__ ) def UpperCamelCase ( self , A__ = None ) -> str: if readme_content is not None: snake_case , snake_case = _split_yaml_from_readme(A__ ) snake_case = '''---\n''' + self.to_yaml_string() + '''---\n''' + content else: snake_case = '''---\n''' + self.to_yaml_string() + '''---\n''' return full_content @classmethod def UpperCamelCase ( cls , A__ ) -> "DatasetMetadata": snake_case = yaml.load(A__ , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields snake_case = { (key.replace('''-''' , '''_''' ) if key.replace('''-''' , '''_''' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**A__ ) def UpperCamelCase ( self ) -> str: return yaml.safe_dump( { (key.replace('''_''' , '''-''' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=A__ , allow_unicode=A__ , encoding='''utf-8''' , ).decode('''utf-8''' ) _lowercase = { 'image-classification': [], 'translation': [], 'image-segmentation': [], 'fill-mask': [], 'automatic-speech-recognition': [], 'token-classification': [], 'sentence-similarity': [], 'audio-classification': [], 'question-answering': [], 'summarization': [], 'zero-shot-classification': [], 'table-to-text': [], 'feature-extraction': [], 'other': [], 'multiple-choice': [], 'text-classification': [], 'text-to-image': [], 'text2text-generation': [], 'zero-shot-image-classification': [], 'tabular-classification': [], 'tabular-regression': [], 'image-to-image': [], 'tabular-to-text': [], 'unconditional-image-generation': [], 'text-retrieval': [], 'text-to-speech': [], 'object-detection': [], 'audio-to-audio': [], 'text-generation': [], 'conversational': [], 'table-question-answering': [], 'visual-question-answering': [], 'image-to-text': [], 'reinforcement-learning': [], 'voice-activity-detection': [], 'time-series-forecasting': [], 'document-question-answering': [], } if __name__ == "__main__": from argparse import ArgumentParser _lowercase = ArgumentParser(usage='Validate the yaml metadata block of a README.md file.') ap.add_argument('readme_filepath') _lowercase = ap.parse_args() _lowercase = Path(args.readme_filepath) _lowercase = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
44
1
'''simple docstring''' def lowercase__( __UpperCamelCase: str ,__UpperCamelCase: str ): """simple docstring""" assert x is not None assert y is not None SCREAMING_SNAKE_CASE : Dict = len(__UpperCamelCase ) SCREAMING_SNAKE_CASE : Any = len(__UpperCamelCase ) # declaring the array for storing the dp values SCREAMING_SNAKE_CASE : Optional[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 ): SCREAMING_SNAKE_CASE : Dict = 1 if x[i - 1] == y[j - 1] else 0 SCREAMING_SNAKE_CASE : List[Any] = max(l[i - 1][j] ,l[i][j - 1] ,l[i - 1][j - 1] + match ) SCREAMING_SNAKE_CASE : Dict = '' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = m, n while i > 0 and j > 0: SCREAMING_SNAKE_CASE : Optional[Any] = 1 if x[i - 1] == y[j - 1] else 0 if l[i][j] == l[i - 1][j - 1] + match: if match == 1: SCREAMING_SNAKE_CASE : List[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__": UpperCamelCase_ = "AGGTAB" UpperCamelCase_ = "GXTXAYB" UpperCamelCase_ = 4 UpperCamelCase_ = "GTAB" UpperCamelCase_ , UpperCamelCase_ = longest_common_subsequence(a, b) print("len =", ln, ", sub-sequence =", subseq) import doctest doctest.testmod()
28
'''simple docstring''' from collections import defaultdict from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst def lowercase__( ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = 9, 14 # noqa: F841 SCREAMING_SNAKE_CASE : Optional[Any] = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] SCREAMING_SNAKE_CASE : Optional[int] = defaultdict(__UpperCamelCase ) for nodea, nodea, cost in edges: adjancency[nodea].append([nodea, cost] ) adjancency[nodea].append([nodea, cost] ) SCREAMING_SNAKE_CASE : Dict = mst(__UpperCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] for answer in expected: SCREAMING_SNAKE_CASE : Any = tuple(answer[:2] ) SCREAMING_SNAKE_CASE : List[Any] = tuple(edge[::-1] ) assert edge in result or reverse in result
28
1
"""simple docstring""" import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration a : Optional[int] = 5_0000 a : Optional[int] = 5000 a , a : Tuple = os.path.split(__file__) a : Tuple = os.path.join(RESULTS_BASEPATH, '''results''', RESULTS_FILENAME.replace('''.py''', '''.json''')) @get_duration def snake_case__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[Any]: for i in range(_SCREAMING_SNAKE_CASE ): UpperCAmelCase__ = dataset[i] @get_duration def snake_case__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->str: for i in range(0 , len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ): UpperCAmelCase__ = dataset[i : i + batch_size] @get_duration def snake_case__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]: with dataset.formatted_as(type=_SCREAMING_SNAKE_CASE ): for i in range(_SCREAMING_SNAKE_CASE ): UpperCAmelCase__ = dataset[i] @get_duration def snake_case__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->int: with dataset.formatted_as(type=_SCREAMING_SNAKE_CASE ): for i in range(0 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCAmelCase__ = dataset[i : i + batch_size] def snake_case__ ( ) ->str: UpperCAmelCase__ = {"""num examples""": SPEED_TEST_N_EXAMPLES} UpperCAmelCase__ = [ (read, {"""length""": SMALL_TEST}), (read, {"""length""": SPEED_TEST_N_EXAMPLES}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1_0}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1_0_0}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1_0_0_0}), (read_formatted, {"""type""": """numpy""", """length""": SMALL_TEST}), (read_formatted, {"""type""": """pandas""", """length""": SMALL_TEST}), (read_formatted, {"""type""": """torch""", """length""": SMALL_TEST}), (read_formatted, {"""type""": """tensorflow""", """length""": SMALL_TEST}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 1_0}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 1_0_0_0}), ] UpperCAmelCase__ = [ (read, {"""length""": SMALL_TEST}), (read, {"""length""": SPEED_TEST_N_EXAMPLES}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1_0}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1_0_0}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1_0_0_0}), (read_formatted, {"""type""": """numpy""", """length""": SMALL_TEST}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 1_0}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 1_0_0_0}), ] with tempfile.TemporaryDirectory() as tmp_dir: print("""generating dataset""" ) UpperCAmelCase__ = datasets.Features( {"""list""": datasets.Sequence(datasets.Value("""float32""" ) ), """numbers""": datasets.Value("""float32""" )} ) UpperCAmelCase__ = generate_example_dataset( os.path.join(_SCREAMING_SNAKE_CASE , """dataset.arrow""" ) , _SCREAMING_SNAKE_CASE , num_examples=_SCREAMING_SNAKE_CASE , seq_shapes={"""list""": (1_0_0,)} , ) print("""first set of iterations""" ) for func, kwargs in functions: print(func.__name__ , str(_SCREAMING_SNAKE_CASE ) ) UpperCAmelCase__ = func(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) print("""shuffling dataset""" ) UpperCAmelCase__ = dataset.shuffle() print("""Second set of iterations (after shuffling""" ) for func, kwargs in functions_shuffled: print("""shuffled """ , func.__name__ , str(_SCREAMING_SNAKE_CASE ) ) UpperCAmelCase__ = func( _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: f.write(json.dumps(_SCREAMING_SNAKE_CASE ).encode("""utf-8""" ) ) if __name__ == "__main__": # useful to run the profiler benchmark_iterating()
422
"""simple docstring""" import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class _UpperCamelCase ( __UpperCamelCase ): '''simple docstring''' def A__ ( self , __lowercase ): with open(__lowercase , encoding="""utf-8""" ) as input_file: UpperCAmelCase__ = re.compile(r"""(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)""" ) UpperCAmelCase__ = input_file.read() UpperCAmelCase__ = regexp.search(__lowercase ) return match def A__ ( self , __lowercase ): with open(__lowercase , encoding="""utf-8""" ) as input_file: UpperCAmelCase__ = re.compile(r"""#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()""" , re.DOTALL ) UpperCAmelCase__ = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` UpperCAmelCase__ = regexp.finditer(__lowercase ) UpperCAmelCase__ = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def A__ ( self ): UpperCAmelCase__ = Path("""./datasets""" ) UpperCAmelCase__ = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(__lowercase ) ): raise AssertionError(F'''open(...) must use utf-8 encoding in {dataset}''' ) def A__ ( self ): UpperCAmelCase__ = Path("""./datasets""" ) UpperCAmelCase__ = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_print_statements(str(__lowercase ) ): raise AssertionError(F'''print statement found in {dataset}. Use datasets.logger/logging instead.''' )
422
1
'''simple docstring''' import math def __UpperCAmelCase ( _UpperCAmelCase : int ) -> list: __snake_case = [True] * n __snake_case = False __snake_case = False __snake_case = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): __snake_case = i * 2 while index < n: __snake_case = False __snake_case = index + i __snake_case = [2] for i in range(3 , _UpperCAmelCase , 2 ): if is_prime[i]: primes.append(_UpperCAmelCase ) return primes def __UpperCAmelCase ( _UpperCAmelCase : int = 99_99_66_66_33_33 ) -> int: __snake_case = math.floor(math.sqrt(_UpperCAmelCase ) ) + 1_00 __snake_case = prime_sieve(_UpperCAmelCase ) __snake_case = 0 __snake_case = 0 __snake_case = primes[prime_index] while (last_prime**2) <= limit: __snake_case = primes[prime_index + 1] __snake_case = last_prime**2 __snake_case = next_prime**2 # Get numbers divisible by lps(current) __snake_case = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __snake_case = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __snake_case = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __snake_case = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
69
import json import os import sys import tempfile import unittest from pathlib import Path from shutil import copyfile from huggingface_hub import HfFolder, Repository, create_repo, delete_repo from requests.exceptions import HTTPError import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, PROCESSOR_MAPPING, TOKENIZER_MAPPING, AutoConfig, AutoFeatureExtractor, AutoProcessor, AutoTokenizer, BertTokenizer, ProcessorMixin, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaProcessor, ) from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 from test_module.custom_processing import CustomProcessor # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 lowerCamelCase = get_tests_dir('fixtures/dummy_feature_extractor_config.json') lowerCamelCase = get_tests_dir('fixtures/vocab.json') lowerCamelCase = get_tests_dir('fixtures') class A ( unittest.TestCase ): UpperCamelCase__ : Dict =['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] def lowerCamelCase ( self : str ) -> Optional[Any]: """simple docstring""" _lowerCamelCase : Dict =0 def lowerCamelCase ( self : str ) -> List[str]: """simple docstring""" _lowerCamelCase : List[Any] =AutoProcessor.from_pretrained('facebook/wav2vec2-base-960h' ) self.assertIsInstance(lowercase_ , lowercase_ ) def lowerCamelCase ( self : int ) -> Tuple: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _lowerCamelCase : int =WavaVecaConfig() _lowerCamelCase : Dict =AutoProcessor.from_pretrained('facebook/wav2vec2-base-960h' ) # save in new folder model_config.save_pretrained(lowercase_ ) processor.save_pretrained(lowercase_ ) _lowerCamelCase : Any =AutoProcessor.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) def lowerCamelCase ( self : str ) -> Union[str, Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: # copy relevant files copyfile(lowercase_ , os.path.join(lowercase_ , lowercase_ ) ) copyfile(lowercase_ , os.path.join(lowercase_ , 'vocab.json' ) ) _lowerCamelCase : Union[str, Any] =AutoProcessor.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) def lowerCamelCase ( self : Any ) -> Optional[Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _lowerCamelCase : List[Any] =WavaVecaFeatureExtractor() _lowerCamelCase : List[str] =AutoTokenizer.from_pretrained('facebook/wav2vec2-base-960h' ) _lowerCamelCase : str =WavaVecaProcessor(lowercase_ , lowercase_ ) # save in new folder processor.save_pretrained(lowercase_ ) # drop `processor_class` in tokenizer with open(os.path.join(lowercase_ , lowercase_ ) , 'r' ) as f: _lowerCamelCase : Optional[int] =json.load(lowercase_ ) config_dict.pop('processor_class' ) with open(os.path.join(lowercase_ , lowercase_ ) , 'w' ) as f: f.write(json.dumps(lowercase_ ) ) _lowerCamelCase : Optional[int] =AutoProcessor.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) def lowerCamelCase ( self : Dict ) -> Optional[int]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _lowerCamelCase : Optional[Any] =WavaVecaFeatureExtractor() _lowerCamelCase : Tuple =AutoTokenizer.from_pretrained('facebook/wav2vec2-base-960h' ) _lowerCamelCase : Dict =WavaVecaProcessor(lowercase_ , lowercase_ ) # save in new folder processor.save_pretrained(lowercase_ ) # drop `processor_class` in feature extractor with open(os.path.join(lowercase_ , lowercase_ ) , 'r' ) as f: _lowerCamelCase : Union[str, Any] =json.load(lowercase_ ) config_dict.pop('processor_class' ) with open(os.path.join(lowercase_ , lowercase_ ) , 'w' ) as f: f.write(json.dumps(lowercase_ ) ) _lowerCamelCase : Optional[int] =AutoProcessor.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) def lowerCamelCase ( self : List[str] ) -> List[str]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _lowerCamelCase : Optional[Any] =WavaVecaConfig(processor_class='Wav2Vec2Processor' ) model_config.save_pretrained(lowercase_ ) # copy relevant files copyfile(lowercase_ , os.path.join(lowercase_ , 'vocab.json' ) ) # create emtpy sample processor with open(os.path.join(lowercase_ , lowercase_ ) , 'w' ) as f: f.write('{}' ) _lowerCamelCase : int =AutoProcessor.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) def lowerCamelCase ( self : str ) -> Optional[int]: """simple docstring""" with self.assertRaises(lowercase_ ): _lowerCamelCase : int =AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor' ) # If remote code is disabled, we can't load this config. with self.assertRaises(lowercase_ ): _lowerCamelCase : Union[str, Any] =AutoProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_processor' , trust_remote_code=lowercase_ ) _lowerCamelCase : List[str] =AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor' , trust_remote_code=lowercase_ ) self.assertTrue(processor.special_attribute_present ) self.assertEqual(processor.__class__.__name__ , 'NewProcessor' ) _lowerCamelCase : int =processor.feature_extractor self.assertTrue(feature_extractor.special_attribute_present ) self.assertEqual(feature_extractor.__class__.__name__ , 'NewFeatureExtractor' ) _lowerCamelCase : Optional[int] =processor.tokenizer self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizerFast' ) # Test we can also load the slow version _lowerCamelCase : int =AutoProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_processor' , trust_remote_code=lowercase_ , use_fast=lowercase_ ) _lowerCamelCase : Optional[int] =new_processor.tokenizer self.assertTrue(new_tokenizer.special_attribute_present ) self.assertEqual(new_tokenizer.__class__.__name__ , 'NewTokenizer' ) else: self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizer' ) def lowerCamelCase ( self : Optional[int] ) -> Optional[int]: """simple docstring""" try: AutoConfig.register('custom' , lowercase_ ) AutoFeatureExtractor.register(lowercase_ , lowercase_ ) AutoTokenizer.register(lowercase_ , slow_tokenizer_class=lowercase_ ) AutoProcessor.register(lowercase_ , lowercase_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowercase_ ): AutoProcessor.register(lowercase_ , lowercase_ ) # Now that the config is registered, it can be used as any other config with the auto-API _lowerCamelCase : str =CustomFeatureExtractor.from_pretrained(lowercase_ ) with tempfile.TemporaryDirectory() as tmp_dir: _lowerCamelCase : str =os.path.join(lowercase_ , 'vocab.txt' ) with open(lowercase_ , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) _lowerCamelCase : List[Any] =CustomTokenizer(lowercase_ ) _lowerCamelCase : Optional[int] =CustomProcessor(lowercase_ , lowercase_ ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained(lowercase_ ) _lowerCamelCase : List[Any] =AutoProcessor.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def lowerCamelCase ( self : Union[str, Any] ) -> List[str]: """simple docstring""" class A ( UpperCamelCase_ ): UpperCamelCase__ : Optional[Any] =False class A ( UpperCamelCase_ ): UpperCamelCase__ : int =False class A ( UpperCamelCase_ ): UpperCamelCase__ : Union[str, Any] ='AutoFeatureExtractor' UpperCamelCase__ : str ='AutoTokenizer' UpperCamelCase__ : List[Any] =False try: AutoConfig.register('custom' , lowercase_ ) AutoFeatureExtractor.register(lowercase_ , lowercase_ ) AutoTokenizer.register(lowercase_ , slow_tokenizer_class=lowercase_ ) AutoProcessor.register(lowercase_ , lowercase_ ) # If remote code is not set, the default is to use local classes. _lowerCamelCase : int =AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor' ) self.assertEqual(processor.__class__.__name__ , 'NewProcessor' ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote code is disabled, we load the local ones. _lowerCamelCase : int =AutoProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_processor' , trust_remote_code=lowercase_ ) self.assertEqual(processor.__class__.__name__ , 'NewProcessor' ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub. _lowerCamelCase : str =AutoProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_processor' , trust_remote_code=lowercase_ ) self.assertEqual(processor.__class__.__name__ , 'NewProcessor' ) self.assertTrue(processor.special_attribute_present ) self.assertTrue(processor.feature_extractor.special_attribute_present ) self.assertTrue(processor.tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def lowerCamelCase ( self : Optional[int] ) -> str: """simple docstring""" _lowerCamelCase : List[Any] =AutoProcessor.from_pretrained('hf-internal-testing/tiny-random-bert' ) self.assertEqual(processor.__class__.__name__ , 'BertTokenizerFast' ) def lowerCamelCase ( self : Any ) -> Dict: """simple docstring""" _lowerCamelCase : Any =AutoProcessor.from_pretrained('hf-internal-testing/tiny-random-convnext' ) self.assertEqual(processor.__class__.__name__ , 'ConvNextImageProcessor' ) @is_staging_test class A ( unittest.TestCase ): UpperCamelCase__ : List[Any] =['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def lowerCamelCase ( cls : int ) -> Optional[Any]: """simple docstring""" _lowerCamelCase : Union[str, Any] =TOKEN HfFolder.save_token(lowercase_ ) @classmethod def lowerCamelCase ( cls : Optional[int] ) -> Union[str, Any]: """simple docstring""" try: delete_repo(token=cls._token , repo_id='test-processor' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-processor-org' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-processor' ) except HTTPError: pass def lowerCamelCase ( self : str ) -> int: """simple docstring""" _lowerCamelCase : Tuple =WavaVecaProcessor.from_pretrained(lowercase_ ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(lowercase_ , 'test-processor' ) , push_to_hub=lowercase_ , use_auth_token=self._token ) _lowerCamelCase : Union[str, Any] =WavaVecaProcessor.from_pretrained(F'''{USER}/test-processor''' ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(lowercase_ , getattr(new_processor.feature_extractor , lowercase_ ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def lowerCamelCase ( self : str ) -> Tuple: """simple docstring""" _lowerCamelCase : int =WavaVecaProcessor.from_pretrained(lowercase_ ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(lowercase_ , 'test-processor-org' ) , push_to_hub=lowercase_ , use_auth_token=self._token , organization='valid_org' , ) _lowerCamelCase : str =WavaVecaProcessor.from_pretrained('valid_org/test-processor-org' ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(lowercase_ , getattr(new_processor.feature_extractor , lowercase_ ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def lowerCamelCase ( self : List[Any] ) -> str: """simple docstring""" CustomFeatureExtractor.register_for_auto_class() CustomTokenizer.register_for_auto_class() CustomProcessor.register_for_auto_class() _lowerCamelCase : Optional[Any] =CustomFeatureExtractor.from_pretrained(lowercase_ ) with tempfile.TemporaryDirectory() as tmp_dir: _lowerCamelCase : Dict =os.path.join(lowercase_ , 'vocab.txt' ) with open(lowercase_ , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) _lowerCamelCase : Any =CustomTokenizer(lowercase_ ) _lowerCamelCase : List[Any] =CustomProcessor(lowercase_ , lowercase_ ) with tempfile.TemporaryDirectory() as tmp_dir: create_repo(F'''{USER}/test-dynamic-processor''' , token=self._token ) _lowerCamelCase : List[str] =Repository(lowercase_ , clone_from=F'''{USER}/test-dynamic-processor''' , token=self._token ) processor.save_pretrained(lowercase_ ) # This has added the proper auto_map field to the feature extractor config self.assertDictEqual( processor.feature_extractor.auto_map , { 'AutoFeatureExtractor': 'custom_feature_extraction.CustomFeatureExtractor', 'AutoProcessor': 'custom_processing.CustomProcessor', } , ) # This has added the proper auto_map field to the tokenizer config with open(os.path.join(lowercase_ , 'tokenizer_config.json' ) ) as f: _lowerCamelCase : Union[str, Any] =json.load(lowercase_ ) self.assertDictEqual( tokenizer_config['auto_map'] , { 'AutoTokenizer': ['custom_tokenization.CustomTokenizer', None], 'AutoProcessor': 'custom_processing.CustomProcessor', } , ) # The code has been copied from fixtures self.assertTrue(os.path.isfile(os.path.join(lowercase_ , 'custom_feature_extraction.py' ) ) ) self.assertTrue(os.path.isfile(os.path.join(lowercase_ , 'custom_tokenization.py' ) ) ) self.assertTrue(os.path.isfile(os.path.join(lowercase_ , 'custom_processing.py' ) ) ) repo.push_to_hub() _lowerCamelCase : Tuple =AutoProcessor.from_pretrained(F'''{USER}/test-dynamic-processor''' , trust_remote_code=lowercase_ ) # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module self.assertEqual(new_processor.__class__.__name__ , 'CustomProcessor' )
464
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A : Any = logging.get_logger(__name__) class _lowercase ( lowercase__ , lowercase__): """simple docstring""" A__ = "maskformer-swin" A__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Any , __lowerCamelCase : Dict=224 , __lowerCamelCase : List[str]=4 , __lowerCamelCase : int=3 , __lowerCamelCase : int=96 , __lowerCamelCase : Tuple=[2, 2, 6, 2] , __lowerCamelCase : Tuple=[3, 6, 12, 24] , __lowerCamelCase : Union[str, Any]=7 , __lowerCamelCase : Union[str, Any]=4.0 , __lowerCamelCase : Any=True , __lowerCamelCase : Tuple=0.0 , __lowerCamelCase : List[str]=0.0 , __lowerCamelCase : List[str]=0.1 , __lowerCamelCase : List[Any]="gelu" , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : Tuple=0.0_2 , __lowerCamelCase : List[Any]=1E-5 , __lowerCamelCase : Dict=None , __lowerCamelCase : Dict=None , **__lowerCamelCase : Tuple , ): '''simple docstring''' super().__init__(**__lowerCamelCase ) lowerCamelCase__ : int = image_size lowerCamelCase__ : Dict = patch_size lowerCamelCase__ : Optional[int] = num_channels lowerCamelCase__ : Optional[Any] = embed_dim lowerCamelCase__ : str = depths lowerCamelCase__ : str = len(__lowerCamelCase ) lowerCamelCase__ : Dict = num_heads lowerCamelCase__ : Optional[Any] = window_size lowerCamelCase__ : str = mlp_ratio lowerCamelCase__ : Tuple = qkv_bias lowerCamelCase__ : Optional[Any] = hidden_dropout_prob lowerCamelCase__ : List[str] = attention_probs_dropout_prob lowerCamelCase__ : Union[str, Any] = drop_path_rate lowerCamelCase__ : int = hidden_act lowerCamelCase__ : Optional[Any] = use_absolute_embeddings lowerCamelCase__ : Dict = layer_norm_eps lowerCamelCase__ : int = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowerCamelCase__ : List[str] = int(embed_dim * 2 ** (len(__lowerCamelCase ) - 1) ) lowerCamelCase__ : Optional[Any] = ["stem"] + [f"stage{idx}" for idx in range(1 , len(__lowerCamelCase ) + 1 )] lowerCamelCase__ : int = get_aligned_output_features_output_indices( out_features=__lowerCamelCase , out_indices=__lowerCamelCase , stage_names=self.stage_names )
717
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class _lowercase : """simple docstring""" def __init__( self : Dict , __lowerCamelCase : str , __lowerCamelCase : Optional[int]=13 , __lowerCamelCase : List[str]=7 , __lowerCamelCase : Tuple=True , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : List[str]=True , __lowerCamelCase : Union[str, Any]=99 , __lowerCamelCase : List[Any]=32 , __lowerCamelCase : List[Any]=5 , __lowerCamelCase : Optional[Any]=4 , __lowerCamelCase : Optional[int]=37 , __lowerCamelCase : List[str]="gelu" , __lowerCamelCase : List[str]=0.1 , __lowerCamelCase : int=0.1 , __lowerCamelCase : List[str]=512 , __lowerCamelCase : Optional[Any]=16 , __lowerCamelCase : Optional[Any]=2 , __lowerCamelCase : str=0.0_2 , __lowerCamelCase : List[str]=3 , __lowerCamelCase : Tuple=4 , __lowerCamelCase : Optional[int]=None , ): '''simple docstring''' lowerCamelCase__ : Tuple = parent lowerCamelCase__ : int = batch_size lowerCamelCase__ : List[Any] = seq_length lowerCamelCase__ : Union[str, Any] = is_training lowerCamelCase__ : Any = use_token_type_ids lowerCamelCase__ : Union[str, Any] = use_labels lowerCamelCase__ : List[str] = vocab_size lowerCamelCase__ : Union[str, Any] = hidden_size lowerCamelCase__ : List[Any] = num_hidden_layers lowerCamelCase__ : Optional[Any] = num_attention_heads lowerCamelCase__ : Any = intermediate_size lowerCamelCase__ : str = hidden_act lowerCamelCase__ : str = hidden_dropout_prob lowerCamelCase__ : Any = attention_probs_dropout_prob lowerCamelCase__ : List[str] = max_position_embeddings lowerCamelCase__ : Optional[int] = type_vocab_size lowerCamelCase__ : List[Any] = type_sequence_label_size lowerCamelCase__ : List[str] = initializer_range lowerCamelCase__ : List[str] = num_labels lowerCamelCase__ : List[Any] = num_choices lowerCamelCase__ : Optional[Any] = scope lowerCamelCase__ : List[Any] = self.vocab_size - 1 def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' lowerCamelCase__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase__ : Optional[Any] = None if self.use_token_type_ids: lowerCamelCase__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase__ : Any = None lowerCamelCase__ : str = None lowerCamelCase__ : str = None if self.use_labels: lowerCamelCase__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase__ : Dict = ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase__ : Union[str, Any] = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) lowerCamelCase__ : Optional[int] = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def lowerCAmelCase ( self : str , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : int , *__lowerCamelCase : List[Any] ): '''simple docstring''' lowerCamelCase__ : Optional[int] = OpenAIGPTModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() lowerCamelCase__ : Tuple = model(__lowerCamelCase , token_type_ids=__lowerCamelCase , head_mask=__lowerCamelCase ) lowerCamelCase__ : str = model(__lowerCamelCase , token_type_ids=__lowerCamelCase ) lowerCamelCase__ : Optional[int] = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase ( self : str , __lowerCamelCase : List[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Any , *__lowerCamelCase : Optional[int] ): '''simple docstring''' lowerCamelCase__ : Tuple = OpenAIGPTLMHeadModel(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() lowerCamelCase__ : List[str] = model(__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase ( self : Dict , __lowerCamelCase : Any , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] , *__lowerCamelCase : Tuple ): '''simple docstring''' lowerCamelCase__ : List[Any] = OpenAIGPTDoubleHeadsModel(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() lowerCamelCase__ : Optional[Any] = model(__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase ( self : Tuple , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any] , *__lowerCamelCase : Optional[int] ): '''simple docstring''' lowerCamelCase__ : Dict = self.num_labels lowerCamelCase__ : Tuple = OpenAIGPTForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() lowerCamelCase__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : List[str] = model(__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : List[str] ): '''simple docstring''' lowerCamelCase__ : str = self.prepare_config_and_inputs() ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) : Any = config_and_inputs lowerCamelCase__ : Union[str, Any] = { "input_ids": input_ids, "token_type_ids": token_type_ids, "head_mask": head_mask, } return config, inputs_dict @require_torch class _lowercase ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase): """simple docstring""" A__ = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) A__ = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly A__ = ( { "feature-extraction": OpenAIGPTModel, "text-classification": OpenAIGPTForSequenceClassification, "text-generation": OpenAIGPTLMHeadModel, "zero-shot": OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def lowerCAmelCase ( self : List[str] , __lowerCamelCase : str , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Union[str, Any] ): '''simple docstring''' if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def lowerCAmelCase ( self : Union[str, Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple=False ): '''simple docstring''' lowerCamelCase__ : Tuple = super()._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": lowerCamelCase__ : Optional[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=__lowerCamelCase , ) lowerCamelCase__ : Tuple = inputs_dict["labels"] lowerCamelCase__ : Any = inputs_dict["labels"] lowerCamelCase__ : Any = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=__lowerCamelCase , ) lowerCamelCase__ : Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCamelCase ) return inputs_dict def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' lowerCamelCase__ : Tuple = OpenAIGPTModelTester(self ) lowerCamelCase__ : Union[str, Any] = ConfigTester(self , config_class=__lowerCamelCase , n_embd=37 ) def lowerCAmelCase ( self : int ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCAmelCase ( self : Dict ): '''simple docstring''' lowerCamelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*__lowerCamelCase ) def lowerCAmelCase ( self : str ): '''simple docstring''' lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*__lowerCamelCase ) def lowerCAmelCase ( self : Dict ): '''simple docstring''' lowerCamelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*__lowerCamelCase ) def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' lowerCamelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*__lowerCamelCase ) @slow def lowerCAmelCase ( self : List[str] ): '''simple docstring''' for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ : Any = OpenAIGPTModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) @require_torch class _lowercase ( unittest.TestCase): """simple docstring""" @slow def lowerCAmelCase ( self : Any ): '''simple docstring''' lowerCamelCase__ : List[Any] = OpenAIGPTLMHeadModel.from_pretrained("openai-gpt" ) model.to(__lowerCamelCase ) lowerCamelCase__ : int = torch.tensor([[481, 4735, 544]] , dtype=torch.long , device=__lowerCamelCase ) # the president is lowerCamelCase__ : Union[str, Any] = [ 481, 4735, 544, 246, 963, 870, 762, 239, 244, 40477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the lowerCamelCase__ : int = model.generate(__lowerCamelCase , do_sample=__lowerCamelCase ) self.assertListEqual(output_ids[0].tolist() , __lowerCamelCase )
5
0
import argparse import json from tqdm import tqdm def SCREAMING_SNAKE_CASE ( ) -> Optional[int]: __UpperCAmelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--src_path''' , type=__lowerCAmelCase , default='''biencoder-nq-dev.json''' , help='''Path to raw DPR training data''' , ) parser.add_argument( '''--evaluation_set''' , type=__lowerCAmelCase , help='''where to store parsed evaluation_set file''' , ) parser.add_argument( '''--gold_data_path''' , type=__lowerCAmelCase , help='''where to store parsed gold_data_path file''' , ) __UpperCAmelCase =parser.parse_args() with open(args.src_path , '''r''' ) as src_file, open(args.evaluation_set , '''w''' ) as eval_file, open( args.gold_data_path , '''w''' ) as gold_file: __UpperCAmelCase =json.load(__lowerCAmelCase ) for dpr_record in tqdm(__lowerCAmelCase ): __UpperCAmelCase =dpr_record["""question"""] __UpperCAmelCase =[context["""title"""] for context in dpr_record["""positive_ctxs"""]] eval_file.write(question + '''\n''' ) gold_file.write('''\t'''.join(__lowerCAmelCase ) + '''\n''' ) if __name__ == "__main__": main()
132
import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging UpperCamelCase = logging.get_logger(__name__) def __lowerCamelCase ( __lowerCAmelCase : Tuple ) -> List[str]: __UpperCamelCase : List[str] = R"""\w+[.]\d+""" __UpperCamelCase : Optional[int] = re.findall(__lowerCAmelCase , __lowerCAmelCase ) for pat in pats: __UpperCamelCase : str = key.replace(__lowerCAmelCase , """_""".join(pat.split(""".""" ) ) ) return key def __lowerCamelCase ( __lowerCAmelCase : int , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] ) -> str: __UpperCamelCase : Dict = pt_tuple_key[:-1] + ("""scale""",) if ( any("""norm""" in str_ for str_ in pt_tuple_key ) and (pt_tuple_key[-1] == "bias") and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict) and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict) ): __UpperCamelCase : List[Any] = pt_tuple_key[:-1] + ("""scale""",) return renamed_pt_tuple_key, pt_tensor elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict: __UpperCamelCase : Dict = pt_tuple_key[:-1] + ("""scale""",) return renamed_pt_tuple_key, pt_tensor # embedding if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict: __UpperCamelCase : Any = pt_tuple_key[:-1] + ("""embedding""",) return renamed_pt_tuple_key, pt_tensor # conv layer __UpperCamelCase : List[Any] = pt_tuple_key[:-1] + ("""kernel""",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4: __UpperCamelCase : Dict = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer __UpperCamelCase : Union[str, Any] = pt_tuple_key[:-1] + ("""kernel""",) if pt_tuple_key[-1] == "weight": __UpperCamelCase : int = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight __UpperCamelCase : List[Any] = pt_tuple_key[:-1] + ("""weight""",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias __UpperCamelCase : Tuple = pt_tuple_key[:-1] + ("""bias""",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def __lowerCamelCase ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int]=42 ) -> int: # Step 1: Convert pytorch tensor to numpy __UpperCamelCase : Dict = {k: v.numpy() for k, v in pt_state_dict.items()} # Step 2: Since the model is stateless, get random Flax params __UpperCamelCase : str = flax_model.init_weights(PRNGKey(__lowerCAmelCase ) ) __UpperCamelCase : Union[str, Any] = flatten_dict(__lowerCAmelCase ) __UpperCamelCase : List[str] = {} # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): __UpperCamelCase : str = rename_key(__lowerCAmelCase ) __UpperCamelCase : Any = tuple(renamed_pt_key.split(""".""" ) ) # Correctly rename weight parameters __UpperCamelCase , __UpperCamelCase : Tuple = rename_key_and_reshape_tensor(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f'PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape ' f'{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) # also add unexpected weight so that warning is thrown __UpperCamelCase : Any = jnp.asarray(__lowerCAmelCase ) return unflatten_dict(__lowerCAmelCase )
269
0
'''simple docstring''' import argparse import hashlib # hashlib is only used inside the Test class import struct class __lowerCAmelCase: def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE : str ): """simple docstring""" SCREAMING_SNAKE_CASE_ :int = data SCREAMING_SNAKE_CASE_ :Union[str, Any] = [0x67_45_23_01, 0xEF_CD_AB_89, 0x98_BA_DC_FE, 0x10_32_54_76, 0xC3_D2_E1_F0] @staticmethod def _lowercase ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" return ((n << b) | (n >> (32 - b))) & 0xFF_FF_FF_FF def _lowercase ( self : Optional[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ :Optional[int] = b'\x80' + b'\x00' * (63 - (len(self.data ) + 8) % 64) SCREAMING_SNAKE_CASE_ :List[str] = self.data + padding + struct.pack('>Q' , 8 * len(self.data ) ) return padded_data def _lowercase ( self : Optional[int] ): """simple docstring""" return [ self.padded_data[i : i + 64] for i in range(0 , len(self.padded_data ) , 64 ) ] def _lowercase ( self : Any , SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ :List[str] = list(struct.unpack('>16L' , SCREAMING_SNAKE_CASE ) ) + [0] * 64 for i in range(16 , 80 ): SCREAMING_SNAKE_CASE_ :Union[str, Any] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]) , 1 ) return w def _lowercase ( self : Tuple ): """simple docstring""" SCREAMING_SNAKE_CASE_ :str = self.padding() SCREAMING_SNAKE_CASE_ :Optional[int] = self.split_blocks() for block in self.blocks: SCREAMING_SNAKE_CASE_ :Dict = self.expand_block(SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :str = self.h for i in range(0 , 80 ): if 0 <= i < 20: SCREAMING_SNAKE_CASE_ :Optional[int] = (b & c) | ((~b) & d) SCREAMING_SNAKE_CASE_ :str = 0x5A_82_79_99 elif 20 <= i < 40: SCREAMING_SNAKE_CASE_ :Optional[Any] = b ^ c ^ d SCREAMING_SNAKE_CASE_ :Dict = 0x6E_D9_EB_A1 elif 40 <= i < 60: SCREAMING_SNAKE_CASE_ :int = (b & c) | (b & d) | (c & d) SCREAMING_SNAKE_CASE_ :Optional[int] = 0x8F_1B_BC_DC elif 60 <= i < 80: SCREAMING_SNAKE_CASE_ :Any = b ^ c ^ d SCREAMING_SNAKE_CASE_ :Tuple = 0xCA_62_C1_D6 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :List[str] = ( self.rotate(SCREAMING_SNAKE_CASE , 5 ) + f + e + k + expanded_block[i] & 0xFF_FF_FF_FF, a, self.rotate(SCREAMING_SNAKE_CASE , 30 ), c, d, ) SCREAMING_SNAKE_CASE_ :Any = ( self.h[0] + a & 0xFF_FF_FF_FF, self.h[1] + b & 0xFF_FF_FF_FF, self.h[2] + c & 0xFF_FF_FF_FF, self.h[3] + d & 0xFF_FF_FF_FF, self.h[4] + e & 0xFF_FF_FF_FF, ) return ("{:08x}" * 5).format(*self.h ) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE_ :Optional[Any] = B'Test String' assert SHAaHash(SCREAMING_SNAKE_CASE ).final_hash() == hashlib.shaa(SCREAMING_SNAKE_CASE ).hexdigest() # noqa: S324 def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE_ :List[str] = argparse.ArgumentParser(description='Process some strings or files' ) parser.add_argument( '--string' , dest='input_string' , default='Hello World!! Welcome to Cryptography' , help='Hash the string' , ) parser.add_argument('--file' , dest='input_file' , help='Hash contents of a file' ) SCREAMING_SNAKE_CASE_ :List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE_ :List[Any] = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , 'rb' ) as f: SCREAMING_SNAKE_CASE_ :Union[str, Any] = f.read() else: SCREAMING_SNAKE_CASE_ :Dict = bytes(SCREAMING_SNAKE_CASE , 'utf-8' ) print(SHAaHash(SCREAMING_SNAKE_CASE ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
233
'''simple docstring''' from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __lowerCAmelCase( lowerCAmelCase__ ): __snake_case : List[str] = ['image_processor', 'tokenizer'] __snake_case : Optional[int] = 'Pix2StructImageProcessor' __snake_case : Optional[int] = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ :Optional[Any] = False super().__init__(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __call__( self : Tuple , SCREAMING_SNAKE_CASE : Any=None , SCREAMING_SNAKE_CASE : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , SCREAMING_SNAKE_CASE : bool = True , SCREAMING_SNAKE_CASE : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE : Union[bool, str, TruncationStrategy] = None , SCREAMING_SNAKE_CASE : Optional[int] = None , SCREAMING_SNAKE_CASE : Optional[int] = 2_048 , SCREAMING_SNAKE_CASE : int = 0 , SCREAMING_SNAKE_CASE : Optional[int] = None , SCREAMING_SNAKE_CASE : Optional[bool] = None , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = True , SCREAMING_SNAKE_CASE : Optional[Union[str, TensorType]] = None , **SCREAMING_SNAKE_CASE : str , ): """simple docstring""" 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 and not self.image_processor.is_vqa: SCREAMING_SNAKE_CASE_ :Union[str, Any] = self.tokenizer SCREAMING_SNAKE_CASE_ :Tuple = self.tokenizer( text=SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , stride=SCREAMING_SNAKE_CASE , pad_to_multiple_of=SCREAMING_SNAKE_CASE , return_attention_mask=SCREAMING_SNAKE_CASE , return_overflowing_tokens=SCREAMING_SNAKE_CASE , return_special_tokens_mask=SCREAMING_SNAKE_CASE , return_offsets_mapping=SCREAMING_SNAKE_CASE , return_token_type_ids=SCREAMING_SNAKE_CASE , return_length=SCREAMING_SNAKE_CASE , verbose=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) return text_encoding if not self.image_processor.is_vqa: # add pixel_values SCREAMING_SNAKE_CASE_ :Any = self.image_processor( SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , max_patches=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) else: # add pixel_values and bbox SCREAMING_SNAKE_CASE_ :Union[str, Any] = self.image_processor( SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , max_patches=SCREAMING_SNAKE_CASE , header_text=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) if text is not None and not self.image_processor.is_vqa: SCREAMING_SNAKE_CASE_ :Any = self.tokenizer( text=SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , stride=SCREAMING_SNAKE_CASE , pad_to_multiple_of=SCREAMING_SNAKE_CASE , return_attention_mask=SCREAMING_SNAKE_CASE , return_overflowing_tokens=SCREAMING_SNAKE_CASE , return_special_tokens_mask=SCREAMING_SNAKE_CASE , return_offsets_mapping=SCREAMING_SNAKE_CASE , return_token_type_ids=SCREAMING_SNAKE_CASE , return_length=SCREAMING_SNAKE_CASE , verbose=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) if "attention_mask" in text_encoding: SCREAMING_SNAKE_CASE_ :List[Any] = text_encoding.pop('attention_mask' ) if "input_ids" in text_encoding: SCREAMING_SNAKE_CASE_ :Any = text_encoding.pop('input_ids' ) else: SCREAMING_SNAKE_CASE_ :Any = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE ) return encoding_image_processor def _lowercase ( self : Tuple , *SCREAMING_SNAKE_CASE : Optional[int] , **SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def _lowercase ( self : Tuple , *SCREAMING_SNAKE_CASE : List[str] , **SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" return self.tokenizer.decode(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) @property def _lowercase ( self : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE_ :Tuple = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE_ :Optional[int] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
233
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCamelCase__ : Tuple = { "configuration_maskformer": ["MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "MaskFormerConfig"], "configuration_maskformer_swin": ["MaskFormerSwinConfig"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : List[str] = ["MaskFormerFeatureExtractor"] UpperCamelCase__ : int = ["MaskFormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : Optional[int] = [ "MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "MaskFormerForInstanceSegmentation", "MaskFormerModel", "MaskFormerPreTrainedModel", ] UpperCamelCase__ : str = [ "MaskFormerSwinBackbone", "MaskFormerSwinModel", "MaskFormerSwinPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig from .configuration_maskformer_swin import MaskFormerSwinConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_maskformer import MaskFormerFeatureExtractor from .image_processing_maskformer import MaskFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskformer import ( MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskFormerForInstanceSegmentation, MaskFormerModel, MaskFormerPreTrainedModel, ) from .modeling_maskformer_swin import ( MaskFormerSwinBackbone, MaskFormerSwinModel, MaskFormerSwinPreTrainedModel, ) else: import sys UpperCamelCase__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure)
614
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 SCREAMING_SNAKE_CASE : Optional[int] = ["\nclass", "\ndef", "\n#", "\n@", "\nprint", "\nif"] class UpperCamelCase ( __a ): def __init__(self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , __UpperCamelCase=1 ) -> List[str]: UpperCamelCase_ : Dict = tokenizer UpperCamelCase_ : Dict = dataset UpperCamelCase_ : str = len(__UpperCamelCase ) if n_tasks is None else n_tasks UpperCamelCase_ : int = n_copies def __iter__(self ) -> Any: UpperCamelCase_ : int = [] 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() ) UpperCamelCase_ : 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 UpperCamelCase ( __a ): def __init__(self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) -> Dict: UpperCamelCase_ : List[Any] = start_length UpperCamelCase_ : List[str] = eof_strings UpperCamelCase_ : str = tokenizer def __call__(self , __UpperCamelCase , __UpperCamelCase , **__UpperCamelCase ) -> Union[str, Any]: UpperCamelCase_ : List[str] = self.tokenizer.batch_decode(input_ids[:, self.start_length :] ) UpperCamelCase_ : List[Any] = [] 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_ ( _SCREAMING_SNAKE_CASE : Dict ): UpperCamelCase_ : int = re.split("""(%s)""" % """|""".join(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) # last string should be "" return "".join(string_list[:-2] ) def lowerCAmelCase_ ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Optional[Any]=20 , **_SCREAMING_SNAKE_CASE : List[str] ): UpperCamelCase_ : Union[str, Any] = defaultdict(_SCREAMING_SNAKE_CASE ) # dict of list of generated tokens for step, batch in tqdm(enumerate(_SCREAMING_SNAKE_CASE ) ): with torch.no_grad(): UpperCamelCase_ : str = batch["""ids"""].shape[-1] UpperCamelCase_ : List[str] = accelerator.unwrap_model(_SCREAMING_SNAKE_CASE ).generate( input_ids=batch["""ids"""][:, : batch["""input_len"""]] , num_return_sequences=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) # each task is generated batch_size times UpperCamelCase_ : List[str] = batch["""task_id"""].repeat(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ : Union[str, Any] = accelerator.pad_across_processes( _SCREAMING_SNAKE_CASE , dim=1 , pad_index=tokenizer.pad_token_id ) UpperCamelCase_,UpperCamelCase_ : Any = accelerator.gather((generated_tokens, generated_tasks) ) UpperCamelCase_ : str = generated_tokens.cpu().numpy() UpperCamelCase_ : List[Any] = generated_tasks.cpu().numpy() for task, generated_tokens in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): gen_token_dict[task].append(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ : List[str] = [[] for _ in range(_SCREAMING_SNAKE_CASE )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: UpperCamelCase_ : List[Any] = tokenizer.decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE ) code_gens[task].append(remove_last_block(_SCREAMING_SNAKE_CASE ) ) return code_gens def lowerCAmelCase_ ( ): # Setup configuration UpperCamelCase_ : List[Any] = HfArgumentParser(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ : Optional[Any] = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric UpperCamelCase_ : int = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing UpperCamelCase_ : str = """false""" if args.num_workers is None: UpperCamelCase_ : List[str] = multiprocessing.cpu_count() # Use dataset load to feed to accelerate UpperCamelCase_ : Optional[Any] = Accelerator() set_seed(args.seed , device_specific=_SCREAMING_SNAKE_CASE ) # Load model and tokenizer UpperCamelCase_ : str = AutoTokenizer.from_pretrained(args.model_ckpt ) UpperCamelCase_ : Any = tokenizer.eos_token UpperCamelCase_ : Tuple = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings UpperCamelCase_ : Union[str, Any] = { """do_sample""": args.do_sample, """temperature""": args.temperature, """max_new_tokens""": args.max_new_tokens, """top_p""": args.top_p, """top_k""": args.top_k, """stopping_criteria""": StoppingCriteriaList([EndOfFunctionCriteria(0 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )] ), } # Load evaluation dataset and metric UpperCamelCase_ : Optional[int] = load_dataset("""openai_humaneval""" ) UpperCamelCase_ : Any = load_metric("""code_eval""" ) UpperCamelCase_ : int = args.num_tasks if args.num_tasks is not None else len(human_eval["""test"""] ) UpperCamelCase_ : List[str] = args.n_samples // args.batch_size UpperCamelCase_ : Tuple = TokenizedDataset(_SCREAMING_SNAKE_CASE , human_eval["""test"""] , n_copies=_SCREAMING_SNAKE_CASE , n_tasks=_SCREAMING_SNAKE_CASE ) # do not confuse args.batch_size, which is actually the num_return_sequences UpperCamelCase_ : List[str] = DataLoader(_SCREAMING_SNAKE_CASE , batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: UpperCamelCase_ : str = 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 UpperCamelCase_,UpperCamelCase_ : int = accelerator.prepare(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ : Optional[int] = complete_code( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , n_tasks=_SCREAMING_SNAKE_CASE , batch_size=args.batch_size , **_SCREAMING_SNAKE_CASE , ) if accelerator.is_main_process: UpperCamelCase_ : List[str] = [] for task in tqdm(range(_SCREAMING_SNAKE_CASE ) ): UpperCamelCase_ : int = human_eval["""test"""][task]["""test"""] UpperCamelCase_ : Tuple = f'''check({human_eval["test"][task]["entry_point"]})''' references.append("""\n""" + test_func + """\n""" + entry_point ) # Evaluate completions with "code_eval" metric UpperCamelCase_,UpperCamelCase_ : Any = code_eval_metric.compute( references=_SCREAMING_SNAKE_CASE , predictions=_SCREAMING_SNAKE_CASE , num_workers=args.num_workers ) print(f'''Results: {pass_at_k}''' ) # Save results to json file with open(args.output_file , """w""" ) as fp: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
635
0
"""simple docstring""" import argparse import os import jax as jnp import numpy as onp import torch import torch.nn as nn from music_spectrogram_diffusion import inference from tax import checkpoints from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder lowercase__ :Tuple = 'base_with_context' def lowerCamelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ ) ->Optional[int]: """simple docstring""" __UpperCAmelCase : Dict = nn.Parameter(torch.FloatTensor(weights['''token_embedder''']['''embedding'''] ) ) __UpperCAmelCase : Tuple = nn.Parameter( torch.FloatTensor(weights['''Embed_0''']['''embedding'''] ) , requires_grad=UpperCAmelCase_ ) for lyr_num, lyr in enumerate(model.encoders ): __UpperCAmelCase : int = weights[f'''layers_{lyr_num}'''] __UpperCAmelCase : Tuple = nn.Parameter( torch.FloatTensor(ly_weight['''pre_attention_layer_norm''']['''scale'''] ) ) __UpperCAmelCase : List[Any] = ly_weight['''attention'''] __UpperCAmelCase : int = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) ) __UpperCAmelCase : Tuple = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) ) __UpperCAmelCase : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) ) __UpperCAmelCase : Dict = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) ) __UpperCAmelCase : str = nn.Parameter(torch.FloatTensor(ly_weight['''pre_mlp_layer_norm''']['''scale'''] ) ) __UpperCAmelCase : List[str] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_0''']['''kernel'''].T ) ) __UpperCAmelCase : Optional[int] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_1''']['''kernel'''].T ) ) __UpperCAmelCase : Union[str, Any] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wo''']['''kernel'''].T ) ) __UpperCAmelCase : Tuple = nn.Parameter(torch.FloatTensor(weights['''encoder_norm''']['''scale'''] ) ) return model def lowerCamelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ ) ->Any: """simple docstring""" __UpperCAmelCase : List[Any] = nn.Parameter(torch.FloatTensor(weights['''input_proj''']['''kernel'''].T ) ) __UpperCAmelCase : Dict = nn.Parameter( torch.FloatTensor(weights['''Embed_0''']['''embedding'''] ) , requires_grad=UpperCAmelCase_ ) for lyr_num, lyr in enumerate(model.encoders ): __UpperCAmelCase : Optional[int] = weights[f'''layers_{lyr_num}'''] __UpperCAmelCase : Any = ly_weight['''attention'''] __UpperCAmelCase : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) ) __UpperCAmelCase : int = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) ) __UpperCAmelCase : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) ) __UpperCAmelCase : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) ) __UpperCAmelCase : Tuple = nn.Parameter( torch.FloatTensor(ly_weight['''pre_attention_layer_norm''']['''scale'''] ) ) __UpperCAmelCase : Union[str, Any] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_0''']['''kernel'''].T ) ) __UpperCAmelCase : str = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_1''']['''kernel'''].T ) ) __UpperCAmelCase : str = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wo''']['''kernel'''].T ) ) __UpperCAmelCase : Tuple = nn.Parameter(torch.FloatTensor(ly_weight['''pre_mlp_layer_norm''']['''scale'''] ) ) __UpperCAmelCase : Any = nn.Parameter(torch.FloatTensor(weights['''encoder_norm''']['''scale'''] ) ) return model def lowerCamelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ ) ->Any: """simple docstring""" __UpperCAmelCase : Union[str, Any] = nn.Parameter(torch.FloatTensor(weights['''time_emb_dense0''']['''kernel'''].T ) ) __UpperCAmelCase : List[Any] = nn.Parameter(torch.FloatTensor(weights['''time_emb_dense1''']['''kernel'''].T ) ) __UpperCAmelCase : int = nn.Parameter( torch.FloatTensor(weights['''Embed_0''']['''embedding'''] ) , requires_grad=UpperCAmelCase_ ) __UpperCAmelCase : Dict = nn.Parameter( torch.FloatTensor(weights['''continuous_inputs_projection''']['''kernel'''].T ) ) for lyr_num, lyr in enumerate(model.decoders ): __UpperCAmelCase : Optional[Any] = weights[f'''layers_{lyr_num}'''] __UpperCAmelCase : List[str] = nn.Parameter( torch.FloatTensor(ly_weight['''pre_self_attention_layer_norm''']['''scale'''] ) ) __UpperCAmelCase : Any = nn.Parameter( torch.FloatTensor(ly_weight['''FiLMLayer_0''']['''DenseGeneral_0''']['''kernel'''].T ) ) __UpperCAmelCase : Union[str, Any] = ly_weight['''self_attention'''] __UpperCAmelCase : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) ) __UpperCAmelCase : Optional[Any] = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) ) __UpperCAmelCase : Any = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) ) __UpperCAmelCase : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) ) __UpperCAmelCase : int = ly_weight['''MultiHeadDotProductAttention_0'''] __UpperCAmelCase : Tuple = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) ) __UpperCAmelCase : Dict = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) ) __UpperCAmelCase : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) ) __UpperCAmelCase : Dict = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) ) __UpperCAmelCase : Dict = nn.Parameter( torch.FloatTensor(ly_weight['''pre_cross_attention_layer_norm''']['''scale'''] ) ) __UpperCAmelCase : Optional[int] = nn.Parameter(torch.FloatTensor(ly_weight['''pre_mlp_layer_norm''']['''scale'''] ) ) __UpperCAmelCase : List[str] = nn.Parameter( torch.FloatTensor(ly_weight['''FiLMLayer_1''']['''DenseGeneral_0''']['''kernel'''].T ) ) __UpperCAmelCase : str = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_0''']['''kernel'''].T ) ) __UpperCAmelCase : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_1''']['''kernel'''].T ) ) __UpperCAmelCase : str = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wo''']['''kernel'''].T ) ) __UpperCAmelCase : Optional[Any] = nn.Parameter(torch.FloatTensor(weights['''decoder_norm''']['''scale'''] ) ) __UpperCAmelCase : List[str] = nn.Parameter(torch.FloatTensor(weights['''spec_out_dense''']['''kernel'''].T ) ) return model def lowerCamelCase_ ( UpperCAmelCase_ ) ->str: """simple docstring""" __UpperCAmelCase : int = checkpoints.load_tax_checkpoint(args.checkpoint_path ) __UpperCAmelCase : str = jnp.tree_util.tree_map(onp.array , UpperCAmelCase_ ) __UpperCAmelCase : List[str] = [ '''from __gin__ import dynamic_registration''', '''from music_spectrogram_diffusion.models.diffusion import diffusion_utils''', '''diffusion_utils.ClassifierFreeGuidanceConfig.eval_condition_weight = 2.0''', '''diffusion_utils.DiffusionConfig.classifier_free_guidance = @diffusion_utils.ClassifierFreeGuidanceConfig()''', ] __UpperCAmelCase : Union[str, Any] = os.path.join(args.checkpoint_path , '''..''' , '''config.gin''' ) __UpperCAmelCase : int = inference.parse_training_gin_file(UpperCAmelCase_ , UpperCAmelCase_ ) __UpperCAmelCase : Union[str, Any] = inference.InferenceModel(args.checkpoint_path , UpperCAmelCase_ ) __UpperCAmelCase : Tuple = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''' , variance_type='''fixed_large''' ) __UpperCAmelCase : str = SpectrogramNotesEncoder( max_length=synth_model.sequence_length['''inputs'''] , vocab_size=synth_model.model.module.config.vocab_size , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj='''gated-gelu''' , ) __UpperCAmelCase : Optional[int] = SpectrogramContEncoder( input_dims=synth_model.audio_codec.n_dims , targets_context_length=synth_model.sequence_length['''targets_context'''] , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj='''gated-gelu''' , ) __UpperCAmelCase : Dict = TaFilmDecoder( input_dims=synth_model.audio_codec.n_dims , targets_length=synth_model.sequence_length['''targets_context'''] , max_decoder_noise_time=synth_model.model.module.config.max_decoder_noise_time , d_model=synth_model.model.module.config.emb_dim , num_layers=synth_model.model.module.config.num_decoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , dropout_rate=synth_model.model.module.config.dropout_rate , ) __UpperCAmelCase : List[str] = load_notes_encoder(ta_checkpoint['''target''']['''token_encoder'''] , UpperCAmelCase_ ) __UpperCAmelCase : int = load_continuous_encoder(ta_checkpoint['''target''']['''continuous_encoder'''] , UpperCAmelCase_ ) __UpperCAmelCase : Dict = load_decoder(ta_checkpoint['''target''']['''decoder'''] , UpperCAmelCase_ ) __UpperCAmelCase : Optional[int] = OnnxRuntimeModel.from_pretrained('''kashif/soundstream_mel_decoder''' ) __UpperCAmelCase : str = SpectrogramDiffusionPipeline( notes_encoder=UpperCAmelCase_ , continuous_encoder=UpperCAmelCase_ , decoder=UpperCAmelCase_ , scheduler=UpperCAmelCase_ , melgan=UpperCAmelCase_ , ) if args.save: pipe.save_pretrained(args.output_path ) if __name__ == "__main__": lowercase__ :Optional[int] = argparse.ArgumentParser() parser.add_argument('--output_path', default=None, type=str, required=True, help='Path to the converted model.') parser.add_argument( '--save', default=True, type=bool, required=False, help='Whether to save the converted model or not.' ) parser.add_argument( '--checkpoint_path', default=f"""{MODEL}/checkpoint_500000""", type=str, required=False, help='Path to the original jax model checkpoint.', ) lowercase__ :Dict = parser.parse_args() main(args)
374
"""simple docstring""" 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 snake_case ( __UpperCAmelCase ): '''simple docstring''' _A : torch.FloatTensor class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' @register_to_config def __init__( self : Union[str, Any] , __lowercase : int = 32 , __lowercase : int = 64 , __lowercase : int = 20 , __lowercase : int = 768 , __lowercase : Optional[int]=77 , __lowercase : Union[str, Any]=4 , __lowercase : float = 0.0 , __lowercase : str = "silu" , __lowercase : Optional[str] = None , __lowercase : Optional[str] = None , __lowercase : Optional[str] = "linear" , __lowercase : Optional[str] = "prd" , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , ): '''simple docstring''' super().__init__() __UpperCAmelCase : int = num_attention_heads __UpperCAmelCase : List[Any] = attention_head_dim __UpperCAmelCase : int = num_attention_heads * attention_head_dim __UpperCAmelCase : List[str] = additional_embeddings __UpperCAmelCase : Optional[int] = time_embed_dim or inner_dim __UpperCAmelCase : Tuple = embedding_proj_dim or embedding_dim __UpperCAmelCase : Dict = clip_embed_dim or embedding_dim __UpperCAmelCase : Dict = Timesteps(__lowercase , __lowercase , 0 ) __UpperCAmelCase : List[str] = TimestepEmbedding(__lowercase , __lowercase , out_dim=__lowercase , act_fn=__lowercase ) __UpperCAmelCase : Any = nn.Linear(__lowercase , __lowercase ) if embedding_proj_norm_type is None: __UpperCAmelCase : Dict = None elif embedding_proj_norm_type == "layer": __UpperCAmelCase : Any = nn.LayerNorm(__lowercase ) else: raise ValueError(f'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}''' ) __UpperCAmelCase : List[Any] = nn.Linear(__lowercase , __lowercase ) if encoder_hid_proj_type is None: __UpperCAmelCase : int = None elif encoder_hid_proj_type == "linear": __UpperCAmelCase : int = nn.Linear(__lowercase , __lowercase ) else: raise ValueError(f'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}''' ) __UpperCAmelCase : str = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , __lowercase ) ) if added_emb_type == "prd": __UpperCAmelCase : Optional[int] = nn.Parameter(torch.zeros(1 , 1 , __lowercase ) ) elif added_emb_type is None: __UpperCAmelCase : str = None else: raise ValueError( f'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.''' ) __UpperCAmelCase : Union[str, Any] = nn.ModuleList( [ BasicTransformerBlock( __lowercase , __lowercase , __lowercase , dropout=__lowercase , activation_fn='''gelu''' , attention_bias=__lowercase , ) for d in range(__lowercase ) ] ) if norm_in_type == "layer": __UpperCAmelCase : Optional[Any] = nn.LayerNorm(__lowercase ) elif norm_in_type is None: __UpperCAmelCase : List[Any] = None else: raise ValueError(f'''Unsupported norm_in_type: {norm_in_type}.''' ) __UpperCAmelCase : str = nn.LayerNorm(__lowercase ) __UpperCAmelCase : List[Any] = nn.Linear(__lowercase , __lowercase ) __UpperCAmelCase : List[Any] = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -1_0_0_0_0.0 ) causal_attention_mask.triu_(1 ) __UpperCAmelCase : Optional[Any] = causal_attention_mask[None, ...] self.register_buffer('''causal_attention_mask''' , __lowercase , persistent=__lowercase ) __UpperCAmelCase : Any = nn.Parameter(torch.zeros(1 , __lowercase ) ) __UpperCAmelCase : List[str] = nn.Parameter(torch.zeros(1 , __lowercase ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def A_ ( self : Optional[int] ): '''simple docstring''' __UpperCAmelCase : Optional[int] = {} def fn_recursive_add_processors(__lowercase : str , __lowercase : torch.nn.Module , __lowercase : Dict[str, AttentionProcessor] ): if hasattr(__lowercase , '''set_processor''' ): __UpperCAmelCase : Optional[Any] = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(f'''{name}.{sub_name}''' , __lowercase , __lowercase ) return processors for name, module in self.named_children(): fn_recursive_add_processors(__lowercase , __lowercase , __lowercase ) return processors def A_ ( self : Any , __lowercase : Union[AttentionProcessor, Dict[str, AttentionProcessor]] ): '''simple docstring''' __UpperCAmelCase : Tuple = len(self.attn_processors.keys() ) if isinstance(__lowercase , __lowercase ) and len(__lowercase ) != count: raise ValueError( f'''A dict of processors was passed, but the number of processors {len(__lowercase )} does not match the''' f''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''' ) def fn_recursive_attn_processor(__lowercase : str , __lowercase : torch.nn.Module , __lowercase : int ): if hasattr(__lowercase , '''set_processor''' ): if not isinstance(__lowercase , __lowercase ): module.set_processor(__lowercase ) 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}''' , __lowercase , __lowercase ) for name, module in self.named_children(): fn_recursive_attn_processor(__lowercase , __lowercase , __lowercase ) def A_ ( self : Optional[Any] ): '''simple docstring''' self.set_attn_processor(AttnProcessor() ) def A_ ( self : Optional[int] , __lowercase : Dict , __lowercase : Union[torch.Tensor, float, int] , __lowercase : torch.FloatTensor , __lowercase : Optional[torch.FloatTensor] = None , __lowercase : Optional[torch.BoolTensor] = None , __lowercase : bool = True , ): '''simple docstring''' __UpperCAmelCase : List[Any] = hidden_states.shape[0] __UpperCAmelCase : Any = timestep if not torch.is_tensor(__lowercase ): __UpperCAmelCase : Union[str, Any] = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(__lowercase ) and len(timesteps.shape ) == 0: __UpperCAmelCase : Union[str, Any] = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML __UpperCAmelCase : List[str] = timesteps * torch.ones(__lowercase , dtype=timesteps.dtype , device=timesteps.device ) __UpperCAmelCase : List[str] = self.time_proj(__lowercase ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. __UpperCAmelCase : Any = timesteps_projected.to(dtype=self.dtype ) __UpperCAmelCase : List[str] = self.time_embedding(__lowercase ) if self.embedding_proj_norm is not None: __UpperCAmelCase : Dict = self.embedding_proj_norm(__lowercase ) __UpperCAmelCase : Optional[int] = self.embedding_proj(__lowercase ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: __UpperCAmelCase : Dict = self.encoder_hidden_states_proj(__lowercase ) 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''' ) __UpperCAmelCase : int = self.proj_in(__lowercase ) __UpperCAmelCase : Tuple = self.positional_embedding.to(hidden_states.dtype ) __UpperCAmelCase : Optional[Any] = [] __UpperCAmelCase : str = 0 if encoder_hidden_states is not None: additional_embeds.append(__lowercase ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: __UpperCAmelCase : str = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: __UpperCAmelCase : Optional[int] = hidden_states[:, None, :] __UpperCAmelCase : str = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: __UpperCAmelCase : Dict = self.prd_embedding.to(hidden_states.dtype ).expand(__lowercase , -1 , -1 ) additional_embeds.append(__lowercase ) __UpperCAmelCase : Optional[Any] = torch.cat( __lowercase , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens __UpperCAmelCase : Optional[int] = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: __UpperCAmelCase : List[str] = F.pad( __lowercase , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) __UpperCAmelCase : Dict = hidden_states + positional_embeddings if attention_mask is not None: __UpperCAmelCase : Optional[Any] = (1 - attention_mask.to(hidden_states.dtype )) * -1_0_0_0_0.0 __UpperCAmelCase : Optional[Any] = F.pad(__lowercase , (0, self.additional_embeddings) , value=0.0 ) __UpperCAmelCase : Dict = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) __UpperCAmelCase : Tuple = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: __UpperCAmelCase : str = self.norm_in(__lowercase ) for block in self.transformer_blocks: __UpperCAmelCase : Dict = block(__lowercase , attention_mask=__lowercase ) __UpperCAmelCase : Any = self.norm_out(__lowercase ) if self.prd_embedding is not None: __UpperCAmelCase : List[Any] = hidden_states[:, -1] else: __UpperCAmelCase : List[str] = hidden_states[:, additional_embeddings_len:] __UpperCAmelCase : Optional[int] = self.proj_to_clip_embeddings(__lowercase ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=__lowercase ) def A_ ( self : List[Any] , __lowercase : Optional[int] ): '''simple docstring''' __UpperCAmelCase : List[str] = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
374
1
def _SCREAMING_SNAKE_CASE ( lowercase : Optional[Any] , lowercase : Union[str, Any] ): '''simple docstring''' lowerCamelCase_ = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def _SCREAMING_SNAKE_CASE ( lowercase : List[str] , lowercase : str , lowercase : Dict ): '''simple docstring''' lowerCamelCase_ = 0 while b > 0: if b & 1: lowerCamelCase_ = ((res % c) + (a % c)) % c a += a b >>= 1 return res
70
def _UpperCAmelCase ( UpperCAmelCase : list ): """simple docstring""" __lowerCamelCase : Tuple = 0 while len(UpperCAmelCase ) > 1: __lowerCamelCase : List[str] = 0 # Consider two files with minimum cost to be merged for _ in range(2 ): __lowerCamelCase : List[Any] = files.index(min(UpperCAmelCase ) ) temp += files[min_index] files.pop(UpperCAmelCase ) files.append(UpperCAmelCase ) optimal_merge_cost += temp return optimal_merge_cost if __name__ == "__main__": import doctest doctest.testmod()
519
0
'''simple docstring''' import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser _lowerCamelCase = logging.getLogger(__name__) torch.set_grad_enabled(False) _lowerCamelCase = 'cuda' if torch.cuda.is_available() else 'cpu' def _SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_=100 , snake_case_=" " ): _lowercase = text.split(snake_case_ ) return [character.join(text[i : i + n] ).strip() for i in range(0 , len(snake_case_ ) , snake_case_ )] def _SCREAMING_SNAKE_CASE ( snake_case_ ): _lowercase , _lowercase = [], [] for title, text in zip(documents["""title"""] , documents["""text"""] ): if text is not None: for passage in split_text(snake_case_ ): titles.append(title if title is not None else """""" ) texts.append(snake_case_ ) return {"title": titles, "text": texts} def _SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ , snake_case_ ): _lowercase = ctx_tokenizer( documents["""title"""] , documents["""text"""] , truncation=snake_case_ , padding="""longest""" , return_tensors="""pt""" )["""input_ids"""] _lowercase = ctx_encoder(input_ids.to(device=snake_case_ ) , return_dict=snake_case_ ).pooler_output return {"embeddings": embeddings.detach().cpu().numpy()} def _SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ , snake_case_ , ): ###################################### logger.info("""Step 1 - Create the dataset""" ) ###################################### # The dataset needed for RAG must have three columns: # - title (string): title of the document # - text (string): text of a passage of the document # - embeddings (array of dimension d): DPR representation of the passage # Let's say you have documents in tab-separated csv files with columns "title" and "text" assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file" # You can load a Dataset object this way _lowercase = load_dataset( """csv""" , data_files=[rag_example_args.csv_path] , split="""train""" , delimiter="""\t""" , column_names=["""title""", """text"""] ) # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files # Then split the documents into passages of 100 words _lowercase = dataset.map(snake_case_ , batched=snake_case_ , num_proc=processing_args.num_proc ) # And compute the embeddings _lowercase = DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=snake_case_ ) _lowercase = DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ) _lowercase = Features( {"""text""": Value("""string""" ), """title""": Value("""string""" ), """embeddings""": Sequence(Value("""float32""" ) )} ) # optional, save as float32 instead of float64 to save space _lowercase = dataset.map( partial(snake_case_ , ctx_encoder=snake_case_ , ctx_tokenizer=snake_case_ ) , batched=snake_case_ , batch_size=processing_args.batch_size , features=snake_case_ , ) # And finally save your dataset _lowercase = os.path.join(rag_example_args.output_dir , """my_knowledge_dataset""" ) dataset.save_to_disk(snake_case_ ) # from datasets import load_from_disk # dataset = load_from_disk(passages_path) # to reload the dataset ###################################### logger.info("""Step 2 - Index the dataset""" ) ###################################### # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search _lowercase = faiss.IndexHNSWFlat(index_hnsw_args.d , index_hnsw_args.m , faiss.METRIC_INNER_PRODUCT ) dataset.add_faiss_index("""embeddings""" , custom_index=snake_case_ ) # And save the index _lowercase = os.path.join(rag_example_args.output_dir , """my_knowledge_dataset_hnsw_index.faiss""" ) dataset.get_index("""embeddings""" ).save(snake_case_ ) # dataset.load_faiss_index("embeddings", index_path) # to reload the index @dataclass class __a : __SCREAMING_SNAKE_CASE : str = field( default=str(Path(_snake_case ).parent / 'test_run' / 'dummy-kb' / 'my_knowledge_dataset.csv' ) ,metadata={'help': 'Path to a tab-separated csv file with columns \'title\' and \'text\''} ,) __SCREAMING_SNAKE_CASE : Optional[str] = field( default=_snake_case ,metadata={'help': 'Question that is passed as input to RAG. Default is \'What does Moses\' rod turn into ?\'.'} ,) __SCREAMING_SNAKE_CASE : str = field( default='facebook/rag-sequence-nq' ,metadata={'help': 'The RAG model to use. Either \'facebook/rag-sequence-nq\' or \'facebook/rag-token-nq\''} ,) __SCREAMING_SNAKE_CASE : str = field( default='facebook/dpr-ctx_encoder-multiset-base' ,metadata={ 'help': ( 'The DPR context encoder model to use. Either \'facebook/dpr-ctx_encoder-single-nq-base\' or' ' \'facebook/dpr-ctx_encoder-multiset-base\'' ) } ,) __SCREAMING_SNAKE_CASE : Optional[str] = field( default=str(Path(_snake_case ).parent / 'test_run' / 'dummy-kb' ) ,metadata={'help': 'Path to a directory where the dataset passages and the index will be saved'} ,) @dataclass class __a : __SCREAMING_SNAKE_CASE : Optional[int] = field( default=_snake_case ,metadata={ 'help': 'The number of processes to use to split the documents into passages. Default is single process.' } ,) __SCREAMING_SNAKE_CASE : int = field( default=1_6 ,metadata={ 'help': 'The batch size to use when computing the passages embeddings using the DPR context encoder.' } ,) @dataclass class __a : __SCREAMING_SNAKE_CASE : int = field( default=7_6_8 ,metadata={'help': 'The dimension of the embeddings to pass to the HNSW Faiss index.'} ,) __SCREAMING_SNAKE_CASE : int = field( default=1_2_8 ,metadata={ 'help': ( 'The number of bi-directional links created for every new element during the HNSW index construction.' ) } ,) if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) logger.setLevel(logging.INFO) _lowerCamelCase = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments)) _lowerCamelCase, _lowerCamelCase, _lowerCamelCase = parser.parse_args_into_dataclasses() with TemporaryDirectory() as tmp_dir: _lowerCamelCase = rag_example_args.output_dir or tmp_dir main(rag_example_args, processing_args, index_hnsw_args)
572
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase = { 'configuration_funnel': ['FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FunnelConfig'], 'convert_funnel_original_tf_checkpoint_to_pytorch': [], 'tokenization_funnel': ['FunnelTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['FunnelTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST', 'FunnelBaseModel', 'FunnelForMaskedLM', 'FunnelForMultipleChoice', 'FunnelForPreTraining', 'FunnelForQuestionAnswering', 'FunnelForSequenceClassification', 'FunnelForTokenClassification', 'FunnelModel', 'FunnelPreTrainedModel', 'load_tf_weights_in_funnel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFFunnelBaseModel', 'TFFunnelForMaskedLM', 'TFFunnelForMultipleChoice', 'TFFunnelForPreTraining', 'TFFunnelForQuestionAnswering', 'TFFunnelForSequenceClassification', 'TFFunnelForTokenClassification', 'TFFunnelModel', 'TFFunnelPreTrainedModel', ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
572
1
'''simple docstring''' from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCamelCase : Tuple = logging.get_logger(__name__) _UpperCamelCase : Union[str, Any] = { 'snap-research/efficientformer-l1-300': ( 'https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json' ), } class snake_case__ ( UpperCamelCase): a_ = "efficientformer" def __init__( self : Optional[Any] , _A : List[int] = [3, 2, 6, 4] , _A : List[int] = [48, 96, 2_24, 4_48] , _A : List[bool] = [True, True, True, True] , _A : int = 4_48 , _A : int = 32 , _A : int = 4 , _A : int = 7 , _A : int = 5 , _A : int = 8 , _A : int = 4 , _A : float = 0.0 , _A : int = 16 , _A : int = 3 , _A : int = 3 , _A : int = 3 , _A : int = 2 , _A : int = 1 , _A : float = 0.0 , _A : int = 1 , _A : bool = True , _A : bool = True , _A : float = 1e-5 , _A : str = "gelu" , _A : float = 0.02 , _A : float = 1e-12 , _A : int = 2_24 , _A : float = 1e-05 , **_A : Union[str, Any] , ) -> None: super().__init__(**_A ) UpperCAmelCase_ : Dict = hidden_act UpperCAmelCase_ : List[str] = hidden_dropout_prob UpperCAmelCase_ : List[str] = hidden_sizes UpperCAmelCase_ : int = num_hidden_layers UpperCAmelCase_ : List[str] = num_attention_heads UpperCAmelCase_ : Dict = initializer_range UpperCAmelCase_ : Dict = layer_norm_eps UpperCAmelCase_ : Optional[int] = patch_size UpperCAmelCase_ : Any = num_channels UpperCAmelCase_ : Any = depths UpperCAmelCase_ : Optional[int] = mlp_expansion_ratio UpperCAmelCase_ : Union[str, Any] = downsamples UpperCAmelCase_ : Any = dim UpperCAmelCase_ : Optional[int] = key_dim UpperCAmelCase_ : int = attention_ratio UpperCAmelCase_ : Union[str, Any] = resolution UpperCAmelCase_ : Union[str, Any] = pool_size UpperCAmelCase_ : Dict = downsample_patch_size UpperCAmelCase_ : int = downsample_stride UpperCAmelCase_ : Optional[Any] = downsample_pad UpperCAmelCase_ : Union[str, Any] = drop_path_rate UpperCAmelCase_ : Optional[Any] = num_metaad_blocks UpperCAmelCase_ : Optional[int] = distillation UpperCAmelCase_ : Union[str, Any] = use_layer_scale UpperCAmelCase_ : Optional[int] = layer_scale_init_value UpperCAmelCase_ : str = image_size UpperCAmelCase_ : str = batch_norm_eps
541
'''simple docstring''' from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def __UpperCAmelCase ( A : Optional[int] , A : Optional[int] ) -> str: UpperCAmelCase_ : List[Any] = [] for part_id in partition_order: UpperCAmelCase_ : Any = df.where(F"SPARK_PARTITION_ID() = {part_id}" ).collect() for row_idx, row in enumerate(A ): expected_row_ids_and_row_dicts.append((F"{part_id}_{row_idx}", row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ) -> Any: UpperCAmelCase_ : Any = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() UpperCAmelCase_ : List[str] = spark.range(1_0_0 ).repartition(1 ) UpperCAmelCase_ : List[Any] = Spark(A ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=1_6 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 5_0 @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ) -> str: UpperCAmelCase_ : List[str] = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() UpperCAmelCase_ : Optional[Any] = spark.range(1_0 ).repartition(2 ) UpperCAmelCase_ : int = [1, 0] UpperCAmelCase_ : str = _generate_iterable_examples(A , A ) # Reverse the partitions. UpperCAmelCase_ : Optional[Any] = _get_expected_row_ids_and_row_dicts_for_partition_order(A , A ) for i, (row_id, row_dict) in enumerate(generate_fn() ): UpperCAmelCase_ , UpperCAmelCase_ : int = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ) -> Union[str, Any]: UpperCAmelCase_ : str = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() UpperCAmelCase_ : List[Any] = spark.range(1_0 ).repartition(1 ) UpperCAmelCase_ : Optional[int] = SparkExamplesIterable(A ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(A ): assert row_id == F"0_{i}" assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ) -> Union[str, Any]: UpperCAmelCase_ : Dict = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() UpperCAmelCase_ : Dict = spark.range(3_0 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch('''numpy.random.Generator''' ) as generator_mock: UpperCAmelCase_ : Any = lambda A : x.reverse() UpperCAmelCase_ : Dict = _get_expected_row_ids_and_row_dicts_for_partition_order(A , [2, 1, 0] ) UpperCAmelCase_ : List[Any] = SparkExamplesIterable(A ).shuffle_data_sources(A ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(A ): UpperCAmelCase_ , UpperCAmelCase_ : Dict = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ) -> int: UpperCAmelCase_ : Tuple = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() UpperCAmelCase_ : int = spark.range(2_0 ).repartition(4 ) # Partitions 0 and 2 UpperCAmelCase_ : int = SparkExamplesIterable(A ).shard_data_sources(worker_id=0 , num_workers=2 ) assert shard_it_a.n_shards == 2 UpperCAmelCase_ : Union[str, Any] = _get_expected_row_ids_and_row_dicts_for_partition_order(A , [0, 2] ) for i, (row_id, row_dict) in enumerate(A ): UpperCAmelCase_ , UpperCAmelCase_ : Dict = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 UpperCAmelCase_ : Tuple = SparkExamplesIterable(A ).shard_data_sources(worker_id=1 , num_workers=2 ) assert shard_it_a.n_shards == 2 UpperCAmelCase_ : List[str] = _get_expected_row_ids_and_row_dicts_for_partition_order(A , [1, 3] ) for i, (row_id, row_dict) in enumerate(A ): UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ) -> Any: UpperCAmelCase_ : List[Any] = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() UpperCAmelCase_ : List[str] = spark.range(1_0_0 ).repartition(1 ) UpperCAmelCase_ : int = Spark(A ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 1_0_0
541
1
import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __UpperCamelCase ( _lowercase , unittest.TestCase ): """simple docstring""" _lowercase : str = AudioLDMPipeline _lowercase : Optional[int] = TEXT_TO_AUDIO_PARAMS _lowercase : Optional[Any] = TEXT_TO_AUDIO_BATCH_PARAMS _lowercase : str = frozenset( [ '''num_inference_steps''', '''num_waveforms_per_prompt''', '''generator''', '''latents''', '''output_type''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def _UpperCAmelCase ( self ) -> List[str]: torch.manual_seed(0 ) a__ = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=(3_2, 6_4) , class_embed_type='''simple_projection''' , projection_class_embeddings_input_dim=3_2 , class_embeddings_concat=SCREAMING_SNAKE_CASE , ) a__ = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='''scaled_linear''' , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) torch.manual_seed(0 ) a__ = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=1 , out_channels=1 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) a__ = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , projection_dim=3_2 , ) a__ = ClapTextModelWithProjection(SCREAMING_SNAKE_CASE ) a__ = RobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-roberta''' , model_max_length=7_7 ) a__ = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6_0_0_0 , upsample_initial_channel=1_6 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=SCREAMING_SNAKE_CASE , ) a__ = SpeechTaHifiGan(SCREAMING_SNAKE_CASE ) a__ = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''vocoder''': vocoder, } return components def _UpperCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0 ) -> Any: if str(SCREAMING_SNAKE_CASE ).startswith('''mps''' ): a__ = torch.manual_seed(SCREAMING_SNAKE_CASE ) else: a__ = torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(SCREAMING_SNAKE_CASE ) a__ = { '''prompt''': '''A hammer hitting a wooden surface''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, } return inputs def _UpperCAmelCase ( self ) -> Dict: a__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator a__ = self.get_dummy_components() a__ = AudioLDMPipeline(**SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) a__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe(**SCREAMING_SNAKE_CASE ) a__ = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE ) == 2_5_6 a__ = audio[:1_0] a__ = np.array( [-0.00_50, 0.00_50, -0.00_60, 0.00_33, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_33] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def _UpperCAmelCase ( self ) -> Any: a__ = self.get_dummy_components() a__ = AudioLDMPipeline(**SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) a__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) a__ = 3 * [inputs['''prompt''']] # forward a__ = audioldm_pipe(**SCREAMING_SNAKE_CASE ) a__ = output.audios[0] a__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) a__ = 3 * [inputs.pop('''prompt''' )] a__ = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE , padding='''max_length''' , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE , return_tensors='''pt''' , ) a__ = text_inputs['''input_ids'''].to(SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE , ) a__ = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state a__ = F.normalize(SCREAMING_SNAKE_CASE , dim=-1 ) a__ = prompt_embeds # forward a__ = audioldm_pipe(**SCREAMING_SNAKE_CASE ) a__ = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def _UpperCAmelCase ( self ) -> Optional[Any]: a__ = self.get_dummy_components() a__ = AudioLDMPipeline(**SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) a__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) a__ = 3 * ['''this is a negative prompt'''] a__ = negative_prompt a__ = 3 * [inputs['''prompt''']] # forward a__ = audioldm_pipe(**SCREAMING_SNAKE_CASE ) a__ = output.audios[0] a__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) a__ = 3 * [inputs.pop('''prompt''' )] a__ = [] for p in [prompt, negative_prompt]: a__ = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE , padding='''max_length''' , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE , return_tensors='''pt''' , ) a__ = text_inputs['''input_ids'''].to(SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE , ) a__ = text_embeds.text_embeds # additional L_2 normalization over each hidden-state a__ = F.normalize(SCREAMING_SNAKE_CASE , dim=-1 ) embeds.append(SCREAMING_SNAKE_CASE ) a__ , a__ = embeds # forward a__ = audioldm_pipe(**SCREAMING_SNAKE_CASE ) a__ = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def _UpperCAmelCase ( self ) -> Dict: a__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator a__ = self.get_dummy_components() a__ = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE ) a__ = AudioLDMPipeline(**SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) a__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) a__ = '''egg cracking''' a__ = audioldm_pipe(**SCREAMING_SNAKE_CASE , negative_prompt=SCREAMING_SNAKE_CASE ) a__ = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE ) == 2_5_6 a__ = audio[:1_0] a__ = np.array( [-0.00_51, 0.00_50, -0.00_60, 0.00_34, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_32] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def _UpperCAmelCase ( self ) -> List[str]: a__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator a__ = self.get_dummy_components() a__ = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE ) a__ = AudioLDMPipeline(**SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) a__ = '''A hammer hitting a wooden surface''' # test num_waveforms_per_prompt=1 (default) a__ = audioldm_pipe(SCREAMING_SNAKE_CASE , num_inference_steps=2 ).audios assert audios.shape == (1, 2_5_6) # test num_waveforms_per_prompt=1 (default) for batch of prompts a__ = 2 a__ = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 2_5_6) # test num_waveforms_per_prompt for single prompt a__ = 2 a__ = audioldm_pipe(SCREAMING_SNAKE_CASE , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE ).audios assert audios.shape == (num_waveforms_per_prompt, 2_5_6) # test num_waveforms_per_prompt for batch of prompts a__ = 2 a__ = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 2_5_6) def _UpperCAmelCase ( self ) -> int: a__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator a__ = self.get_dummy_components() a__ = AudioLDMPipeline(**SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe.vocoder.config.sampling_rate a__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe(audio_length_in_s=0.0_16 , **SCREAMING_SNAKE_CASE ) a__ = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE ) / vocoder_sampling_rate == 0.0_16 a__ = audioldm_pipe(audio_length_in_s=0.0_32 , **SCREAMING_SNAKE_CASE ) a__ = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE ) / vocoder_sampling_rate == 0.0_32 def _UpperCAmelCase ( self ) -> Union[str, Any]: a__ = self.get_dummy_components() a__ = AudioLDMPipeline(**SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) a__ = ['''hey'''] a__ = audioldm_pipe(SCREAMING_SNAKE_CASE , num_inference_steps=1 ) a__ = output.audios.shape assert audio_shape == (1, 2_5_6) a__ = audioldm_pipe.vocoder.config config.model_in_dim *= 2 a__ = SpeechTaHifiGan(SCREAMING_SNAKE_CASE ).to(SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe(SCREAMING_SNAKE_CASE , num_inference_steps=1 ) a__ = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 2_5_6) def _UpperCAmelCase ( self ) -> Dict: self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( self ) -> Union[str, Any]: self._test_inference_batch_single_identical(test_mean_pixel_difference=SCREAMING_SNAKE_CASE ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def _UpperCAmelCase ( self ) -> List[str]: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE ) @slow class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def _UpperCAmelCase ( self ) -> Union[str, Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def _UpperCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE="cpu" , SCREAMING_SNAKE_CASE=torch.floataa , SCREAMING_SNAKE_CASE=0 ) -> Union[str, Any]: a__ = torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(SCREAMING_SNAKE_CASE ) a__ = np.random.RandomState(SCREAMING_SNAKE_CASE ).standard_normal((1, 8, 1_2_8, 1_6) ) a__ = torch.from_numpy(SCREAMING_SNAKE_CASE ).to(device=SCREAMING_SNAKE_CASE , dtype=SCREAMING_SNAKE_CASE ) a__ = { '''prompt''': '''A hammer hitting a wooden surface''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 2.5, } return inputs def _UpperCAmelCase ( self ) -> str: a__ = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''' ) a__ = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) a__ = self.get_inputs(SCREAMING_SNAKE_CASE ) a__ = 2_5 a__ = audioldm_pipe(**SCREAMING_SNAKE_CASE ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE ) == 8_1_9_2_0 a__ = audio[7_7_2_3_0:7_7_2_4_0] a__ = np.array( [-0.48_84, -0.46_07, 0.00_23, 0.50_07, 0.58_96, 0.51_51, 0.38_13, -0.02_08, -0.36_87, -0.43_15] ) a__ = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def _UpperCAmelCase ( self ) -> Any: a__ = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''' ) a__ = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) a__ = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) a__ = self.get_inputs(SCREAMING_SNAKE_CASE ) a__ = audioldm_pipe(**SCREAMING_SNAKE_CASE ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE ) == 8_1_9_2_0 a__ = audio[2_7_7_8_0:2_7_7_9_0] a__ = np.array([-0.21_31, -0.08_73, -0.01_24, -0.01_89, 0.05_69, 0.13_73, 0.18_83, 0.28_86, 0.32_97, 0.22_12] ) a__ = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
148
import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def _UpperCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: a__ = jnp.ones((batch_size, length) ) / length return scores def _UpperCAmelCase ( self ) -> int: a__ = None a__ = 2_0 a__ = self._get_uniform_logits(batch_size=2 , length=SCREAMING_SNAKE_CASE ) # tweak scores to not be uniform anymore a__ = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch a__ = scores.at[1, 1_0].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax a__ = jax.nn.softmax(SCREAMING_SNAKE_CASE , axis=-1 ) a__ = FlaxTemperatureLogitsWarper(temperature=0.5 ) a__ = FlaxTemperatureLogitsWarper(temperature=1.3 ) a__ = jax.nn.softmax(temp_dist_warper_sharper(SCREAMING_SNAKE_CASE , scores.copy() , cur_len=SCREAMING_SNAKE_CASE ) , axis=-1 ) a__ = jax.nn.softmax(temp_dist_warper_smoother(SCREAMING_SNAKE_CASE , scores.copy() , cur_len=SCREAMING_SNAKE_CASE ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def _UpperCAmelCase ( self ) -> Dict: a__ = None a__ = 1_0 a__ = 2 # create ramp distribution a__ = np.broadcast_to(np.arange(SCREAMING_SNAKE_CASE )[None, :] , (batch_size, vocab_size) ).copy() a__ = ramp_logits[1:, : vocab_size // 2] + vocab_size a__ = FlaxTopKLogitsWarper(3 ) a__ = top_k_warp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case a__ = 5 a__ = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) a__ = np.broadcast_to(np.arange(SCREAMING_SNAKE_CASE )[None, :] , (batch_size, length) ).copy() a__ = top_k_warp_safety_check(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def _UpperCAmelCase ( self ) -> List[str]: a__ = None a__ = 1_0 a__ = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) a__ = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) ) a__ = FlaxTopPLogitsWarper(0.8 ) a__ = np.exp(top_p_warp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 a__ = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # check edge cases with negative and extreme logits a__ = np.broadcast_to(np.arange(SCREAMING_SNAKE_CASE )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme a__ = ramp_logits[1] * 1_00.0 # make sure at least 2 tokens are kept a__ = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) a__ = top_p_warp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def _UpperCAmelCase ( self ) -> str: a__ = 2_0 a__ = 4 a__ = 0 a__ = FlaxMinLengthLogitsProcessor(min_length=1_0 , eos_token_id=SCREAMING_SNAKE_CASE ) # check that min length is applied at length 5 a__ = ids_tensor((batch_size, 2_0) , vocab_size=2_0 ) a__ = 5 a__ = self._get_uniform_logits(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ = min_dist_processor(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('''inf''' )] ) # check that min length is not applied anymore at length 15 a__ = self._get_uniform_logits(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ = 1_5 a__ = min_dist_processor(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) self.assertFalse(jnp.isinf(SCREAMING_SNAKE_CASE ).any() ) def _UpperCAmelCase ( self ) -> Union[str, Any]: a__ = 2_0 a__ = 4 a__ = 0 a__ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=SCREAMING_SNAKE_CASE ) # check that all scores are -inf except the bos_token_id score a__ = ids_tensor((batch_size, 1) , vocab_size=2_0 ) a__ = 1 a__ = self._get_uniform_logits(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ = logits_processor(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 a__ = 3 a__ = self._get_uniform_logits(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ = logits_processor(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) self.assertFalse(jnp.isinf(SCREAMING_SNAKE_CASE ).any() ) def _UpperCAmelCase ( self ) -> str: a__ = 2_0 a__ = 4 a__ = 0 a__ = 5 a__ = FlaxForcedEOSTokenLogitsProcessor(max_length=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE ) # check that all scores are -inf except the eos_token_id when max_length is reached a__ = ids_tensor((batch_size, 4) , vocab_size=2_0 ) a__ = 4 a__ = self._get_uniform_logits(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ = logits_processor(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached a__ = 3 a__ = self._get_uniform_logits(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ = logits_processor(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) self.assertFalse(jnp.isinf(SCREAMING_SNAKE_CASE ).any() ) def _UpperCAmelCase ( self ) -> List[str]: a__ = 4 a__ = 1_0 a__ = 1_5 a__ = 2 a__ = 1 a__ = 1_5 # dummy input_ids and scores a__ = ids_tensor((batch_size, sequence_length) , SCREAMING_SNAKE_CASE ) a__ = input_ids.copy() a__ = self._get_uniform_logits(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ = scores.copy() # instantiate all dist processors a__ = FlaxTemperatureLogitsWarper(temperature=0.5 ) a__ = FlaxTopKLogitsWarper(3 ) a__ = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors a__ = FlaxMinLengthLogitsProcessor(min_length=1_0 , eos_token_id=SCREAMING_SNAKE_CASE ) a__ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=SCREAMING_SNAKE_CASE ) a__ = FlaxForcedEOSTokenLogitsProcessor(max_length=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE ) a__ = 1_0 # no processor list a__ = temp_dist_warp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) a__ = top_k_warp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) a__ = top_p_warp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) a__ = min_dist_proc(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) a__ = bos_dist_proc(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) a__ = eos_dist_proc(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) # with processor list a__ = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) a__ = processor(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) # scores should be equal self.assertTrue(jnp.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def _UpperCAmelCase ( self ) -> Optional[int]: a__ = 4 a__ = 1_0 a__ = 1_5 a__ = 2 a__ = 1 a__ = 1_5 # dummy input_ids and scores a__ = ids_tensor((batch_size, sequence_length) , SCREAMING_SNAKE_CASE ) a__ = input_ids.copy() a__ = self._get_uniform_logits(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ = scores.copy() # instantiate all dist processors a__ = FlaxTemperatureLogitsWarper(temperature=0.5 ) a__ = FlaxTopKLogitsWarper(3 ) a__ = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors a__ = FlaxMinLengthLogitsProcessor(min_length=1_0 , eos_token_id=SCREAMING_SNAKE_CASE ) a__ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=SCREAMING_SNAKE_CASE ) a__ = FlaxForcedEOSTokenLogitsProcessor(max_length=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE ) a__ = 1_0 # no processor list def run_no_processor_list(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): a__ = temp_dist_warp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) a__ = top_k_warp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) a__ = top_p_warp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) a__ = min_dist_proc(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) a__ = bos_dist_proc(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) a__ = eos_dist_proc(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) return scores # with processor list def run_processor_list(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): a__ = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) a__ = processor(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cur_len=SCREAMING_SNAKE_CASE ) return scores a__ = jax.jit(SCREAMING_SNAKE_CASE ) a__ = jax.jit(SCREAMING_SNAKE_CASE ) a__ = jitted_run_no_processor_list(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ = jitted_run_processor_list(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # scores should be equal self.assertTrue(jnp.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
148
1
from copy import deepcopy from typing import Optional, Union import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_tf_available, is_torch_available if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf class __lowerCamelCase (__UpperCamelCase ): _lowercase = ["image_processor"] _lowercase = "SamImageProcessor" def __init__( self: Any,A_: Any ): '''simple docstring''' super().__init__(snake_case__ ) __UpperCamelCase = self.image_processor __UpperCamelCase = -10 __UpperCamelCase = self.image_processor.size['longest_edge'] def __call__( self: List[str],A_: Tuple=None,A_: List[str]=None,A_: int=None,A_: Tuple=None,A_: Optional[Union[str, TensorType]] = None,**A_: Optional[Any],): '''simple docstring''' __UpperCamelCase = self.image_processor( snake_case__,return_tensors=snake_case__,**snake_case__,) # pop arguments that are not used in the foward but used nevertheless __UpperCamelCase = encoding_image_processor['original_sizes'] if hasattr(snake_case__,'numpy' ): # Checks if Torch or TF tensor __UpperCamelCase = original_sizes.numpy() __UpperCamelCase, __UpperCamelCase, __UpperCamelCase = self._check_and_preprocess_points( input_points=snake_case__,input_labels=snake_case__,input_boxes=snake_case__,) __UpperCamelCase = self._normalize_and_convert( snake_case__,snake_case__,input_points=snake_case__,input_labels=snake_case__,input_boxes=snake_case__,return_tensors=snake_case__,) return encoding_image_processor def snake_case_ ( self: List[Any],A_: Tuple,A_: Optional[Any],A_: Any=None,A_: Tuple=None,A_: Any=None,A_: Any="pt",): '''simple docstring''' if input_points is not None: if len(snake_case__ ) != len(snake_case__ ): __UpperCamelCase = [ self._normalize_coordinates(self.target_size,snake_case__,original_sizes[0] ) for point in input_points ] else: __UpperCamelCase = [ self._normalize_coordinates(self.target_size,snake_case__,snake_case__ ) for point, original_size in zip(snake_case__,snake_case__ ) ] # check that all arrays have the same shape if not all(point.shape == input_points[0].shape for point in input_points ): if input_labels is not None: __UpperCamelCase, __UpperCamelCase = self._pad_points_and_labels(snake_case__,snake_case__ ) __UpperCamelCase = np.array(snake_case__ ) if input_labels is not None: __UpperCamelCase = np.array(snake_case__ ) if input_boxes is not None: if len(snake_case__ ) != len(snake_case__ ): __UpperCamelCase = [ self._normalize_coordinates(self.target_size,snake_case__,original_sizes[0],is_bounding_box=snake_case__ ) for box in input_boxes ] else: __UpperCamelCase = [ self._normalize_coordinates(self.target_size,snake_case__,snake_case__,is_bounding_box=snake_case__ ) for box, original_size in zip(snake_case__,snake_case__ ) ] __UpperCamelCase = np.array(snake_case__ ) if input_boxes is not None: if return_tensors == "pt": __UpperCamelCase = torch.from_numpy(snake_case__ ) # boxes batch size of 1 by default __UpperCamelCase = input_boxes.unsqueeze(1 ) if len(input_boxes.shape ) != 3 else input_boxes elif return_tensors == "tf": __UpperCamelCase = tf.convert_to_tensor(snake_case__ ) # boxes batch size of 1 by default __UpperCamelCase = tf.expand_dims(snake_case__,1 ) if len(input_boxes.shape ) != 3 else input_boxes encoding_image_processor.update({'input_boxes': input_boxes} ) if input_points is not None: if return_tensors == "pt": __UpperCamelCase = torch.from_numpy(snake_case__ ) # point batch size of 1 by default __UpperCamelCase = input_points.unsqueeze(1 ) if len(input_points.shape ) != 4 else input_points elif return_tensors == "tf": __UpperCamelCase = tf.convert_to_tensor(snake_case__ ) # point batch size of 1 by default __UpperCamelCase = tf.expand_dims(snake_case__,1 ) if len(input_points.shape ) != 4 else input_points encoding_image_processor.update({'input_points': input_points} ) if input_labels is not None: if return_tensors == "pt": __UpperCamelCase = torch.from_numpy(snake_case__ ) # point batch size of 1 by default __UpperCamelCase = input_labels.unsqueeze(1 ) if len(input_labels.shape ) != 3 else input_labels elif return_tensors == "tf": __UpperCamelCase = tf.convert_to_tensor(snake_case__ ) # point batch size of 1 by default __UpperCamelCase = tf.expand_dims(snake_case__,1 ) if len(input_labels.shape ) != 3 else input_labels encoding_image_processor.update({'input_labels': input_labels} ) return encoding_image_processor def snake_case_ ( self: str,A_: Any,A_: str ): '''simple docstring''' __UpperCamelCase = max([point.shape[0] for point in input_points] ) __UpperCamelCase = [] for i, point in enumerate(snake_case__ ): if point.shape[0] != expected_nb_points: __UpperCamelCase = np.concatenate( [point, np.zeros((expected_nb_points - point.shape[0], 2) ) + self.point_pad_value],axis=0 ) __UpperCamelCase = np.append(input_labels[i],[self.point_pad_value] ) processed_input_points.append(snake_case__ ) __UpperCamelCase = processed_input_points return input_points, input_labels def snake_case_ ( self: Tuple,A_: int,A_: np.ndarray,A_: Dict,A_: Any=False ): '''simple docstring''' __UpperCamelCase, __UpperCamelCase = original_size __UpperCamelCase, __UpperCamelCase = self.image_processor._get_preprocess_shape(snake_case__,longest_edge=snake_case__ ) __UpperCamelCase = deepcopy(snake_case__ ).astype(snake_case__ ) if is_bounding_box: __UpperCamelCase = coords.reshape(-1,2,2 ) __UpperCamelCase = coords[..., 0] * (new_w / old_w) __UpperCamelCase = coords[..., 1] * (new_h / old_h) if is_bounding_box: __UpperCamelCase = coords.reshape(-1,4 ) return coords def snake_case_ ( self: str,A_: int=None,A_: Union[str, Any]=None,A_: Union[str, Any]=None,): '''simple docstring''' if input_points is not None: if hasattr(snake_case__,'numpy' ): # Checks for TF or Torch tensor __UpperCamelCase = input_points.numpy().tolist() if not isinstance(snake_case__,snake_case__ ) or not isinstance(input_points[0],snake_case__ ): raise ValueError('Input points must be a list of list of floating points.' ) __UpperCamelCase = [np.array(snake_case__ ) for input_point in input_points] else: __UpperCamelCase = None if input_labels is not None: if hasattr(snake_case__,'numpy' ): __UpperCamelCase = input_labels.numpy().tolist() if not isinstance(snake_case__,snake_case__ ) or not isinstance(input_labels[0],snake_case__ ): raise ValueError('Input labels must be a list of list integers.' ) __UpperCamelCase = [np.array(snake_case__ ) for label in input_labels] else: __UpperCamelCase = None if input_boxes is not None: if hasattr(snake_case__,'numpy' ): __UpperCamelCase = input_boxes.numpy().tolist() if ( not isinstance(snake_case__,snake_case__ ) or not isinstance(input_boxes[0],snake_case__ ) or not isinstance(input_boxes[0][0],snake_case__ ) ): raise ValueError('Input boxes must be a list of list of list of floating points.' ) __UpperCamelCase = [np.array(snake_case__ ).astype(np.floataa ) for box in input_boxes] else: __UpperCamelCase = None return input_points, input_labels, input_boxes @property def snake_case_ ( self: Optional[int] ): '''simple docstring''' __UpperCamelCase = self.image_processor.model_input_names return list(dict.fromkeys(snake_case__ ) ) def snake_case_ ( self: List[str],*A_: str,**A_: List[Any] ): '''simple docstring''' return self.image_processor.post_process_masks(*snake_case__,**snake_case__ )
1
"""simple docstring""" def _UpperCAmelCase ( lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" return abs(lowerCamelCase__ ) if a == 0 else greatest_common_divisor(b % a , lowerCamelCase__ ) def _UpperCAmelCase ( lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" while y: # --> when y=0 then loop will terminate and return x as final GCD. lowerCAmelCase__ , lowerCAmelCase__ = y, x % y return abs(lowerCamelCase__ ) def _UpperCAmelCase ( ): """simple docstring""" try: lowerCAmelCase__ = input("""Enter two integers separated by comma (,): """ ).split(""",""" ) lowerCAmelCase__ = int(nums[0] ) lowerCAmelCase__ = int(nums[1] ) print( f"""greatest_common_divisor({num_a}, {num_a}) = """ f"""{greatest_common_divisor(lowerCamelCase__ , lowerCamelCase__ )}""" ) print(f"""By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(lowerCamelCase__ , lowerCamelCase__ )}""" ) except (IndexError, UnboundLocalError, ValueError): print("""Wrong input""" ) if __name__ == "__main__": main()
644
0
'''simple docstring''' def __snake_case ( SCREAMING_SNAKE_CASE_ : float ) -> float: """simple docstring""" if edge <= 0 or not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): raise ValueError('''Length must be a positive.''' ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def __snake_case ( SCREAMING_SNAKE_CASE_ : float ) -> float: """simple docstring""" if edge <= 0 or not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): raise ValueError('''Length must be a positive.''' ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
711
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =StableDiffusionInpaintPipeline _lowerCamelCase =TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _lowerCamelCase =TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _lowerCamelCase =frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _lowerCamelCase =frozenset([] ) def __snake_case ( self : List[str] ): torch.manual_seed(0 ) UpperCAmelCase = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a__ , ) UpperCAmelCase = PNDMScheduler(skip_prk_steps=a__ ) torch.manual_seed(0 ) UpperCAmelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='''gelu''' , projection_dim=512 , ) UpperCAmelCase = CLIPTextModel(a__ ) UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) UpperCAmelCase = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __snake_case ( self : Dict , a__ : List[Any] , a__ : Tuple=0 ): # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched UpperCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(a__ ) ).to(a__ ) UpperCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCAmelCase = Image.fromarray(np.uinta(a__ ) ).convert('''RGB''' ).resize((64, 64) ) UpperCAmelCase = Image.fromarray(np.uinta(image + 4 ) ).convert('''RGB''' ).resize((64, 64) ) if str(a__ ).startswith('''mps''' ): UpperCAmelCase = torch.manual_seed(a__ ) else: UpperCAmelCase = torch.Generator(device=a__ ).manual_seed(a__ ) UpperCAmelCase = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': init_image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def __snake_case ( self : int ): UpperCAmelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator UpperCAmelCase = self.get_dummy_components() UpperCAmelCase = StableDiffusionInpaintPipeline(**a__ ) UpperCAmelCase = sd_pipe.to(a__ ) sd_pipe.set_progress_bar_config(disable=a__ ) UpperCAmelCase = self.get_dummy_inputs(a__ ) UpperCAmelCase = sd_pipe(**a__ ).images UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __snake_case ( self : List[Any] ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __snake_case ( self : Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self : Any ): UpperCAmelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) UpperCAmelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) UpperCAmelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench.npy''' ) UpperCAmelCase = '''stabilityai/stable-diffusion-2-inpainting''' UpperCAmelCase = StableDiffusionInpaintPipeline.from_pretrained(a__ , safety_checker=a__ ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing() UpperCAmelCase = '''Face of a yellow cat, high resolution, sitting on a park bench''' UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = pipe( prompt=a__ , image=a__ , mask_image=a__ , generator=a__ , output_type='''np''' , ) UpperCAmelCase = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9e-3 def __snake_case ( self : int ): UpperCAmelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) UpperCAmelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) UpperCAmelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench_fp16.npy''' ) UpperCAmelCase = '''stabilityai/stable-diffusion-2-inpainting''' UpperCAmelCase = StableDiffusionInpaintPipeline.from_pretrained( a__ , torch_dtype=torch.floataa , safety_checker=a__ , ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing() UpperCAmelCase = '''Face of a yellow cat, high resolution, sitting on a park bench''' UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = pipe( prompt=a__ , image=a__ , mask_image=a__ , generator=a__ , output_type='''np''' , ) UpperCAmelCase = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5e-1 def __snake_case ( self : List[str] ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() UpperCAmelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) UpperCAmelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) UpperCAmelCase = '''stabilityai/stable-diffusion-2-inpainting''' UpperCAmelCase = PNDMScheduler.from_pretrained(a__ , subfolder='''scheduler''' ) UpperCAmelCase = StableDiffusionInpaintPipeline.from_pretrained( a__ , safety_checker=a__ , scheduler=a__ , torch_dtype=torch.floataa , ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() UpperCAmelCase = '''Face of a yellow cat, high resolution, sitting on a park bench''' UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = pipe( prompt=a__ , image=a__ , mask_image=a__ , generator=a__ , num_inference_steps=2 , output_type='''np''' , ) UpperCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
570
0
from __future__ import annotations from collections.abc import Callable __A : int = list[list[float | int]] def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Matrix: """simple docstring""" _A = len(_SCREAMING_SNAKE_CASE ) _A = [[0 for _ in range(size + 1 )] for _ in range(_SCREAMING_SNAKE_CASE )] _A = 42 _A = 42 _A = 42 _A = 42 _A = 42 _A = 42 for row in range(_SCREAMING_SNAKE_CASE ): for col in range(_SCREAMING_SNAKE_CASE ): _A = matrix[row][col] _A = vector[row][0] _A = 0 _A = 0 while row < size and col < size: # pivoting _A = max((abs(augmented[rowa][col] ), rowa) for rowa in range(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: _A, _A = augmented[pivot_row], augmented[row] for rowa in range(row + 1 , _SCREAMING_SNAKE_CASE ): _A = augmented[rowa][col] / augmented[row][col] _A = 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 , _SCREAMING_SNAKE_CASE ): for row in range(_SCREAMING_SNAKE_CASE ): _A = augmented[row][col] / augmented[col][col] for cola in range(_SCREAMING_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(_SCREAMING_SNAKE_CASE ) ] def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Callable[[int], int]: """simple docstring""" _A = len(_SCREAMING_SNAKE_CASE ) _A = [[0 for _ in range(_SCREAMING_SNAKE_CASE )] for _ in range(_SCREAMING_SNAKE_CASE )] _A = [[0] for _ in range(_SCREAMING_SNAKE_CASE )] _A = 42 _A = 42 _A = 42 _A = 42 for x_val, y_val in enumerate(_SCREAMING_SNAKE_CASE ): for col in range(_SCREAMING_SNAKE_CASE ): _A = (x_val + 1) ** (size - col - 1) _A = y_val _A = solve(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def interpolated_func(_SCREAMING_SNAKE_CASE ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(_SCREAMING_SNAKE_CASE ) ) return interpolated_func def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE = question_function , _SCREAMING_SNAKE_CASE = 10 ) -> int: """simple docstring""" _A = [func(_SCREAMING_SNAKE_CASE ) for x_val in range(1 , order + 1 )] _A = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 ) ] _A = 0 _A = 42 _A = 42 for poly in polynomials: _A = 1 while func(_SCREAMING_SNAKE_CASE ) == poly(_SCREAMING_SNAKE_CASE ): x_val += 1 ret += poly(_SCREAMING_SNAKE_CASE ) return ret if __name__ == "__main__": print(f"{solution() = }")
27
__A : Dict = "Alexander Joslin" import operator as op from .stack import Stack def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" _A = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub} _A = Stack() _A = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(_SCREAMING_SNAKE_CASE ) ) elif i in operators: # RULE 2 operator_stack.push(_SCREAMING_SNAKE_CASE ) elif i == ")": # RULE 4 _A = operator_stack.peek() operator_stack.pop() _A = operand_stack.peek() operand_stack.pop() _A = operand_stack.peek() operand_stack.pop() _A = operators[opr](_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) operand_stack.push(_SCREAMING_SNAKE_CASE ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": __A : Any = "(5 + ((4 * 2) * (2 + 3)))" # answer = 45 print(f"{equation} = {dijkstras_two_stack_algorithm(equation)}")
27
1
from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A_ : '''simple docstring''' def __init__( self , _A , _A=3 , _A=32 , _A=3 , _A=10 , _A=[10, 20, 30, 40] , _A=[1, 1, 2, 1] , _A=True , _A=True , _A="relu" , _A=3 , _A=None , ) -> List[Any]: """simple docstring""" _UpperCAmelCase : Optional[int] = parent _UpperCAmelCase : List[str] = batch_size _UpperCAmelCase : Tuple = image_size _UpperCAmelCase : List[str] = num_channels _UpperCAmelCase : List[str] = embeddings_size _UpperCAmelCase : str = hidden_sizes _UpperCAmelCase : Union[str, Any] = depths _UpperCAmelCase : List[Any] = is_training _UpperCAmelCase : str = use_labels _UpperCAmelCase : Dict = hidden_act _UpperCAmelCase : Dict = num_labels _UpperCAmelCase : Dict = scope _UpperCAmelCase : Tuple = len(_A) def snake_case__ ( self) -> List[str]: """simple docstring""" _UpperCAmelCase : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) _UpperCAmelCase : int = None if self.use_labels: _UpperCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.num_labels) _UpperCAmelCase : str = self.get_config() return config, pixel_values, labels def snake_case__ ( self) -> Optional[int]: """simple docstring""" return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def snake_case__ ( self , _A , _A , _A) -> List[str]: """simple docstring""" _UpperCAmelCase : Optional[int] = TFRegNetModel(config=_A) _UpperCAmelCase : str = model(_A , training=_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 snake_case__ ( self , _A , _A , _A) -> Optional[Any]: """simple docstring""" _UpperCAmelCase : List[Any] = self.num_labels _UpperCAmelCase : List[Any] = TFRegNetForImageClassification(_A) _UpperCAmelCase : Any = model(_A , labels=_A , training=_A) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def snake_case__ ( self) -> Optional[Any]: """simple docstring""" _UpperCAmelCase : Optional[Any] = self.prepare_config_and_inputs() _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : str = config_and_inputs _UpperCAmelCase : Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class A_ ( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' _SCREAMING_SNAKE_CASE : Dict = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () _SCREAMING_SNAKE_CASE : Optional[int] = ( {"feature-extraction": TFRegNetModel, "image-classification": TFRegNetForImageClassification} if is_tf_available() else {} ) _SCREAMING_SNAKE_CASE : int = False _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : List[str] = False _SCREAMING_SNAKE_CASE : List[str] = False _SCREAMING_SNAKE_CASE : List[Any] = False def snake_case__ ( self) -> int: """simple docstring""" _UpperCAmelCase : Tuple = TFRegNetModelTester(self) _UpperCAmelCase : Tuple = ConfigTester(self , config_class=_A , has_text_modality=_A) def snake_case__ ( self) -> Dict: """simple docstring""" return @unittest.skip(reason='''RegNet does not use inputs_embeds''') def snake_case__ ( self) -> List[str]: """simple docstring""" pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('''GPU''')) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , ) @slow def snake_case__ ( self) -> Tuple: """simple docstring""" super().test_keras_fit() @unittest.skip(reason='''RegNet does not support input and output embeddings''') def snake_case__ ( self) -> Optional[int]: """simple docstring""" pass def snake_case__ ( self) -> Dict: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase : Any = model_class(_A) _UpperCAmelCase : str = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCAmelCase : List[str] = [*signature.parameters.keys()] _UpperCAmelCase : List[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _A) def snake_case__ ( self) -> str: """simple docstring""" _UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A) def snake_case__ ( self) -> Optional[int]: """simple docstring""" def check_hidden_states_output(_A , _A , _A): _UpperCAmelCase : Optional[int] = model_class(_A) _UpperCAmelCase : Any = model(**self._prepare_for_class(_A , _A) , training=_A) _UpperCAmelCase : int = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _UpperCAmelCase : int = self.model_tester.num_stages self.assertEqual(len(_A) , expected_num_stages + 1) # RegNet'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 // 2, self.model_tester.image_size // 2] , ) _UpperCAmelCase , _UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase : Optional[int] = ['''basic''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: _UpperCAmelCase : Optional[Any] = layer_type _UpperCAmelCase : int = True check_hidden_states_output(_A , _A , _A) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase : Any = True check_hidden_states_output(_A , _A , _A) def snake_case__ ( self) -> str: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(_A , _A , _A , _A={}): _UpperCAmelCase : Dict = model(_A , return_dict=_A , **_A) _UpperCAmelCase : Optional[Any] = model(_A , return_dict=_A , **_A).to_tuple() def recursive_check(_A , _A): if isinstance(_A , (List, Tuple)): for tuple_iterable_value, dict_iterable_value in zip(_A , _A): recursive_check(_A , _A) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(_A , _A)) , msg=( '''Tuple and dict output are not equal. Difference:''' f''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}''' ) , ) recursive_check(_A , _A) for model_class in self.all_model_classes: _UpperCAmelCase : str = model_class(_A) _UpperCAmelCase : Any = self._prepare_for_class(_A , _A) _UpperCAmelCase : Tuple = self._prepare_for_class(_A , _A) check_equivalence(_A , _A , _A) _UpperCAmelCase : str = self._prepare_for_class(_A , _A , return_labels=_A) _UpperCAmelCase : Tuple = self._prepare_for_class(_A , _A , return_labels=_A) check_equivalence(_A , _A , _A) _UpperCAmelCase : Union[str, Any] = self._prepare_for_class(_A , _A) _UpperCAmelCase : Tuple = self._prepare_for_class(_A , _A) check_equivalence(_A , _A , _A , {'''output_hidden_states''': True}) _UpperCAmelCase : Union[str, Any] = self._prepare_for_class(_A , _A , return_labels=_A) _UpperCAmelCase : List[str] = self._prepare_for_class(_A , _A , return_labels=_A) check_equivalence(_A , _A , _A , {'''output_hidden_states''': True}) def snake_case__ ( self) -> Optional[Any]: """simple docstring""" _UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A) @slow def snake_case__ ( self) -> Any: """simple docstring""" for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase : Dict = TFRegNetModel.from_pretrained(_A) self.assertIsNotNone(_A) def _lowerCamelCase ( ) -> Dict: _UpperCAmelCase : Optional[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def snake_case__ ( self) -> Tuple: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def snake_case__ ( self) -> str: """simple docstring""" _UpperCAmelCase : int = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) _UpperCAmelCase : Union[str, Any] = self.default_image_processor _UpperCAmelCase : List[Any] = prepare_img() _UpperCAmelCase : Optional[int] = image_processor(images=_A , return_tensors='''tf''') # forward pass _UpperCAmelCase : int = model(**_A , training=_A) # verify the logits _UpperCAmelCase : List[Any] = tf.TensorShape((1, 1000)) self.assertEqual(outputs.logits.shape , _A) _UpperCAmelCase : Dict = tf.constant([-0.4180, -1.5051, -3.4836]) tf.debugging.assert_near(outputs.logits[0, :3] , _A , atol=1e-4)
186
from __future__ import annotations def _lowerCamelCase ( __A : int ) -> list[int]: _UpperCAmelCase : List[str] = [True] * limit _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Dict = False _UpperCAmelCase : List[str] = True for i in range(3 , int(limit**0.5 + 1 ) , 2 ): _UpperCAmelCase : List[str] = i * 2 while index < limit: _UpperCAmelCase : Union[str, Any] = False _UpperCAmelCase : int = index + i _UpperCAmelCase : Optional[int] = [2] for i in range(3 , __A , 2 ): if is_prime[i]: primes.append(__A ) return primes def _lowerCamelCase ( __A : int = 1_000_000 ) -> int: _UpperCAmelCase : Any = prime_sieve(__A ) _UpperCAmelCase : Optional[Any] = 0 _UpperCAmelCase : Tuple = 0 for i in range(len(__A ) ): for j in range(i + length , len(__A ) ): _UpperCAmelCase : List[Any] = sum(primes[i:j] ) if sol >= ceiling: break if sol in primes: _UpperCAmelCase : List[str] = j - i _UpperCAmelCase : Optional[Any] = sol return largest if __name__ == "__main__": print(F'{solution() = }')
186
1
import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: a = None a = logging.get_logger(__name__) a = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} a = { "vocab_file": { "t5-small": "https://huggingface.co/t5-small/resolve/main/spiece.model", "t5-base": "https://huggingface.co/t5-base/resolve/main/spiece.model", "t5-large": "https://huggingface.co/t5-large/resolve/main/spiece.model", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/spiece.model", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/spiece.model", }, "tokenizer_file": { "t5-small": "https://huggingface.co/t5-small/resolve/main/tokenizer.json", "t5-base": "https://huggingface.co/t5-base/resolve/main/tokenizer.json", "t5-large": "https://huggingface.co/t5-large/resolve/main/tokenizer.json", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/tokenizer.json", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/tokenizer.json", }, } # TODO(PVP) - this should be removed in Transformers v5 a = { "t5-small": 512, "t5-base": 512, "t5-large": 512, "t5-3b": 512, "t5-11b": 512, } class _A ( __lowercase ): __a = VOCAB_FILES_NAMES __a = PRETRAINED_VOCAB_FILES_MAP __a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a = ["""input_ids""", """attention_mask"""] __a = TaTokenizer __a = [] def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="</s>" , _SCREAMING_SNAKE_CASE="<unk>" , _SCREAMING_SNAKE_CASE="<pad>" , _SCREAMING_SNAKE_CASE=100 , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: _UpperCAmelCase = [F"<extra_id_{i}>" for i in range(_SCREAMING_SNAKE_CASE )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens _UpperCAmelCase = len(set(filter(lambda _SCREAMING_SNAKE_CASE : bool("""extra_id_""" in str(_SCREAMING_SNAKE_CASE ) ) , _SCREAMING_SNAKE_CASE ) ) ) if extra_tokens != extra_ids: raise ValueError( F"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are" """ provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids""" """ tokens""" ) super().__init__( _SCREAMING_SNAKE_CASE , tokenizer_file=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , extra_ids=_SCREAMING_SNAKE_CASE , additional_special_tokens=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = vocab_file _UpperCAmelCase = False if not self.vocab_file else True _UpperCAmelCase = extra_ids @staticmethod def UpperCAmelCase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: _UpperCAmelCase = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( """This tokenizer was incorrectly instantiated with a model max length of""" F" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this" """ behavior is kept to avoid breaking backwards compatibility when padding/encoding with""" """ `truncation is True`.\n- Be aware that you SHOULD NOT rely on""" F" {pretrained_model_name_or_path} automatically truncating your input to" F" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences" F" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with" """ `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please""" """ instantiate this tokenizer with `model_max_length` set to your preferred value.""" , _SCREAMING_SNAKE_CASE , ) return max_model_length def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ): if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return _UpperCAmelCase = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) logger.info(F"Copy vocab file to {out_vocab_file}" ) return (out_vocab_file,) def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ): _UpperCAmelCase = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: _UpperCAmelCase = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ): _UpperCAmelCase = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def UpperCAmelCase ( self ): return list( set(filter(lambda _SCREAMING_SNAKE_CASE : bool(re.search(r"""<extra_id_\d+>""" , _SCREAMING_SNAKE_CASE ) ) is not None , self.additional_special_tokens ) ) ) def UpperCAmelCase ( self ): return [self.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) for token in self.get_sentinel_tokens()]
518
import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP a = False try: a = _is_package_available("google.colab") except ModuleNotFoundError: pass @input.register class _A : def __init__( self , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = [] ): _UpperCAmelCase = 0 _UpperCAmelCase = choices _UpperCAmelCase = prompt if sys.platform == "win32": _UpperCAmelCase = """*""" else: _UpperCAmelCase = """➔ """ def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , _SCREAMING_SNAKE_CASE ) else: forceWrite(self.choices[index] , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ): if index == self.position: forceWrite(F" {self.arrow_char} " ) self.write_choice(_SCREAMING_SNAKE_CASE ) else: forceWrite(F" {self.choices[index]}" ) reset_cursor() def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 1 ): _UpperCAmelCase = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(_SCREAMING_SNAKE_CASE ) move_cursor(_SCREAMING_SNAKE_CASE , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP["""up"""] ) def UpperCAmelCase ( self ): self.move_direction(Direction.UP ) @input.mark(KEYMAP["""down"""] ) def UpperCAmelCase ( self ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["""newline"""] ) def UpperCAmelCase ( self ): move_cursor(len(self.choices ) - self.position , """DOWN""" ) return self.position @input.mark(KEYMAP["""interrupt"""] ) def UpperCAmelCase ( self ): move_cursor(len(self.choices ) - self.position , """DOWN""" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(_SCREAMING_SNAKE_CASE )] for number in range(10 )] ) def UpperCAmelCase ( self ): _UpperCAmelCase = int(chr(self.current_selection ) ) _UpperCAmelCase = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , _SCREAMING_SNAKE_CASE ) else: return else: return def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , """\n""" ) if in_colab: forceWrite("""Please input a choice index (starting from 0), and press enter""" , """\n""" ) else: forceWrite("""Please select a choice using the arrow or number keys, and selecting with enter""" , """\n""" ) _UpperCAmelCase = default_choice for i in range(len(self.choices ) ): self.print_choice(_SCREAMING_SNAKE_CASE ) forceWrite("""\n""" ) move_cursor(len(self.choices ) - self.position , """UP""" ) with cursor.hide(): while True: if in_colab: try: _UpperCAmelCase = int(builtins.input() ) except ValueError: _UpperCAmelCase = default_choice else: _UpperCAmelCase = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , """UP""" ) clear_line() self.write_choice(_SCREAMING_SNAKE_CASE , """\n""" ) return choice
518
1
"""simple docstring""" import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE ): """simple docstring""" _A : str = (UniPCMultistepScheduler,) _A : Any = (("""num_inference_steps""", 25),) def lowerCamelCase(self , **lowerCAmelCase_ ): A_ : Tuple = { """num_train_timesteps""": 1000, """beta_start""": 0.0001, """beta_end""": 0.02, """beta_schedule""": """linear""", """solver_order""": 2, """solver_type""": """bh2""", } config.update(**lowerCAmelCase_ ) return config def lowerCamelCase(self , lowerCAmelCase_=0 , **lowerCAmelCase_ ): A_ : Dict = dict(self.forward_default_kwargs ) A_ : int = kwargs.pop("""num_inference_steps""" , lowerCAmelCase_ ) A_ : Tuple = self.dummy_sample A_ : Optional[Any] = 0.1 * sample A_ : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A_ : Any = self.get_scheduler_config(**lowerCAmelCase_ ) A_ : Optional[Any] = scheduler_class(**lowerCAmelCase_ ) scheduler.set_timesteps(lowerCAmelCase_ ) # copy over dummy past residuals A_ : str = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowerCAmelCase_ ) A_ : List[Any] = scheduler_class.from_pretrained(lowerCAmelCase_ ) new_scheduler.set_timesteps(lowerCAmelCase_ ) # copy over dummy past residuals A_ : Union[str, Any] = dummy_past_residuals[: new_scheduler.config.solver_order] A_ , A_ : Union[str, Any] = sample, sample for t in range(lowerCAmelCase_ , time_step + scheduler.config.solver_order + 1 ): A_ : Any = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample A_ : List[Any] = new_scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def lowerCamelCase(self , lowerCAmelCase_=0 , **lowerCAmelCase_ ): A_ : Union[str, Any] = dict(self.forward_default_kwargs ) A_ : int = kwargs.pop("""num_inference_steps""" , lowerCAmelCase_ ) A_ : Any = self.dummy_sample A_ : int = 0.1 * sample A_ : Tuple = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A_ : Tuple = self.get_scheduler_config() A_ : List[str] = scheduler_class(**lowerCAmelCase_ ) scheduler.set_timesteps(lowerCAmelCase_ ) # copy over dummy past residuals (must be after setting timesteps) A_ : Any = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowerCAmelCase_ ) A_ : Any = scheduler_class.from_pretrained(lowerCAmelCase_ ) # copy over dummy past residuals new_scheduler.set_timesteps(lowerCAmelCase_ ) # copy over dummy past residual (must be after setting timesteps) A_ : Optional[Any] = dummy_past_residuals[: new_scheduler.config.solver_order] A_ : Tuple = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample A_ : List[Any] = new_scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def lowerCamelCase(self , lowerCAmelCase_=None , **lowerCAmelCase_ ): if scheduler is None: A_ : Any = self.scheduler_classes[0] A_ : Dict = self.get_scheduler_config(**lowerCAmelCase_ ) A_ : List[Any] = scheduler_class(**lowerCAmelCase_ ) A_ : Any = self.scheduler_classes[0] A_ : Any = self.get_scheduler_config(**lowerCAmelCase_ ) A_ : Any = scheduler_class(**lowerCAmelCase_ ) A_ : int = 10 A_ : Tuple = self.dummy_model() A_ : Tuple = self.dummy_sample_deter scheduler.set_timesteps(lowerCAmelCase_ ) for i, t in enumerate(scheduler.timesteps ): A_ : List[str] = model(lowerCAmelCase_ , lowerCAmelCase_ ) A_ : Optional[int] = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ).prev_sample return sample def lowerCamelCase(self ): A_ : Any = dict(self.forward_default_kwargs ) A_ : Dict = kwargs.pop("""num_inference_steps""" , lowerCAmelCase_ ) for scheduler_class in self.scheduler_classes: A_ : int = self.get_scheduler_config() A_ : Dict = scheduler_class(**lowerCAmelCase_ ) A_ : Dict = self.dummy_sample A_ : Dict = 0.1 * sample if num_inference_steps is not None and hasattr(lowerCAmelCase_ , """set_timesteps""" ): scheduler.set_timesteps(lowerCAmelCase_ ) elif num_inference_steps is not None and not hasattr(lowerCAmelCase_ , """set_timesteps""" ): A_ : Tuple = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) A_ : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10] A_ : int = dummy_past_residuals[: scheduler.config.solver_order] A_ : str = scheduler.timesteps[5] A_ : List[Any] = scheduler.timesteps[6] A_ : List[Any] = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample A_ : Dict = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def lowerCamelCase(self ): # make sure that iterating over schedulers with same config names gives same results # for defaults A_ : Optional[Any] = UniPCMultistepScheduler(**self.get_scheduler_config() ) A_ : List[str] = self.full_loop(scheduler=lowerCAmelCase_ ) A_ : Tuple = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_mean.item() - 0.2464 ) < 1e-3 A_ : Dict = DPMSolverSinglestepScheduler.from_config(scheduler.config ) A_ : Dict = DEISMultistepScheduler.from_config(scheduler.config ) A_ : List[str] = DPMSolverMultistepScheduler.from_config(scheduler.config ) A_ : Dict = UniPCMultistepScheduler.from_config(scheduler.config ) A_ : Union[str, Any] = self.full_loop(scheduler=lowerCAmelCase_ ) A_ : Optional[int] = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_mean.item() - 0.2464 ) < 1e-3 def lowerCamelCase(self ): for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=lowerCAmelCase_ ) def lowerCamelCase(self ): self.check_over_configs(thresholding=lowerCAmelCase_ ) for order in [1, 2, 3]: for solver_type in ["bh1", "bh2"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=lowerCAmelCase_ , prediction_type=lowerCAmelCase_ , sample_max_value=lowerCAmelCase_ , solver_order=lowerCAmelCase_ , solver_type=lowerCAmelCase_ , ) def lowerCamelCase(self ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowerCAmelCase_ ) def lowerCamelCase(self ): for solver_type in ["bh1", "bh2"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=lowerCAmelCase_ , solver_type=lowerCAmelCase_ , prediction_type=lowerCAmelCase_ , ) A_ : Optional[Any] = self.full_loop( solver_order=lowerCAmelCase_ , solver_type=lowerCAmelCase_ , prediction_type=lowerCAmelCase_ , ) assert not torch.isnan(lowerCAmelCase_ ).any(), "Samples have nan numbers" def lowerCamelCase(self ): self.check_over_configs(lower_order_final=lowerCAmelCase_ ) self.check_over_configs(lower_order_final=lowerCAmelCase_ ) def lowerCamelCase(self ): for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=lowerCAmelCase_ , time_step=0 ) def lowerCamelCase(self ): A_ : str = self.full_loop() A_ : Optional[Any] = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_mean.item() - 0.2464 ) < 1e-3 def lowerCamelCase(self ): A_ : Union[str, Any] = self.full_loop(prediction_type="""v_prediction""" ) A_ : Tuple = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_mean.item() - 0.1014 ) < 1e-3 def lowerCamelCase(self ): A_ : Dict = self.scheduler_classes[0] A_ : Tuple = self.get_scheduler_config(thresholding=lowerCAmelCase_ , dynamic_thresholding_ratio=0 ) A_ : List[str] = scheduler_class(**lowerCAmelCase_ ) A_ : Any = 10 A_ : str = self.dummy_model() A_ : Any = self.dummy_sample_deter.half() scheduler.set_timesteps(lowerCAmelCase_ ) for i, t in enumerate(scheduler.timesteps ): A_ : Any = model(lowerCAmelCase_ , lowerCAmelCase_ ) A_ : Union[str, Any] = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ).prev_sample assert sample.dtype == torch.floataa def lowerCamelCase(self , **lowerCAmelCase_ ): for scheduler_class in self.scheduler_classes: A_ : List[Any] = self.get_scheduler_config(**lowerCAmelCase_ ) A_ : Union[str, Any] = scheduler_class(**lowerCAmelCase_ ) scheduler.set_timesteps(scheduler.config.num_train_timesteps ) assert len(scheduler.timesteps.unique() ) == scheduler.num_inference_steps
480
"""simple docstring""" _lowerCAmelCase = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []} _lowerCAmelCase = ["a", "b", "c", "d", "e"] def __UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ ): A_ : int = start # add current to visited visited.append(snake_case__ ) A_ : Any = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: A_ : Optional[Any] = topological_sort(snake_case__ , snake_case__ , snake_case__ ) # if all neighbors visited add current to sort sort.append(snake_case__ ) # if all vertices haven't been visited select a new one to visit if len(snake_case__ ) != len(snake_case__ ): for vertice in vertices: if vertice not in visited: A_ : Optional[Any] = topological_sort(snake_case__ , snake_case__ , snake_case__ ) # return sort return sort if __name__ == "__main__": _lowerCAmelCase = topological_sort("a", [], []) print(sort)
480
1
import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor if is_flax_available(): import jax from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class lowercase_ (unittest.TestCase ): def __init__( self , lowercase_ , lowercase_=100 , lowercase_=13 , lowercase_=30 , lowercase_=2 , lowercase_=3 , lowercase_=True , lowercase_=True , lowercase_=32 , lowercase_=5 , lowercase_=4 , lowercase_=37 , lowercase_="gelu" , lowercase_=0.1 , lowercase_=0.1 , lowercase_=10 , lowercase_=0.02 , lowercase_=3 , ) -> Dict: a__ =parent a__ =vocab_size a__ =batch_size a__ =image_size a__ =patch_size a__ =num_channels a__ =is_training a__ =use_labels a__ =hidden_size a__ =num_hidden_layers a__ =num_attention_heads a__ =intermediate_size a__ =hidden_act a__ =hidden_dropout_prob a__ =attention_probs_dropout_prob a__ =type_sequence_label_size a__ =initializer_range # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) a__ =(image_size // patch_size) ** 2 a__ =num_patches + 1 def __UpperCamelCase ( self) -> Dict: a__ =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) a__ =None if self.use_labels: a__ =ids_tensor([self.batch_size] , self.type_sequence_label_size) a__ =BeitConfig( vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowercase_ , initializer_range=self.initializer_range , ) return config, pixel_values, labels def __UpperCamelCase ( self , lowercase_ , lowercase_ , lowercase_) -> List[Any]: a__ =FlaxBeitModel(config=lowercase_) a__ =model(lowercase_) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def __UpperCamelCase ( self , lowercase_ , lowercase_ , lowercase_) -> Any: a__ =FlaxBeitForMaskedImageModeling(config=lowercase_) a__ =model(lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size)) def __UpperCamelCase ( self , lowercase_ , lowercase_ , lowercase_) -> List[str]: a__ =self.type_sequence_label_size a__ =FlaxBeitForImageClassification(config=lowercase_) a__ =model(lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) # test greyscale images a__ =1 a__ =FlaxBeitForImageClassification(lowercase_) a__ =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) a__ =model(lowercase_) def __UpperCamelCase ( self) -> Dict: a__ =self.prepare_config_and_inputs() ( ( a__ ) , ( a__ ) , ( a__ ) , ) =config_and_inputs a__ ={'pixel_values': pixel_values} return config, inputs_dict @require_flax class lowercase_ (lowercase__ , unittest.TestCase ): snake_case =( (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else () ) def __UpperCamelCase ( self) -> None: a__ =FlaxBeitModelTester(self) a__ =ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37) def __UpperCamelCase ( self) -> Union[str, Any]: self.config_tester.run_common_tests() def __UpperCamelCase ( self) -> Dict: a__ , a__ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ =model_class(lowercase_) a__ =inspect.signature(model.__call__) # signature.parameters is an OrderedDict => so arg_names order is deterministic a__ =[*signature.parameters.keys()] a__ =['pixel_values'] self.assertListEqual(arg_names[:1] , lowercase_) def __UpperCamelCase ( self) -> int: a__ , a__ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__): a__ =self._prepare_for_class(lowercase_ , lowercase_) a__ =model_class(lowercase_) @jax.jit def model_jitted(lowercase_ , **lowercase_): return model(pixel_values=lowercase_ , **lowercase_) with self.subTest('JIT Enabled'): a__ =model_jitted(**lowercase_).to_tuple() with self.subTest('JIT Disabled'): with jax.disable_jit(): a__ =model_jitted(**lowercase_).to_tuple() self.assertEqual(len(lowercase_) , len(lowercase_)) for jitted_output, output in zip(lowercase_ , lowercase_): self.assertEqual(jitted_output.shape , output.shape) def __UpperCamelCase ( self) -> int: a__ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def __UpperCamelCase ( self) -> Optional[Any]: a__ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowercase_) def __UpperCamelCase ( self) -> Any: a__ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) @slow def __UpperCamelCase ( self) -> Union[str, Any]: for model_class_name in self.all_model_classes: a__ =model_class_name.from_pretrained('microsoft/beit-base-patch16-224') a__ =model(np.ones((1, 3, 224, 224))) self.assertIsNotNone(lowercase_) def _lowercase( ): a__ =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @require_flax class lowercase_ (unittest.TestCase ): @cached_property def __UpperCamelCase ( self) -> List[Any]: return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224') if is_vision_available() else None @slow def __UpperCamelCase ( self) -> Dict: a__ =FlaxBeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k') a__ =self.default_image_processor a__ =prepare_img() a__ =image_processor(images=lowercase_ , return_tensors='np').pixel_values # prepare bool_masked_pos a__ =np.ones((1, 196) , dtype=lowercase_) # forward pass a__ =model(pixel_values=lowercase_ , bool_masked_pos=lowercase_) a__ =outputs.logits # verify the logits a__ =(1, 196, 8192) self.assertEqual(logits.shape , lowercase_) a__ =np.array( [[-3.24_37, 0.50_72, -13.91_74], [-3.24_56, 0.49_48, -13.94_01], [-3.20_33, 0.51_21, -13.85_50]]) self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3] , lowercase_ , atol=1e-2)) @slow def __UpperCamelCase ( self) -> List[Any]: a__ =FlaxBeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224') a__ =self.default_image_processor a__ =prepare_img() a__ =image_processor(images=lowercase_ , return_tensors='np') # forward pass a__ =model(**lowercase_) a__ =outputs.logits # verify the logits a__ =(1, 1000) self.assertEqual(logits.shape , lowercase_) a__ =np.array([-1.23_85, -1.09_87, -1.01_08]) self.assertTrue(np.allclose(logits[0, :3] , lowercase_ , atol=1e-4)) a__ =281 self.assertEqual(logits.argmax(-1).item() , lowercase_) @slow def __UpperCamelCase ( self) -> Union[str, Any]: a__ =FlaxBeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k') a__ =self.default_image_processor a__ =prepare_img() a__ =image_processor(images=lowercase_ , return_tensors='np') # forward pass a__ =model(**lowercase_) a__ =outputs.logits # verify the logits a__ =(1, 21841) self.assertEqual(logits.shape , lowercase_) a__ =np.array([1.68_81, -0.27_87, 0.59_01]) self.assertTrue(np.allclose(logits[0, :3] , lowercase_ , atol=1e-4)) a__ =2396 self.assertEqual(logits.argmax(-1).item() , lowercase_)
20
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class SCREAMING_SNAKE_CASE__ : @staticmethod def A__ ( *__lowerCamelCase : List[str] , **__lowerCamelCase : Optional[int] ): """simple docstring""" pass def a_ ( __lowerCAmelCase ): lowerCAmelCase__ = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def a_ ( __lowerCAmelCase ): lowerCAmelCase__ = np.array(__lowerCAmelCase ) lowerCAmelCase__ = npimg.shape return {"hash": hashimage(__lowerCAmelCase ), "shape": shape} @is_pipeline_test @require_vision @require_torch class SCREAMING_SNAKE_CASE__ (unittest.TestCase ): lowercase_ : Any = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) lowercase_ : str = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def A__ ( self : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : int ): """simple docstring""" lowerCAmelCase__ = MaskGenerationPipeline(model=__lowerCamelCase , image_processor=__lowerCamelCase ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def A__ ( self : Optional[int] , __lowerCamelCase : Dict , __lowerCamelCase : Optional[int] ): """simple docstring""" pass @require_tf @unittest.skip('''Image segmentation not implemented in TF''' ) def A__ ( self : Dict ): """simple docstring""" pass @slow @require_torch def A__ ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = pipeline('''mask-generation''' , model='''facebook/sam-vit-huge''' ) lowerCAmelCase__ = image_segmenter('''http://images.cocodataset.org/val2017/000000039769.jpg''' , points_per_batch=2_56 ) # Shortening by hashing lowerCAmelCase__ = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(__lowerCamelCase ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (4_80, 6_40)}, '''scores''': 1.021}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0053}, {'''mask''': {'''hash''': '''e2d0b7a0b7''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9967}, {'''mask''': {'''hash''': '''453c7844bd''', '''shape''': (4_80, 6_40)}, '''scores''': 0.993}, {'''mask''': {'''hash''': '''3d44f2926d''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9909}, {'''mask''': {'''hash''': '''64033ddc3f''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9879}, {'''mask''': {'''hash''': '''801064ff79''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9834}, {'''mask''': {'''hash''': '''6172f276ef''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9716}, {'''mask''': {'''hash''': '''b49e60e084''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9612}, {'''mask''': {'''hash''': '''a811e775fd''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9599}, {'''mask''': {'''hash''': '''a6a8ebcf4b''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9552}, {'''mask''': {'''hash''': '''9d8257e080''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9532}, {'''mask''': {'''hash''': '''32de6454a8''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9516}, {'''mask''': {'''hash''': '''af3d4af2c8''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9499}, {'''mask''': {'''hash''': '''3c6db475fb''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9483}, {'''mask''': {'''hash''': '''c290813fb9''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9464}, {'''mask''': {'''hash''': '''b6f0b8f606''', '''shape''': (4_80, 6_40)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''92ce16bfdf''', '''shape''': (4_80, 6_40)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''c749b25868''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9408}, {'''mask''': {'''hash''': '''efb6cab859''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9335}, {'''mask''': {'''hash''': '''1ff2eafb30''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9326}, {'''mask''': {'''hash''': '''788b798e24''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9262}, {'''mask''': {'''hash''': '''abea804f0e''', '''shape''': (4_80, 6_40)}, '''scores''': 0.8999}, {'''mask''': {'''hash''': '''7b9e8ddb73''', '''shape''': (4_80, 6_40)}, '''scores''': 0.8986}, {'''mask''': {'''hash''': '''cd24047c8a''', '''shape''': (4_80, 6_40)}, '''scores''': 0.8984}, {'''mask''': {'''hash''': '''6943e6bcbd''', '''shape''': (4_80, 6_40)}, '''scores''': 0.8873}, {'''mask''': {'''hash''': '''b5f47c9191''', '''shape''': (4_80, 6_40)}, '''scores''': 0.8871} ] , ) # fmt: on @require_torch @slow def A__ ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = '''facebook/sam-vit-huge''' lowerCAmelCase__ = pipeline('''mask-generation''' , model=__lowerCamelCase ) lowerCAmelCase__ = image_segmenter( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , pred_iou_thresh=1 , points_per_batch=2_56 ) # Shortening by hashing lowerCAmelCase__ = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(__lowerCamelCase ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(__lowerCamelCase , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0210}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0053}, ] , )
615
0
'''simple docstring''' 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 __snake_case : def __init__( self, A = "cpu", A = "openai/clip-vit-large-patch14" ): """simple docstring""" lowerCamelCase : Dict = device lowerCamelCase : Any = CLIPTokenizerFast.from_pretrained(A ) lowerCamelCase : Union[str, Any] = [0.4814_5466, 0.457_8275, 0.4082_1073] lowerCamelCase : int = [0.2686_2954, 0.2613_0258, 0.2757_7711] lowerCamelCase : Optional[int] = torchvision.transforms.Normalize(self.image_mean, self.image_std ) lowerCamelCase : str = torchvision.transforms.Resize(224 ) lowerCamelCase : Union[str, Any] = torchvision.transforms.CenterCrop(224 ) def UpperCAmelCase_ ( self, A ): """simple docstring""" lowerCamelCase : str = self.resize(A ) lowerCamelCase : List[str] = self.center_crop(A ) lowerCamelCase : List[str] = self.normalize(A ) return images def __call__( self, A=None, A=None, **A ): """simple docstring""" lowerCamelCase : List[str] = self.tokenizer(text=A, **A ) lowerCamelCase : List[str] = self.preprocess_img(A ) lowerCamelCase : Any = {key: value.to(self.device ) for (key, value) in encoding.items()} return encoding class __snake_case ( 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, ): """simple docstring""" super().__init__() lowerCamelCase : List[str] = None lowerCamelCase : str = device if device else get_device() if vqgan: lowerCamelCase : Optional[Any] = vqgan else: lowerCamelCase : str = load_vqgan(self.device, conf_path=A, ckpt_path=A ) self.vqgan.eval() if clip: lowerCamelCase : Dict = clip else: lowerCamelCase : str = CLIPModel.from_pretrained('openai/clip-vit-base-patch32' ) self.clip.to(self.device ) lowerCamelCase : Union[str, Any] = ProcessorGradientFlow(device=self.device ) lowerCamelCase : Any = iterations lowerCamelCase : List[str] = lr lowerCamelCase : int = log lowerCamelCase : Optional[int] = make_grid lowerCamelCase : Optional[Any] = return_val lowerCamelCase : str = quantize lowerCamelCase : int = self.vqgan.decoder.z_shape def UpperCAmelCase_ ( self, A=None, A=None, A=5, A=True ): """simple docstring""" lowerCamelCase : List[Any] = [] if output_path is None: lowerCamelCase : Optional[Any] = './animation.gif' if input_path is None: lowerCamelCase : Tuple = self.save_path lowerCamelCase : Tuple = 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?)' ) lowerCamelCase : int = total_duration / len(A ) lowerCamelCase : str = [frame_duration] * len(A ) if extend_frames: lowerCamelCase : Optional[Any] = 1.5 lowerCamelCase : Union[str, Any] = 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 UpperCAmelCase_ ( self, A=None, A=None ): """simple docstring""" if not (path or img): raise ValueError('Input either path or tensor' ) if img is not None: raise NotImplementedError lowerCamelCase : Tuple = preprocess(Image.open(A ), target_image_size=256 ).to(self.device ) lowerCamelCase : int = preprocess_vqgan(A ) lowerCamelCase : Optional[int] = self.vqgan.encode(A ) return z def UpperCAmelCase_ ( self, A ): """simple docstring""" lowerCamelCase : str = self.latent.detach().requires_grad_() lowerCamelCase : int = base_latent + transform_vector if self.quantize: lowerCamelCase : int = self.vqgan.quantize(A ) else: lowerCamelCase : int = trans_latent return self.vqgan.decode(A ) def UpperCAmelCase_ ( self, A, A, A=None ): """simple docstring""" lowerCamelCase : Any = self.clip_preprocessor(text=A, images=A, return_tensors='pt', padding=A ) lowerCamelCase : Dict = self.clip(**A ) lowerCamelCase : Optional[int] = clip_outputs.logits_per_image if weights is not None: lowerCamelCase : int = similarity_logits * weights return similarity_logits.sum() def UpperCAmelCase_ ( self, A, A, A ): """simple docstring""" lowerCamelCase : Optional[int] = self._get_clip_similarity(pos_prompts['prompts'], A, weights=(1 / pos_prompts['weights']) ) if neg_prompts: lowerCamelCase : List[Any] = self._get_clip_similarity(neg_prompts['prompts'], A, weights=neg_prompts['weights'] ) else: lowerCamelCase : Optional[Any] = torch.tensor([1], device=self.device ) lowerCamelCase : int = -torch.log(A ) + torch.log(A ) return loss def UpperCAmelCase_ ( self, A, A, A ): """simple docstring""" lowerCamelCase : Optional[Any] = torch.randn_like(self.latent, requires_grad=A, device=self.device ) lowerCamelCase : Tuple = torch.optim.Adam([vector], lr=self.lr ) for i in range(self.iterations ): optim.zero_grad() lowerCamelCase : int = self._add_vector(A ) lowerCamelCase : List[Any] = loop_post_process(A ) lowerCamelCase : Any = 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 UpperCAmelCase_ ( self, A, A, A ): """simple docstring""" 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: lowerCamelCase : List[str] = Image.open(A ) lowerCamelCase : str = image.resize((256, 256) ) wandb.log('Original Image', wandb.Image(A ) ) def UpperCAmelCase_ ( self, A ): """simple docstring""" if not prompts: return [] lowerCamelCase : str = [] lowerCamelCase : Union[str, Any] = [] if isinstance(A, A ): lowerCamelCase : Optional[Any] = [prompt.strip() for prompt in prompts.split('|' )] for prompt in prompts: if isinstance(A, (tuple, list) ): lowerCamelCase : Optional[Any] = prompt[0] lowerCamelCase : Any = float(prompt[1] ) elif ":" in prompt: lowerCamelCase : str = prompt.split(':' ) lowerCamelCase : Any = float(A ) else: lowerCamelCase : Optional[Any] = prompt lowerCamelCase : List[Any] = 1.0 processed_prompts.append(A ) weights.append(A ) return { "prompts": processed_prompts, "weights": torch.tensor(A, device=self.device ), } def UpperCAmelCase_ ( self, A, A=None, A=None, A=True, A=False, A=True, A=True, A=None, ): """simple docstring""" if image_path: lowerCamelCase : Dict = self._get_latent(A ) else: lowerCamelCase : List[str] = 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." lowerCamelCase : str = self.process_prompts(A ) lowerCamelCase : Optional[int] = self.process_prompts(A ) if save_final and save_path is None: lowerCamelCase : Dict = os.path.join('./outputs/', '_'.join(pos_prompts['prompts'] ) ) if not os.path.exists(A ): os.makedirs(A ) else: lowerCamelCase : List[Any] = save_path + '_' + get_timestamp() os.makedirs(A ) lowerCamelCase : List[Any] = save_path lowerCamelCase : Tuple = self.vqgan.decode(self.latent )[0] if show_intermediate: print('Original Image' ) show_pil(custom_to_pil(A ) ) lowerCamelCase : Optional[Any] = 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''' ) )
713
'''simple docstring''' from manim import * class __snake_case ( a__): def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : Optional[int] = Rectangle(height=0.5, width=0.5 ) lowerCamelCase : List[Any] = Rectangle(height=0.46, width=0.46 ).set_stroke(width=0 ) lowerCamelCase : List[str] = [mem.copy() for i in range(6 )] lowerCamelCase : List[Any] = [mem.copy() for i in range(6 )] lowerCamelCase : str = VGroup(*A ).arrange(A, buff=0 ) lowerCamelCase : Any = VGroup(*A ).arrange(A, buff=0 ) lowerCamelCase : Dict = VGroup(A, A ).arrange(A, buff=0 ) lowerCamelCase : str = Text('CPU', font_size=24 ) lowerCamelCase : int = Group(A, A ).arrange(A, buff=0.5, aligned_edge=A ) cpu.move_to([-2.5, -0.5, 0] ) self.add(A ) lowerCamelCase : Optional[int] = [mem.copy() for i in range(1 )] lowerCamelCase : Union[str, Any] = VGroup(*A ).arrange(A, buff=0 ) lowerCamelCase : Optional[Any] = Text('GPU', font_size=24 ) lowerCamelCase : Tuple = Group(A, A ).arrange(A, buff=0.5, aligned_edge=A ) gpu.align_to(A, A ) gpu.set_x(gpu.get_x() - 1 ) self.add(A ) lowerCamelCase : Optional[int] = [mem.copy() for i in range(6 )] lowerCamelCase : Optional[Any] = VGroup(*A ).arrange(A, buff=0 ) lowerCamelCase : Any = Text('Model', font_size=24 ) lowerCamelCase : Tuple = Group(A, A ).arrange(A, buff=0.5, aligned_edge=A ) model.move_to([3, -1.0, 0] ) self.play( Create(A, run_time=1 ), Create(A, run_time=1 ), Create(A, run_time=1 ), ) lowerCamelCase : str = MarkupText( F'''First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.''', font_size=24, ) lowerCamelCase : Any = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) lowerCamelCase : Tuple = MarkupText( F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''', font_size=18, ) key_text.move_to([-5, 2.4, 0] ) step_a.move_to([2, 2, 0] ) self.play(Write(A, run_time=2.5 ), Write(A ), Write(A ) ) self.add(A ) lowerCamelCase : str = [] lowerCamelCase : Optional[int] = [] lowerCamelCase : Optional[Any] = [] for i, rect in enumerate(A ): lowerCamelCase : List[str] = Rectangle(height=0.46, width=0.46 ).set_stroke(width=0.0 ).set_fill(A, opacity=0.7 ) cpu_target.move_to(A ) cpu_target.generate_target() lowerCamelCase : int = 0.46 / 4 lowerCamelCase : Optional[int] = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ), buff=0.02, direction=A ) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 ) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target, direction=A, buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target, direction=A, buff=0.0 ) cpu_targs.append(A ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(A ) ) second_animations.append(MoveToTarget(A, run_time=1.5 ) ) self.play(*A ) self.play(*A ) self.wait()
449
0
'''simple docstring''' from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging UpperCamelCase_ = logging.get_logger(__name__) def _UpperCAmelCase ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[Any] ) -> List[Any]: try: with open(_lowerCamelCase , """rb""" ) as flax_state_f: _lowerCAmelCase : Dict = from_bytes(_lowerCamelCase , flax_state_f.read() ) except UnpicklingError as e: try: with open(_lowerCamelCase ) as f: if f.read().startswith("""version""" ): raise OSError( """You seem to have cloned a repository without having git-lfs installed. Please""" """ install git-lfs and run `git lfs install` followed by `git lfs pull` in the""" """ folder you cloned.""" ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(f'Unable to convert {model_file} to Flax deserializable object. ' ) return load_flax_weights_in_pytorch_model(_lowerCamelCase , _lowerCamelCase ) def _UpperCAmelCase ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : List[str] ) -> int: try: import torch # noqa: F401 except ImportError: logger.error( """Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see""" """ https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation""" """ instructions.""" ) raise # check if we have bf16 weights _lowerCAmelCase : int = flatten_dict(jax.tree_util.tree_map(lambda _lowerCamelCase : x.dtype == jnp.bfloataa , _lowerCamelCase ) ).values() if any(_lowerCamelCase ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( """Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` """ """before loading those in PyTorch model.""" ) _lowerCAmelCase : List[Any] = jax.tree_util.tree_map( lambda _lowerCamelCase : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , _lowerCamelCase ) _lowerCAmelCase : Union[str, Any] = """""" _lowerCAmelCase : Dict = flatten_dict(_lowerCamelCase , sep=""".""" ) _lowerCAmelCase : int = pt_model.state_dict() # keep track of unexpected & missing keys _lowerCAmelCase : Dict = [] _lowerCAmelCase : int = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): _lowerCAmelCase : Tuple = flax_key_tuple.split(""".""" ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: _lowerCAmelCase : Dict = flax_key_tuple_array[:-1] + ["""weight"""] _lowerCAmelCase : List[str] = jnp.transpose(_lowerCamelCase , (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": _lowerCAmelCase : Any = flax_key_tuple_array[:-1] + ["""weight"""] _lowerCAmelCase : str = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": _lowerCAmelCase : List[Any] = flax_key_tuple_array[:-1] + ["""weight"""] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(_lowerCamelCase ): _lowerCAmelCase : Dict = ( flax_key_tuple_string.replace("""_0""" , """.0""" ) .replace("""_1""" , """.1""" ) .replace("""_2""" , """.2""" ) .replace("""_3""" , """.3""" ) .replace("""_4""" , """.4""" ) .replace("""_5""" , """.5""" ) .replace("""_6""" , """.6""" ) .replace("""_7""" , """.7""" ) .replace("""_8""" , """.8""" ) .replace("""_9""" , """.9""" ) ) _lowerCAmelCase : Tuple = """.""".join(_lowerCamelCase ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ' f'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) else: # add weight to pytorch dict _lowerCAmelCase : List[Any] = np.asarray(_lowerCamelCase ) if not isinstance(_lowerCamelCase , np.ndarray ) else flax_tensor _lowerCAmelCase : Union[str, Any] = torch.from_numpy(_lowerCamelCase ) # remove from missing keys missing_keys.remove(_lowerCamelCase ) else: # weight is not expected by PyTorch model unexpected_keys.append(_lowerCamelCase ) pt_model.load_state_dict(_lowerCamelCase ) # re-transform missing_keys to list _lowerCAmelCase : Optional[int] = list(_lowerCamelCase ) if len(_lowerCamelCase ) > 0: logger.warning( """Some weights of the Flax model were not used when initializing the PyTorch model""" f' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing' f' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture' """ (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This""" f' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect' """ to be exactly identical (e.g. initializing a BertForSequenceClassification model from a""" """ FlaxBertForSequenceClassification model).""" ) if len(_lowerCamelCase ) > 0: logger.warning( f'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly' f' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to' """ use it for predictions and inference.""" ) return pt_model
384
'''simple docstring''' from collections.abc import Sequence def _UpperCAmelCase ( _lowerCamelCase : Sequence[float] , _lowerCamelCase : float ) -> float: return sum(c * (x**i) for i, c in enumerate(_lowerCamelCase ) ) def _UpperCAmelCase ( _lowerCamelCase : Sequence[float] , _lowerCamelCase : float ) -> float: _lowerCAmelCase : List[Any] = 0.0 for coeff in reversed(_lowerCamelCase ): _lowerCAmelCase : Optional[Any] = result * x + coeff return result if __name__ == "__main__": UpperCamelCase_ = (0.0, 0.0, 5.0, 9.3, 7.0) UpperCamelCase_ = 1_0.0 print(evaluate_poly(poly, x)) print(horner(poly, x))
384
1
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 __lowerCamelCase = logging.get_logger(__name__) __lowerCamelCase = { '''facebook/data2vec-vision-base-ft''': ( '''https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json''' ), } class snake_case_ (lowercase__ ): """simple docstring""" _lowerCamelCase = """data2vec-vision""" def __init__( self ,lowercase=768 ,lowercase=12 ,lowercase=12 ,lowercase=3072 ,lowercase="gelu" ,lowercase=0.0 ,lowercase=0.0 ,lowercase=0.02 ,lowercase=1E-12 ,lowercase=224 ,lowercase=16 ,lowercase=3 ,lowercase=False ,lowercase=False ,lowercase=False ,lowercase=False ,lowercase=0.1 ,lowercase=0.1 ,lowercase=True ,lowercase=[3, 5, 7, 11] ,lowercase=[1, 2, 3, 6] ,lowercase=True ,lowercase=0.4 ,lowercase=256 ,lowercase=1 ,lowercase=False ,lowercase=255 ,**lowercase ,): """simple docstring""" super().__init__(**lowercase) UpperCAmelCase_ : Dict = hidden_size UpperCAmelCase_ : Any = num_hidden_layers UpperCAmelCase_ : int = num_attention_heads UpperCAmelCase_ : str = intermediate_size UpperCAmelCase_ : Tuple = hidden_act UpperCAmelCase_ : str = hidden_dropout_prob UpperCAmelCase_ : Union[str, Any] = attention_probs_dropout_prob UpperCAmelCase_ : Any = initializer_range UpperCAmelCase_ : List[str] = layer_norm_eps UpperCAmelCase_ : int = image_size UpperCAmelCase_ : Optional[Any] = patch_size UpperCAmelCase_ : str = num_channels UpperCAmelCase_ : int = use_mask_token UpperCAmelCase_ : Any = use_absolute_position_embeddings UpperCAmelCase_ : str = use_relative_position_bias UpperCAmelCase_ : Union[str, Any] = use_shared_relative_position_bias UpperCAmelCase_ : Optional[Any] = layer_scale_init_value UpperCAmelCase_ : Optional[Any] = drop_path_rate UpperCAmelCase_ : List[Any] = use_mean_pooling # decode head attributes (semantic segmentation) UpperCAmelCase_ : List[Any] = out_indices UpperCAmelCase_ : Dict = pool_scales # auxiliary head attributes (semantic segmentation) UpperCAmelCase_ : List[Any] = use_auxiliary_head UpperCAmelCase_ : str = auxiliary_loss_weight UpperCAmelCase_ : Dict = auxiliary_channels UpperCAmelCase_ : Union[str, Any] = auxiliary_num_convs UpperCAmelCase_ : List[str] = auxiliary_concat_input UpperCAmelCase_ : List[Any] = semantic_loss_ignore_index class snake_case_ (lowercase__ ): """simple docstring""" _lowerCamelCase = version.parse("""1.11""" ) @property def A_ ( self): """simple docstring""" return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ]) @property def A_ ( self): """simple docstring""" return 1E-4
714
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging __lowerCamelCase = logging.get_logger(__name__) __lowerCamelCase = { '''google/umt5-small''': '''https://huggingface.co/google/umt5-small/resolve/main/config.json''', # See all umt5 models at https://huggingface.co/models?filter=umt5 } class snake_case_ (lowercase__ ): """simple docstring""" _lowerCamelCase = """umt5""" _lowerCamelCase = ["""past_key_values"""] def __init__( self ,lowercase=250112 ,lowercase=512 ,lowercase=64 ,lowercase=1024 ,lowercase=8 ,lowercase=None ,lowercase=6 ,lowercase=32 ,lowercase=128 ,lowercase=0.1 ,lowercase=1E-6 ,lowercase=1.0 ,lowercase="gated-gelu" ,lowercase=True ,lowercase=True ,lowercase="T5Tokenizer" ,lowercase=True ,lowercase=0 ,lowercase=1 ,lowercase=0 ,**lowercase ,): """simple docstring""" super().__init__( is_encoder_decoder=lowercase ,tokenizer_class=lowercase ,tie_word_embeddings=lowercase ,pad_token_id=lowercase ,eos_token_id=lowercase ,decoder_start_token_id=lowercase ,**lowercase ,) UpperCAmelCase_ : Optional[int] = vocab_size UpperCAmelCase_ : Any = d_model UpperCAmelCase_ : Any = d_kv UpperCAmelCase_ : int = d_ff UpperCAmelCase_ : Tuple = num_layers UpperCAmelCase_ : int = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry UpperCAmelCase_ : Optional[int] = num_heads UpperCAmelCase_ : str = relative_attention_num_buckets UpperCAmelCase_ : Any = relative_attention_max_distance UpperCAmelCase_ : Optional[Any] = dropout_rate UpperCAmelCase_ : Union[str, Any] = layer_norm_epsilon UpperCAmelCase_ : Optional[Any] = initializer_factor UpperCAmelCase_ : int = feed_forward_proj UpperCAmelCase_ : str = use_cache UpperCAmelCase_ : List[str] = self.feed_forward_proj.split("-") UpperCAmelCase_ : Any = act_info[-1] UpperCAmelCase_ : Optional[int] = act_info[0] == "gated" if len(lowercase) > 1 and act_info[0] != "gated" or len(lowercase) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. " "'gated-gelu' or 'relu'") if feed_forward_proj == "gated-gelu": UpperCAmelCase_ : Tuple = "gelu_new" @property def A_ ( self): """simple docstring""" return self.d_model @property def A_ ( self): """simple docstring""" return self.num_heads @property def A_ ( self): """simple docstring""" return self.num_layers class snake_case_ (lowercase__ ): """simple docstring""" @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def A_ ( self): """simple docstring""" UpperCAmelCase_ : int = { "input_ids": {0: "batch", 1: "encoder_sequence"}, "attention_mask": {0: "batch", 1: "encoder_sequence"}, } if self.use_past: UpperCAmelCase_ : Union[str, Any] = "past_encoder_sequence + sequence" UpperCAmelCase_ : Optional[int] = {0: "batch"} UpperCAmelCase_ : Union[str, Any] = {0: "batch", 1: "past_decoder_sequence + sequence"} else: UpperCAmelCase_ : Optional[int] = {0: "batch", 1: "decoder_sequence"} UpperCAmelCase_ : Dict = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(lowercase ,direction="inputs") return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def A_ ( self): """simple docstring""" return 13 @property def A_ ( self): """simple docstring""" return 5E-4
455
0
from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class _lowerCamelCase( nn.Module ): def __init__( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=0.0, lowerCamelCase = None, lowerCamelCase = "geglu", lowerCamelCase = None, lowerCamelCase = False, lowerCamelCase = False, lowerCamelCase = False, lowerCamelCase = False, lowerCamelCase = True, lowerCamelCase = "layer_norm", lowerCamelCase = False, ) -> Dict: """simple docstring""" super().__init__() _lowercase : Union[str, Any] = only_cross_attention _lowercase : Union[str, Any] = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm_zero' _lowercase : List[str] = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm' if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( F'''`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to''' F''' define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.''') # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: _lowercase : Union[str, Any] = AdaLayerNorm(lowerCamelCase, lowerCamelCase) elif self.use_ada_layer_norm_zero: _lowercase : List[str] = AdaLayerNormZero(lowerCamelCase, lowerCamelCase) else: _lowercase : Tuple = nn.LayerNorm(lowerCamelCase, elementwise_affine=lowerCamelCase) _lowercase : Optional[int] = Attention( query_dim=lowerCamelCase, heads=lowerCamelCase, dim_head=lowerCamelCase, dropout=lowerCamelCase, bias=lowerCamelCase, cross_attention_dim=cross_attention_dim if only_cross_attention else None, upcast_attention=lowerCamelCase, ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. _lowercase : Dict = ( AdaLayerNorm(lowerCamelCase, lowerCamelCase) if self.use_ada_layer_norm else nn.LayerNorm(lowerCamelCase, elementwise_affine=lowerCamelCase) ) _lowercase : str = Attention( query_dim=lowerCamelCase, cross_attention_dim=cross_attention_dim if not double_self_attention else None, heads=lowerCamelCase, dim_head=lowerCamelCase, dropout=lowerCamelCase, bias=lowerCamelCase, upcast_attention=lowerCamelCase, ) # is self-attn if encoder_hidden_states is none else: _lowercase : Optional[int] = None _lowercase : List[Any] = None # 3. Feed-forward _lowercase : Dict = nn.LayerNorm(lowerCamelCase, elementwise_affine=lowerCamelCase) _lowercase : Dict = FeedForward(lowerCamelCase, dropout=lowerCamelCase, activation_fn=lowerCamelCase, final_dropout=lowerCamelCase) # let chunk size default to None _lowercase : Union[str, Any] = None _lowercase : str = 0 def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase) -> Tuple: """simple docstring""" _lowercase : Any = chunk_size _lowercase : Union[str, Any] = dim def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = None, lowerCamelCase = None, lowerCamelCase = None, lowerCamelCase = None, lowerCamelCase = None, lowerCamelCase = None, ) -> List[Any]: """simple docstring""" if self.use_ada_layer_norm: _lowercase : List[str] = self.norma(lowerCamelCase, lowerCamelCase) elif self.use_ada_layer_norm_zero: _lowercase , _lowercase , _lowercase , _lowercase , _lowercase : Any = self.norma( lowerCamelCase, lowerCamelCase, lowerCamelCase, hidden_dtype=hidden_states.dtype) else: _lowercase : List[Any] = self.norma(lowerCamelCase) _lowercase : List[Any] = cross_attention_kwargs if cross_attention_kwargs is not None else {} _lowercase : Any = self.attna( lowerCamelCase, encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None, attention_mask=lowerCamelCase, **lowerCamelCase, ) if self.use_ada_layer_norm_zero: _lowercase : List[Any] = gate_msa.unsqueeze(1) * attn_output _lowercase : List[Any] = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: _lowercase : List[Any] = ( self.norma(lowerCamelCase, lowerCamelCase) if self.use_ada_layer_norm else self.norma(lowerCamelCase) ) _lowercase : Any = self.attna( lowerCamelCase, encoder_hidden_states=lowerCamelCase, attention_mask=lowerCamelCase, **lowerCamelCase, ) _lowercase : Optional[int] = attn_output + hidden_states # 3. Feed-forward _lowercase : List[str] = self.norma(lowerCamelCase) if self.use_ada_layer_norm_zero: _lowercase : str = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( F'''`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.''') _lowercase : Optional[Any] = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size _lowercase : Optional[Any] = torch.cat( [self.ff(lowerCamelCase) for hid_slice in norm_hidden_states.chunk(lowerCamelCase, dim=self._chunk_dim)], dim=self._chunk_dim, ) else: _lowercase : Union[str, Any] = self.ff(lowerCamelCase) if self.use_ada_layer_norm_zero: _lowercase : List[str] = gate_mlp.unsqueeze(1) * ff_output _lowercase : Tuple = ff_output + hidden_states return hidden_states class _lowerCamelCase( nn.Module ): def __init__( self, lowerCamelCase, lowerCamelCase = None, lowerCamelCase = 4, lowerCamelCase = 0.0, lowerCamelCase = "geglu", lowerCamelCase = False, ) -> Tuple: """simple docstring""" super().__init__() _lowercase : Optional[Any] = int(dim * mult) _lowercase : Optional[Any] = dim_out if dim_out is not None else dim if activation_fn == "gelu": _lowercase : Union[str, Any] = GELU(lowerCamelCase, lowerCamelCase) if activation_fn == "gelu-approximate": _lowercase : Optional[Any] = GELU(lowerCamelCase, lowerCamelCase, approximate='tanh') elif activation_fn == "geglu": _lowercase : str = GEGLU(lowerCamelCase, lowerCamelCase) elif activation_fn == "geglu-approximate": _lowercase : Union[str, Any] = ApproximateGELU(lowerCamelCase, lowerCamelCase) _lowercase : List[Any] = nn.ModuleList([]) # project in self.net.append(lowerCamelCase) # project dropout self.net.append(nn.Dropout(lowerCamelCase)) # project out self.net.append(nn.Linear(lowerCamelCase, lowerCamelCase)) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(lowerCamelCase)) def UpperCamelCase ( self, lowerCamelCase) -> Optional[int]: """simple docstring""" for module in self.net: _lowercase : Union[str, Any] = module(lowerCamelCase) return hidden_states class _lowerCamelCase( nn.Module ): def __init__( self, lowerCamelCase, lowerCamelCase, lowerCamelCase = "none") -> Optional[int]: """simple docstring""" super().__init__() _lowercase : Union[str, Any] = nn.Linear(lowerCamelCase, lowerCamelCase) _lowercase : List[Any] = approximate def UpperCamelCase ( self, lowerCamelCase) -> Tuple: """simple docstring""" if gate.device.type != "mps": return F.gelu(lowerCamelCase, approximate=self.approximate) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa), approximate=self.approximate).to(dtype=gate.dtype) def UpperCamelCase ( self, lowerCamelCase) -> Tuple: """simple docstring""" _lowercase : Optional[int] = self.proj(lowerCamelCase) _lowercase : Union[str, Any] = self.gelu(lowerCamelCase) return hidden_states class _lowerCamelCase( nn.Module ): def __init__( self, lowerCamelCase, lowerCamelCase) -> int: """simple docstring""" super().__init__() _lowercase : Optional[Any] = nn.Linear(lowerCamelCase, dim_out * 2) def UpperCamelCase ( self, lowerCamelCase) -> Any: """simple docstring""" if gate.device.type != "mps": return F.gelu(lowerCamelCase) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa)).to(dtype=gate.dtype) def UpperCamelCase ( self, lowerCamelCase) -> Optional[int]: """simple docstring""" _lowercase , _lowercase : Tuple = self.proj(lowerCamelCase).chunk(2, dim=-1) return hidden_states * self.gelu(lowerCamelCase) class _lowerCamelCase( nn.Module ): def __init__( self, lowerCamelCase, lowerCamelCase) -> Any: """simple docstring""" super().__init__() _lowercase : str = nn.Linear(lowerCamelCase, lowerCamelCase) def UpperCamelCase ( self, lowerCamelCase) -> Union[str, Any]: """simple docstring""" _lowercase : Optional[int] = self.proj(lowerCamelCase) return x * torch.sigmoid(1.7_0_2 * x) class _lowerCamelCase( nn.Module ): def __init__( self, lowerCamelCase, lowerCamelCase) -> Tuple: """simple docstring""" super().__init__() _lowercase : int = nn.Embedding(lowerCamelCase, lowerCamelCase) _lowercase : List[Any] = nn.SiLU() _lowercase : Optional[Any] = nn.Linear(lowerCamelCase, embedding_dim * 2) _lowercase : List[Any] = nn.LayerNorm(lowerCamelCase, elementwise_affine=lowerCamelCase) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase) -> Optional[Any]: """simple docstring""" _lowercase : List[str] = self.linear(self.silu(self.emb(lowerCamelCase))) _lowercase , _lowercase : int = torch.chunk(lowerCamelCase, 2) _lowercase : Optional[Any] = self.norm(lowerCamelCase) * (1 + scale) + shift return x class _lowerCamelCase( nn.Module ): def __init__( self, lowerCamelCase, lowerCamelCase) -> Union[str, Any]: """simple docstring""" super().__init__() _lowercase : List[Any] = CombinedTimestepLabelEmbeddings(lowerCamelCase, lowerCamelCase) _lowercase : Tuple = nn.SiLU() _lowercase : Any = nn.Linear(lowerCamelCase, 6 * embedding_dim, bias=lowerCamelCase) _lowercase : List[str] = nn.LayerNorm(lowerCamelCase, elementwise_affine=lowerCamelCase, eps=1E-6) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=None) -> Dict: """simple docstring""" _lowercase : Optional[int] = self.linear(self.silu(self.emb(lowerCamelCase, lowerCamelCase, hidden_dtype=lowerCamelCase))) _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase : List[str] = emb.chunk(6, dim=1) _lowercase : Dict = self.norm(lowerCamelCase) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class _lowerCamelCase( nn.Module ): def __init__( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase = None, lowerCamelCase = 1E-5) -> Union[str, Any]: """simple docstring""" super().__init__() _lowercase : Optional[Any] = num_groups _lowercase : Any = eps if act_fn is None: _lowercase : Optional[Any] = None else: _lowercase : Any = get_activation(lowerCamelCase) _lowercase : int = nn.Linear(lowerCamelCase, out_dim * 2) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase) -> Optional[int]: """simple docstring""" if self.act: _lowercase : Optional[int] = self.act(lowerCamelCase) _lowercase : Union[str, Any] = self.linear(lowerCamelCase) _lowercase : Optional[Any] = emb[:, :, None, None] _lowercase , _lowercase : Optional[Any] = emb.chunk(2, dim=1) _lowercase : Any = F.group_norm(lowerCamelCase, self.num_groups, eps=self.eps) _lowercase : Optional[Any] = x * (1 + scale) + shift return x
89
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope='session' ) def UpperCamelCase_( ) -> Any: _lowercase : str = 10 _lowercase : List[str] = datasets.Features( { 'tokens': datasets.Sequence(datasets.Value('string' ) ), 'labels': datasets.Sequence(datasets.ClassLabel(names=['negative', 'positive'] ) ), 'answers': datasets.Sequence( { 'text': datasets.Value('string' ), 'answer_start': datasets.Value('int32' ), } ), 'id': datasets.Value('int64' ), } ) _lowercase : Union[str, Any] = datasets.Dataset.from_dict( { 'tokens': [['foo'] * 5] * n, 'labels': [[1] * 5] * n, 'answers': [{'answer_start': [97], 'text': ['1976']}] * 10, 'id': list(range(lowerCamelCase_ ) ), } , features=lowerCamelCase_ , ) return dataset @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> int: _lowercase : int = str(tmp_path_factory.mktemp('data' ) / 'file.arrow' ) dataset.map(cache_file_name=lowerCamelCase_ ) return filename # FILE_CONTENT + files SCREAMING_SNAKE_CASE : str = "\\n Text data.\n Second line of data." @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> List[Any]: _lowercase : str = tmp_path_factory.mktemp('data' ) / 'file.txt' _lowercase : List[str] = FILE_CONTENT with open(lowerCamelCase_ , 'w' ) as f: f.write(lowerCamelCase_ ) return filename @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> Tuple: import bza _lowercase : Any = tmp_path_factory.mktemp('data' ) / 'file.txt.bz2' _lowercase : Optional[Any] = bytes(lowerCamelCase_ , 'utf-8' ) with bza.open(lowerCamelCase_ , 'wb' ) as f: f.write(lowerCamelCase_ ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> List[Any]: import gzip _lowercase : Optional[int] = str(tmp_path_factory.mktemp('data' ) / 'file.txt.gz' ) _lowercase : Optional[int] = bytes(lowerCamelCase_ , 'utf-8' ) with gzip.open(lowerCamelCase_ , 'wb' ) as f: f.write(lowerCamelCase_ ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> str: if datasets.config.LZ4_AVAILABLE: import lza.frame _lowercase : Any = tmp_path_factory.mktemp('data' ) / 'file.txt.lz4' _lowercase : Optional[Any] = bytes(lowerCamelCase_ , 'utf-8' ) with lza.frame.open(lowerCamelCase_ , 'wb' ) as f: f.write(lowerCamelCase_ ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> str: if datasets.config.PY7ZR_AVAILABLE: import pyazr _lowercase : int = tmp_path_factory.mktemp('data' ) / 'file.txt.7z' with pyazr.SevenZipFile(lowerCamelCase_ , 'w' ) as archive: archive.write(lowerCamelCase_ , arcname=os.path.basename(lowerCamelCase_ ) ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> List[str]: import tarfile _lowercase : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'file.txt.tar' with tarfile.TarFile(lowerCamelCase_ , 'w' ) as f: f.add(lowerCamelCase_ , arcname=os.path.basename(lowerCamelCase_ ) ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> str: import lzma _lowercase : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'file.txt.xz' _lowercase : int = bytes(lowerCamelCase_ , 'utf-8' ) with lzma.open(lowerCamelCase_ , 'wb' ) as f: f.write(lowerCamelCase_ ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> str: import zipfile _lowercase : Dict = tmp_path_factory.mktemp('data' ) / 'file.txt.zip' with zipfile.ZipFile(lowerCamelCase_ , 'w' ) as f: f.write(lowerCamelCase_ , arcname=os.path.basename(lowerCamelCase_ ) ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> Optional[Any]: if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd _lowercase : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'file.txt.zst' _lowercase : Dict = bytes(lowerCamelCase_ , 'utf-8' ) with zstd.open(lowerCamelCase_ , 'wb' ) as f: f.write(lowerCamelCase_ ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> str: _lowercase : Union[str, Any] = tmp_path_factory.mktemp('data' ) / 'file.xml' _lowercase : Optional[Any] = textwrap.dedent( '\\n <?xml version="1.0" encoding="UTF-8" ?>\n <tmx version="1.4">\n <header segtype="sentence" srclang="ca" />\n <body>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang="en"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang="en"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang="en"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang="en"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang="en"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>' ) with open(lowerCamelCase_ , 'w' ) as f: f.write(lowerCamelCase_ ) return filename SCREAMING_SNAKE_CASE : Dict = [ {"col_1": "0", "col_2": 0, "col_3": 0.0}, {"col_1": "1", "col_2": 1, "col_3": 1.0}, {"col_1": "2", "col_2": 2, "col_3": 2.0}, {"col_1": "3", "col_2": 3, "col_3": 3.0}, ] SCREAMING_SNAKE_CASE : Dict = [ {"col_1": "4", "col_2": 4, "col_3": 4.0}, {"col_1": "5", "col_2": 5, "col_3": 5.0}, ] SCREAMING_SNAKE_CASE : Optional[Any] = { "col_1": ["0", "1", "2", "3"], "col_2": [0, 1, 2, 3], "col_3": [0.0, 1.0, 2.0, 3.0], } SCREAMING_SNAKE_CASE : Tuple = [ {"col_3": 0.0, "col_1": "0", "col_2": 0}, {"col_3": 1.0, "col_1": "1", "col_2": 1}, ] SCREAMING_SNAKE_CASE : Any = [ {"col_1": "s0", "col_2": 0, "col_3": 0.0}, {"col_1": "s1", "col_2": 1, "col_3": 1.0}, {"col_1": "s2", "col_2": 2, "col_3": 2.0}, {"col_1": "s3", "col_2": 3, "col_3": 3.0}, ] @pytest.fixture(scope='session' ) def UpperCamelCase_( ) -> List[str]: return DATA_DICT_OF_LISTS @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> Dict: _lowercase : Optional[int] = datasets.Dataset.from_dict(lowerCamelCase_ ) _lowercase : List[Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset.arrow' ) dataset.map(cache_file_name=lowerCamelCase_ ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> str: _lowercase : List[str] = str(tmp_path_factory.mktemp('data' ) / 'dataset.sqlite' ) with contextlib.closing(sqlitea.connect(lowerCamelCase_ ) ) as con: _lowercase : Union[str, Any] = con.cursor() cur.execute('CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)' ) for item in DATA: cur.execute('INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)' , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> Dict: _lowercase : List[str] = str(tmp_path_factory.mktemp('data' ) / 'dataset.csv' ) with open(lowerCamelCase_ , 'w' , newline='' ) as f: _lowercase : Tuple = csv.DictWriter(lowerCamelCase_ , fieldnames=['col_1', 'col_2', 'col_3'] ) writer.writeheader() for item in DATA: writer.writerow(lowerCamelCase_ ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> List[Any]: _lowercase : Tuple = str(tmp_path_factory.mktemp('data' ) / 'dataset2.csv' ) with open(lowerCamelCase_ , 'w' , newline='' ) as f: _lowercase : str = csv.DictWriter(lowerCamelCase_ , fieldnames=['col_1', 'col_2', 'col_3'] ) writer.writeheader() for item in DATA: writer.writerow(lowerCamelCase_ ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> Any: import bza _lowercase : int = tmp_path_factory.mktemp('data' ) / 'dataset.csv.bz2' with open(lowerCamelCase_ , 'rb' ) as f: _lowercase : int = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(lowerCamelCase_ , 'wb' ) as f: f.write(lowerCamelCase_ ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Optional[int]: _lowercase : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'dataset.csv.zip' with zipfile.ZipFile(lowerCamelCase_ , 'w' ) as f: f.write(lowerCamelCase_ , arcname=os.path.basename(lowerCamelCase_ ) ) f.write(lowerCamelCase_ , arcname=os.path.basename(lowerCamelCase_ ) ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Optional[Any]: _lowercase : str = tmp_path_factory.mktemp('data' ) / 'dataset.csv.zip' with zipfile.ZipFile(lowerCamelCase_ , 'w' ) as f: f.write(lowerCamelCase_ , arcname=os.path.basename(csv_path.replace('.csv' , '.CSV' ) ) ) f.write(lowerCamelCase_ , arcname=os.path.basename(csva_path.replace('.csv' , '.CSV' ) ) ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Union[str, Any]: _lowercase : Union[str, Any] = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.csv.zip' with zipfile.ZipFile(lowerCamelCase_ , 'w' ) as f: f.write(lowerCamelCase_ , arcname=os.path.join('main_dir' , os.path.basename(lowerCamelCase_ ) ) ) f.write(lowerCamelCase_ , arcname=os.path.join('main_dir' , os.path.basename(lowerCamelCase_ ) ) ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> int: _lowercase : Optional[int] = str(tmp_path_factory.mktemp('data' ) / 'dataset.parquet' ) _lowercase : Optional[Any] = pa.schema( { 'col_1': pa.string(), 'col_2': pa.intaa(), 'col_3': pa.floataa(), } ) with open(lowerCamelCase_ , 'wb' ) as f: _lowercase : List[str] = pq.ParquetWriter(lowerCamelCase_ , schema=lowerCamelCase_ ) _lowercase : Any = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(lowerCamelCase_ ) )] for k in DATA[0]} , schema=lowerCamelCase_ ) writer.write_table(lowerCamelCase_ ) writer.close() return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> Optional[Any]: _lowercase : Optional[Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset.json' ) _lowercase : List[Any] = {'data': DATA} with open(lowerCamelCase_ , 'w' ) as f: json.dump(lowerCamelCase_ , lowerCamelCase_ ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> Any: _lowercase : Tuple = str(tmp_path_factory.mktemp('data' ) / 'dataset.json' ) _lowercase : Optional[Any] = {'data': DATA_DICT_OF_LISTS} with open(lowerCamelCase_ , 'w' ) as f: json.dump(lowerCamelCase_ , lowerCamelCase_ ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> Union[str, Any]: _lowercase : Any = str(tmp_path_factory.mktemp('data' ) / 'dataset.jsonl' ) with open(lowerCamelCase_ , 'w' ) as f: for item in DATA: f.write(json.dumps(lowerCamelCase_ ) + '\n' ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> Dict: _lowercase : Dict = str(tmp_path_factory.mktemp('data' ) / 'dataset2.jsonl' ) with open(lowerCamelCase_ , 'w' ) as f: for item in DATA: f.write(json.dumps(lowerCamelCase_ ) + '\n' ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> List[str]: _lowercase : Optional[Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset_312.jsonl' ) with open(lowerCamelCase_ , 'w' ) as f: for item in DATA_312: f.write(json.dumps(lowerCamelCase_ ) + '\n' ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> List[Any]: _lowercase : str = str(tmp_path_factory.mktemp('data' ) / 'dataset-str.jsonl' ) with open(lowerCamelCase_ , 'w' ) as f: for item in DATA_STR: f.write(json.dumps(lowerCamelCase_ ) + '\n' ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> Optional[Any]: import gzip _lowercase : Tuple = str(tmp_path_factory.mktemp('data' ) / 'dataset.txt.gz' ) with open(lowerCamelCase_ , 'rb' ) as orig_file: with gzip.open(lowerCamelCase_ , 'wb' ) as zipped_file: zipped_file.writelines(lowerCamelCase_ ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> Dict: import gzip _lowercase : Optional[int] = str(tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.gz' ) with open(lowerCamelCase_ , 'rb' ) as orig_file: with gzip.open(lowerCamelCase_ , 'wb' ) as zipped_file: zipped_file.writelines(lowerCamelCase_ ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> List[str]: _lowercase : Any = tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.zip' with zipfile.ZipFile(lowerCamelCase_ , 'w' ) as f: f.write(lowerCamelCase_ , arcname=os.path.basename(lowerCamelCase_ ) ) f.write(lowerCamelCase_ , arcname=os.path.basename(lowerCamelCase_ ) ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> str: _lowercase : str = tmp_path_factory.mktemp('data' ) / 'dataset_nested.jsonl.zip' with zipfile.ZipFile(lowerCamelCase_ , 'w' ) as f: f.write(lowerCamelCase_ , arcname=os.path.join('nested' , os.path.basename(lowerCamelCase_ ) ) ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> int: _lowercase : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.jsonl.zip' with zipfile.ZipFile(lowerCamelCase_ , 'w' ) as f: f.write(lowerCamelCase_ , arcname=os.path.join('main_dir' , os.path.basename(lowerCamelCase_ ) ) ) f.write(lowerCamelCase_ , arcname=os.path.join('main_dir' , os.path.basename(lowerCamelCase_ ) ) ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Optional[int]: _lowercase : Tuple = tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.tar' with tarfile.TarFile(lowerCamelCase_ , 'w' ) as f: f.add(lowerCamelCase_ , arcname=os.path.basename(lowerCamelCase_ ) ) f.add(lowerCamelCase_ , arcname=os.path.basename(lowerCamelCase_ ) ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Any: _lowercase : str = tmp_path_factory.mktemp('data' ) / 'dataset_nested.jsonl.tar' with tarfile.TarFile(lowerCamelCase_ , 'w' ) as f: f.add(lowerCamelCase_ , arcname=os.path.join('nested' , os.path.basename(lowerCamelCase_ ) ) ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> Any: _lowercase : Optional[int] = ['0', '1', '2', '3'] _lowercase : str = str(tmp_path_factory.mktemp('data' ) / 'dataset.txt' ) with open(lowerCamelCase_ , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> Union[str, Any]: _lowercase : str = ['0', '1', '2', '3'] _lowercase : List[Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset2.txt' ) with open(lowerCamelCase_ , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> List[str]: _lowercase : List[Any] = ['0', '1', '2', '3'] _lowercase : Optional[int] = tmp_path_factory.mktemp('data' ) / 'dataset.abc' with open(lowerCamelCase_ , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Any: _lowercase : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'dataset.text.zip' with zipfile.ZipFile(lowerCamelCase_ , 'w' ) as f: f.write(lowerCamelCase_ , arcname=os.path.basename(lowerCamelCase_ ) ) f.write(lowerCamelCase_ , arcname=os.path.basename(lowerCamelCase_ ) ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Dict: _lowercase : List[Any] = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.text.zip' with zipfile.ZipFile(lowerCamelCase_ , 'w' ) as f: f.write(lowerCamelCase_ , arcname=os.path.join('main_dir' , os.path.basename(lowerCamelCase_ ) ) ) f.write(lowerCamelCase_ , arcname=os.path.join('main_dir' , os.path.basename(lowerCamelCase_ ) ) ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> str: _lowercase : Any = tmp_path_factory.mktemp('data' ) / 'dataset.ext.zip' with zipfile.ZipFile(lowerCamelCase_ , 'w' ) as f: f.write(lowerCamelCase_ , arcname=os.path.basename('unsupported.ext' ) ) f.write(lowerCamelCase_ , arcname=os.path.basename('unsupported_2.ext' ) ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> int: _lowercase : List[str] = '\n'.join(['First', 'Second\u2029with Unicode new line', 'Third'] ) _lowercase : Any = str(tmp_path_factory.mktemp('data' ) / 'dataset_with_unicode_new_lines.txt' ) with open(lowerCamelCase_ , 'w' , encoding='utf-8' ) as f: f.write(lowerCamelCase_ ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( ) -> Dict: return os.path.join('tests' , 'features' , 'data' , 'test_image_rgb.jpg' ) @pytest.fixture(scope='session' ) def UpperCamelCase_( ) -> int: return os.path.join('tests' , 'features' , 'data' , 'test_audio_44100.wav' ) @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> Any: _lowercase : Dict = tmp_path_factory.mktemp('data' ) / 'dataset.img.zip' with zipfile.ZipFile(lowerCamelCase_ , 'w' ) as f: f.write(lowerCamelCase_ , arcname=os.path.basename(lowerCamelCase_ ) ) f.write(lowerCamelCase_ , arcname=os.path.basename(lowerCamelCase_ ).replace('.jpg' , '2.jpg' ) ) return path @pytest.fixture(scope='session' ) def UpperCamelCase_( lowerCamelCase_ ) -> Optional[Any]: _lowercase : str = tmp_path_factory.mktemp('data_dir' ) (data_dir / "subdir").mkdir() with open(data_dir / 'subdir' / 'train.txt' , 'w' ) as f: f.write('foo\n' * 10 ) with open(data_dir / 'subdir' / 'test.txt' , 'w' ) as f: f.write('bar\n' * 10 ) # hidden file with open(data_dir / 'subdir' / '.test.txt' , 'w' ) as f: f.write('bar\n' * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / '.subdir' / 'train.txt' , 'w' ) as f: f.write('foo\n' * 10 ) with open(data_dir / '.subdir' / 'test.txt' , 'w' ) as f: f.write('bar\n' * 10 ) return data_dir
89
1
"""simple docstring""" import numpy as np import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel from ...utils import logging SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) class _UpperCAmelCase ( __snake_case ): '''simple docstring''' lowerCamelCase__ =CLIPConfig lowerCamelCase__ =['CLIPEncoderLayer'] def __init__(self , a_ ): '''simple docstring''' super().__init__(a_ ) __snake_case : Dict = CLIPVisionModelWithProjection(config.vision_config ) __snake_case : str = nn.Linear(config.vision_config.projection_dim , 1 ) __snake_case : Tuple = nn.Linear(config.vision_config.projection_dim , 1 ) @torch.no_grad() def SCREAMING_SNAKE_CASE (self , a_ , a_ , a_=0.5 , a_=0.5 ): '''simple docstring''' __snake_case : str = self.vision_model(a_ )[0] __snake_case : Optional[int] = self.p_head(a_ ) __snake_case : Optional[Any] = nsfw_detected.flatten() __snake_case : Optional[int] = nsfw_detected > p_threshold __snake_case : Optional[int] = nsfw_detected.tolist() if any(a_ ): logger.warning( '''Potential NSFW content was detected in one or more images. A black image will be returned instead.''' ''' Try again with a different prompt and/or seed.''' ) for idx, nsfw_detected_ in enumerate(a_ ): if nsfw_detected_: __snake_case : Tuple = np.zeros(images[idx].shape ) __snake_case : Any = self.w_head(a_ ) __snake_case : Tuple = watermark_detected.flatten() __snake_case : str = watermark_detected > w_threshold __snake_case : Dict = watermark_detected.tolist() if any(a_ ): logger.warning( '''Potential watermarked content was detected in one or more images. A black image will be returned instead.''' ''' Try again with a different prompt and/or seed.''' ) for idx, watermark_detected_ in enumerate(a_ ): if watermark_detected_: __snake_case : List[Any] = np.zeros(images[idx].shape ) return images, nsfw_detected, watermark_detected
229
"""simple docstring""" def lowercase ( _snake_case : list[list] ) ->list[list]: """simple docstring""" __snake_case : Dict = current_set.copy() for row_index, row in enumerate(_snake_case ): __snake_case : str = row[0] for column_index, column in enumerate(_snake_case ): if magnitude == 0: __snake_case : str = column continue __snake_case : str = column / magnitude # Subtract to cancel term __snake_case : Union[str, Any] = current_set[0] __snake_case : int = [first_row] __snake_case : Tuple = current_set[1::] for row in current_set: __snake_case : Optional[int] = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(_snake_case ) continue for column_index in range(len(_snake_case ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(_snake_case ) # Create next recursion iteration set if len(final_set[0] ) != 3: __snake_case : Tuple = final_set[0] __snake_case : Tuple = [] __snake_case : List[str] = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) __snake_case : str = simplify(_snake_case ) for i in range(len(_snake_case ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , _snake_case ) __snake_case : List[Any] = resultant return final_set def lowercase ( _snake_case : list[list] ) ->list: """simple docstring""" if len(_snake_case ) == 0: raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) __snake_case : Optional[int] = len(_snake_case ) + 1 if any(len(_snake_case ) != _length for item in equations ): raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) for row in equations: if any(not isinstance(_snake_case , (int, float) ) for column in row ): raise ValueError('''solve_simultaneous() requires lists of integers''' ) if len(_snake_case ) == 1: return [equations[0][-1] / equations[0][0]] __snake_case : int = equations.copy() if any(0 in row for row in data_set ): __snake_case : List[Any] = data_set.copy() __snake_case : int = [] for row_index, row in enumerate(_snake_case ): if 0 not in row: __snake_case : Tuple = data_set.pop(_snake_case ) break if not full_row: raise ValueError('''solve_simultaneous() requires at least 1 full equation''' ) data_set.insert(0 , _snake_case ) __snake_case : Tuple = data_set.copy() __snake_case : Dict = simplify(_snake_case ) __snake_case : Optional[int] = simplified[::-1] __snake_case : list = [] for row in simplified: __snake_case : Union[str, Any] = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue __snake_case : Any = row.copy()[: len(_snake_case ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(_snake_case ) == 0: solutions.append(0 ) continue __snake_case : Tuple = temp_row[1::] __snake_case : List[str] = temp_row[::-1] for column_index, column in enumerate(_snake_case ): current_solution -= column * solutions[column_index] solutions.append(_snake_case ) __snake_case : Optional[Any] = [] for item in solutions: final.append(float(round(_snake_case , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() SCREAMING_SNAKE_CASE : Tuple = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
229
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Dict = logging.get_logger(__name__) __A : List[str] = { "facebook/xlm-roberta-xl": "https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json", "facebook/xlm-roberta-xxl": "https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json", # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl } class __lowerCAmelCase ( _UpperCamelCase): '''simple docstring''' __magic_name__ : List[Any] = """xlm-roberta-xl""" def __init__( self : Any , UpperCamelCase__ : Optional[Any]=250880 , UpperCamelCase__ : Any=2560 , UpperCamelCase__ : str=36 , UpperCamelCase__ : List[Any]=32 , UpperCamelCase__ : Tuple=10240 , UpperCamelCase__ : Dict="gelu" , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : int=514 , UpperCamelCase__ : Tuple=1 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Union[str, Any]=1E-05 , UpperCamelCase__ : int=1 , UpperCamelCase__ : Dict=0 , UpperCamelCase__ : List[str]=2 , UpperCamelCase__ : List[Any]="absolute" , UpperCamelCase__ : Tuple=True , UpperCamelCase__ : Dict=None , **UpperCamelCase__ : Optional[int] , ): super().__init__(pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ ) A__ : Optional[Any] =vocab_size A__ : List[Any] =hidden_size A__ : Any =num_hidden_layers A__ : Dict =num_attention_heads A__ : int =hidden_act A__ : str =intermediate_size A__ : str =hidden_dropout_prob A__ : List[str] =attention_probs_dropout_prob A__ : Any =max_position_embeddings A__ : Tuple =type_vocab_size A__ : Optional[Any] =initializer_range A__ : List[str] =layer_norm_eps A__ : Any =position_embedding_type A__ : int =use_cache A__ : Optional[int] =classifier_dropout class __lowerCAmelCase ( _UpperCamelCase): '''simple docstring''' @property def _UpperCAmelCase ( self : str ): if self.task == "multiple-choice": A__ : List[str] ={0: "batch", 1: "choice", 2: "sequence"} else: A__ : Optional[Any] ={0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
656
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import requests import torch from PIL import Image from transformers import GLPNConfig, GLPNForDepthEstimation, GLPNImageProcessor from transformers.utils import logging logging.set_verbosity_info() __A : int = logging.get_logger(__name__) def lowercase ( UpperCamelCase : Any ): """simple docstring""" A__ : str =OrderedDict() for key, value in state_dict.items(): if key.startswith("module.encoder" ): A__ : Dict =key.replace("module.encoder" , "glpn.encoder" ) if key.startswith("module.decoder" ): A__ : Optional[int] =key.replace("module.decoder" , "decoder.stages" ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 A__ : Tuple =key[key.find("patch_embed" ) + len("patch_embed" )] A__ : Optional[Any] =key.replace(F'''patch_embed{idx}''' , F'''patch_embeddings.{int(UpperCamelCase )-1}''' ) if "norm" in key: A__ : Dict =key.replace("norm" , "layer_norm" ) if "glpn.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 A__ : Any =key[key.find("glpn.encoder.layer_norm" ) + len("glpn.encoder.layer_norm" )] A__ : Tuple =key.replace(F'''layer_norm{idx}''' , F'''layer_norm.{int(UpperCamelCase )-1}''' ) if "layer_norm1" in key: A__ : List[Any] =key.replace("layer_norm1" , "layer_norm_1" ) if "layer_norm2" in key: A__ : Optional[int] =key.replace("layer_norm2" , "layer_norm_2" ) if "block" in key: # replace for example block1 by block.0 A__ : int =key[key.find("block" ) + len("block" )] A__ : Optional[Any] =key.replace(F'''block{idx}''' , F'''block.{int(UpperCamelCase )-1}''' ) if "attn.q" in key: A__ : Optional[Any] =key.replace("attn.q" , "attention.self.query" ) if "attn.proj" in key: A__ : Union[str, Any] =key.replace("attn.proj" , "attention.output.dense" ) if "attn" in key: A__ : str =key.replace("attn" , "attention.self" ) if "fc1" in key: A__ : Dict =key.replace("fc1" , "dense1" ) if "fc2" in key: A__ : str =key.replace("fc2" , "dense2" ) if "linear_pred" in key: A__ : List[Any] =key.replace("linear_pred" , "classifier" ) if "linear_fuse" in key: A__ : List[str] =key.replace("linear_fuse.conv" , "linear_fuse" ) A__ : Any =key.replace("linear_fuse.bn" , "batch_norm" ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 A__ : str =key[key.find("linear_c" ) + len("linear_c" )] A__ : Dict =key.replace(F'''linear_c{idx}''' , F'''linear_c.{int(UpperCamelCase )-1}''' ) if "bot_conv" in key: A__ : Union[str, Any] =key.replace("bot_conv" , "0.convolution" ) if "skip_conv1" in key: A__ : List[Any] =key.replace("skip_conv1" , "1.convolution" ) if "skip_conv2" in key: A__ : int =key.replace("skip_conv2" , "2.convolution" ) if "fusion1" in key: A__ : Optional[Any] =key.replace("fusion1" , "1.fusion" ) if "fusion2" in key: A__ : Optional[Any] =key.replace("fusion2" , "2.fusion" ) if "fusion3" in key: A__ : int =key.replace("fusion3" , "3.fusion" ) if "fusion" in key and "conv" in key: A__ : List[str] =key.replace("conv" , "convolutional_layer" ) if key.startswith("module.last_layer_depth" ): A__ : Tuple =key.replace("module.last_layer_depth" , "head.head" ) A__ : int =value return new_state_dict def lowercase ( UpperCamelCase : Union[str, Any] , UpperCamelCase : Dict ): """simple docstring""" # for each of the encoder blocks: for i in range(config.num_encoder_blocks ): for j in range(config.depths[i] ): # read in weights + bias of keys and values (which is a single matrix in the original implementation) A__ : int =state_dict.pop(F'''glpn.encoder.block.{i}.{j}.attention.self.kv.weight''' ) A__ : str =state_dict.pop(F'''glpn.encoder.block.{i}.{j}.attention.self.kv.bias''' ) # next, add keys and values (in that order) to the state dict A__ : List[str] =kv_weight[ : config.hidden_sizes[i], : ] A__ : Dict =kv_bias[: config.hidden_sizes[i]] A__ : Any =kv_weight[ config.hidden_sizes[i] :, : ] A__ : Any =kv_bias[config.hidden_sizes[i] :] def lowercase ( ): """simple docstring""" A__ : Optional[Any] ="http://images.cocodataset.org/val2017/000000039769.jpg" A__ : List[Any] =Image.open(requests.get(UpperCamelCase , stream=UpperCamelCase ).raw ) return image @torch.no_grad() def lowercase ( UpperCamelCase : str , UpperCamelCase : Tuple , UpperCamelCase : List[str]=False , UpperCamelCase : str=None ): """simple docstring""" A__ : List[str] =GLPNConfig(hidden_sizes=[64, 128, 320, 512] , decoder_hidden_size=64 , depths=[3, 8, 27, 3] ) # load image processor (only resize + rescale) A__ : str =GLPNImageProcessor() # prepare image A__ : Any =prepare_img() A__ : Optional[int] =image_processor(images=UpperCamelCase , return_tensors="pt" ).pixel_values logger.info("Converting model..." ) # load original state dict A__ : int =torch.load(UpperCamelCase , map_location=torch.device("cpu" ) ) # rename keys A__ : Union[str, Any] =rename_keys(UpperCamelCase ) # key and value matrices need special treatment read_in_k_v(UpperCamelCase , UpperCamelCase ) # create HuggingFace model and load state dict A__ : Optional[int] =GLPNForDepthEstimation(UpperCamelCase ) model.load_state_dict(UpperCamelCase ) model.eval() # forward pass A__ : int =model(UpperCamelCase ) A__ : Optional[Any] =outputs.predicted_depth # verify output if model_name is not None: if "nyu" in model_name: A__ : List[Any] =torch.tensor( [[4.41_47, 4.08_73, 4.06_73], [3.78_90, 3.28_81, 3.15_25], [3.76_74, 3.54_23, 3.49_13]] ) elif "kitti" in model_name: A__ : Tuple =torch.tensor( [[3.42_91, 2.78_65, 2.51_51], [3.28_41, 2.70_21, 2.35_02], [3.11_47, 2.46_25, 2.24_81]] ) else: raise ValueError(F'''Unknown model name: {model_name}''' ) A__ : str =torch.Size([1, 480, 640] ) assert predicted_depth.shape == expected_shape assert torch.allclose(predicted_depth[0, :3, :3] , UpperCamelCase , atol=1E-4 ) print("Looks ok!" ) # finally, push to hub if required if push_to_hub: logger.info("Pushing model and image processor to the hub..." ) model.push_to_hub( repo_path_or_name=Path(UpperCamelCase , UpperCamelCase ) , organization="nielsr" , commit_message="Add model" , use_temp_dir=UpperCamelCase , ) image_processor.push_to_hub( repo_path_or_name=Path(UpperCamelCase , UpperCamelCase ) , organization="nielsr" , commit_message="Add image processor" , use_temp_dir=UpperCamelCase , ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() parser.add_argument( "--checkpoint_path", default=None, type=str, help="Path to the original PyTorch checkpoint (.pth file).", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to upload the model to the HuggingFace hub." ) parser.add_argument( "--model_name", default="glpn-kitti", type=str, help="Name of the model in case you're pushing to the hub.", ) __A : Any = parser.parse_args() convert_glpn_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
656
1
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class _a ( lowercase__ ): """simple docstring""" snake_case_ = 42 snake_case_ = 42 class _a ( lowercase__ , lowercase__ ): """simple docstring""" snake_case_ = 1 @register_to_config def __init__( self : Dict , a : int = 20_00 , a : float = 0.15 , a : float = 0.01 , a : float = 1348.0 , a : float = 1E-5 , a : int = 1 , ) ->int: # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE__ : Any = sigma_max # setable values SCREAMING_SNAKE_CASE__ : Optional[int] = None self.set_sigmas(a , a , a , a ) def A_ ( self : Any , a : torch.FloatTensor , a : Optional[int] = None ) ->torch.FloatTensor: return sample def A_ ( self : Tuple , a : int , a : float = None , a : Union[str, torch.device] = None ) ->str: SCREAMING_SNAKE_CASE__ : Optional[Any] = sampling_eps if sampling_eps is not None else self.config.sampling_eps SCREAMING_SNAKE_CASE__ : str = torch.linspace(1 , a , a , device=a ) def A_ ( self : Optional[Any] , a : int , a : float = None , a : float = None , a : float = None ) ->Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] = sigma_min if sigma_min is not None else self.config.sigma_min SCREAMING_SNAKE_CASE__ : List[str] = sigma_max if sigma_max is not None else self.config.sigma_max SCREAMING_SNAKE_CASE__ : Tuple = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(a , a ) SCREAMING_SNAKE_CASE__ : Tuple = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.exp(torch.linspace(math.log(a ) , math.log(a ) , a ) ) SCREAMING_SNAKE_CASE__ : Dict = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps] ) def A_ ( self : Optional[Any] , a : str , a : Tuple ) ->Dict: return torch.where( timesteps == 0 , torch.zeros_like(t.to(timesteps.device ) ) , self.discrete_sigmas[timesteps - 1].to(timesteps.device ) , ) def A_ ( self : Optional[int] , a : torch.FloatTensor , a : int , a : torch.FloatTensor , a : Optional[torch.Generator] = None , a : bool = True , ) ->Union[SdeVeOutput, Tuple]: if self.timesteps is None: raise ValueError( "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler" ) SCREAMING_SNAKE_CASE__ : Tuple = timestep * torch.ones( sample.shape[0] , device=sample.device ) # torch.repeat_interleave(timestep, sample.shape[0]) SCREAMING_SNAKE_CASE__ : str = (timestep * (len(self.timesteps ) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda SCREAMING_SNAKE_CASE__ : List[Any] = timesteps.to(self.discrete_sigmas.device ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.discrete_sigmas[timesteps].to(sample.device ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_adjacent_sigma(a , a ).to(sample.device ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.zeros_like(a ) SCREAMING_SNAKE_CASE__ : List[str] = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods SCREAMING_SNAKE_CASE__ : Optional[Any] = diffusion.flatten() while len(diffusion.shape ) < len(sample.shape ): SCREAMING_SNAKE_CASE__ : Any = diffusion.unsqueeze(-1 ) SCREAMING_SNAKE_CASE__ : Any = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of SCREAMING_SNAKE_CASE__ : Tuple = randn_tensor( sample.shape , layout=sample.layout , generator=a , device=sample.device , dtype=sample.dtype ) SCREAMING_SNAKE_CASE__ : str = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? SCREAMING_SNAKE_CASE__ : str = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=a , prev_sample_mean=a ) def A_ ( self : Optional[Any] , a : torch.FloatTensor , a : torch.FloatTensor , a : Optional[torch.Generator] = None , a : bool = True , ) ->Union[SchedulerOutput, Tuple]: if self.timesteps is None: raise ValueError( "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler" ) # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction SCREAMING_SNAKE_CASE__ : str = randn_tensor(sample.shape , layout=sample.layout , generator=a ).to(sample.device ) # compute step size from the model_output, the noise, and the snr SCREAMING_SNAKE_CASE__ : int = torch.norm(model_output.reshape(model_output.shape[0] , -1 ) , dim=-1 ).mean() SCREAMING_SNAKE_CASE__ : Any = torch.norm(noise.reshape(noise.shape[0] , -1 ) , dim=-1 ).mean() SCREAMING_SNAKE_CASE__ : Tuple = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 SCREAMING_SNAKE_CASE__ : Optional[int] = step_size * torch.ones(sample.shape[0] ).to(sample.device ) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term SCREAMING_SNAKE_CASE__ : Tuple = step_size.flatten() while len(step_size.shape ) < len(sample.shape ): SCREAMING_SNAKE_CASE__ : Tuple = step_size.unsqueeze(-1 ) SCREAMING_SNAKE_CASE__ : List[str] = sample + step_size * model_output SCREAMING_SNAKE_CASE__ : int = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=a ) def A_ ( self : Tuple , a : torch.FloatTensor , a : torch.FloatTensor , a : torch.FloatTensor , ) ->torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples SCREAMING_SNAKE_CASE__ : Optional[int] = timesteps.to(original_samples.device ) SCREAMING_SNAKE_CASE__ : Dict = self.discrete_sigmas.to(original_samples.device )[timesteps] SCREAMING_SNAKE_CASE__ : Any = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(a ) * sigmas[:, None, None, None] ) SCREAMING_SNAKE_CASE__ : int = noise + original_samples return noisy_samples def __len__( self : Dict ) ->Any: return self.config.num_train_timesteps
700
import json import os import sys import tempfile import unittest from pathlib import Path from shutil import copyfile from huggingface_hub import HfFolder, Repository, create_repo, delete_repo from requests.exceptions import HTTPError import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, PROCESSOR_MAPPING, TOKENIZER_MAPPING, AutoConfig, AutoFeatureExtractor, AutoProcessor, AutoTokenizer, BertTokenizer, ProcessorMixin, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaProcessor, ) from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 from test_module.custom_processing import CustomProcessor # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 __lowercase :List[str] = get_tests_dir("fixtures/dummy_feature_extractor_config.json") __lowercase :str = get_tests_dir("fixtures/vocab.json") __lowercase :Optional[int] = get_tests_dir("fixtures") class _a ( unittest.TestCase ): """simple docstring""" snake_case_ = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] def A_ ( self : Optional[Any] ) ->int: SCREAMING_SNAKE_CASE__ : Dict = 0 def A_ ( self : Any ) ->Optional[int]: SCREAMING_SNAKE_CASE__ : List[Any] = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h" ) self.assertIsInstance(a , a ) def A_ ( self : Union[str, Any] ) ->List[str]: with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Dict = WavaVecaConfig() SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h" ) # save in new folder model_config.save_pretrained(a ) processor.save_pretrained(a ) SCREAMING_SNAKE_CASE__ : str = AutoProcessor.from_pretrained(a ) self.assertIsInstance(a , a ) def A_ ( self : int ) ->List[str]: with tempfile.TemporaryDirectory() as tmpdirname: # copy relevant files copyfile(a , os.path.join(a , a ) ) copyfile(a , os.path.join(a , "vocab.json" ) ) SCREAMING_SNAKE_CASE__ : List[Any] = AutoProcessor.from_pretrained(a ) self.assertIsInstance(a , a ) def A_ ( self : List[Any] ) ->Tuple: with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Optional[Any] = WavaVecaFeatureExtractor() SCREAMING_SNAKE_CASE__ : Tuple = AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h" ) SCREAMING_SNAKE_CASE__ : Any = WavaVecaProcessor(a , a ) # save in new folder processor.save_pretrained(a ) # drop `processor_class` in tokenizer with open(os.path.join(a , a ) , "r" ) as f: SCREAMING_SNAKE_CASE__ : Optional[int] = json.load(a ) config_dict.pop("processor_class" ) with open(os.path.join(a , a ) , "w" ) as f: f.write(json.dumps(a ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = AutoProcessor.from_pretrained(a ) self.assertIsInstance(a , a ) def A_ ( self : List[str] ) ->Optional[Any]: with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Tuple = WavaVecaFeatureExtractor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h" ) SCREAMING_SNAKE_CASE__ : Optional[int] = WavaVecaProcessor(a , a ) # save in new folder processor.save_pretrained(a ) # drop `processor_class` in feature extractor with open(os.path.join(a , a ) , "r" ) as f: SCREAMING_SNAKE_CASE__ : List[Any] = json.load(a ) config_dict.pop("processor_class" ) with open(os.path.join(a , a ) , "w" ) as f: f.write(json.dumps(a ) ) SCREAMING_SNAKE_CASE__ : List[Any] = AutoProcessor.from_pretrained(a ) self.assertIsInstance(a , a ) def A_ ( self : Union[str, Any] ) ->str: with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : List[Any] = WavaVecaConfig(processor_class="Wav2Vec2Processor" ) model_config.save_pretrained(a ) # copy relevant files copyfile(a , os.path.join(a , "vocab.json" ) ) # create emtpy sample processor with open(os.path.join(a , a ) , "w" ) as f: f.write("{}" ) SCREAMING_SNAKE_CASE__ : Tuple = AutoProcessor.from_pretrained(a ) self.assertIsInstance(a , a ) def A_ ( self : Optional[Any] ) ->Optional[int]: # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(a ): SCREAMING_SNAKE_CASE__ : Optional[int] = AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor" ) # If remote code is disabled, we can't load this config. with self.assertRaises(a ): SCREAMING_SNAKE_CASE__ : Any = AutoProcessor.from_pretrained( "hf-internal-testing/test_dynamic_processor" , trust_remote_code=a ) SCREAMING_SNAKE_CASE__ : List[Any] = AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor" , trust_remote_code=a ) self.assertTrue(processor.special_attribute_present ) self.assertEqual(processor.__class__.__name__ , "NewProcessor" ) SCREAMING_SNAKE_CASE__ : Dict = processor.feature_extractor self.assertTrue(feature_extractor.special_attribute_present ) self.assertEqual(feature_extractor.__class__.__name__ , "NewFeatureExtractor" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.tokenizer self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizerFast" ) # Test we can also load the slow version SCREAMING_SNAKE_CASE__ : int = AutoProcessor.from_pretrained( "hf-internal-testing/test_dynamic_processor" , trust_remote_code=a , use_fast=a ) SCREAMING_SNAKE_CASE__ : List[Any] = new_processor.tokenizer self.assertTrue(new_tokenizer.special_attribute_present ) self.assertEqual(new_tokenizer.__class__.__name__ , "NewTokenizer" ) else: self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizer" ) def A_ ( self : Tuple ) ->List[Any]: try: AutoConfig.register("custom" , a ) AutoFeatureExtractor.register(a , a ) AutoTokenizer.register(a , slow_tokenizer_class=a ) AutoProcessor.register(a , a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(a ): AutoProcessor.register(a , a ) # Now that the config is registered, it can be used as any other config with the auto-API SCREAMING_SNAKE_CASE__ : List[str] = CustomFeatureExtractor.from_pretrained(a ) with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ : int = os.path.join(a , "vocab.txt" ) with open(a , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = CustomTokenizer(a ) SCREAMING_SNAKE_CASE__ : List[Any] = CustomProcessor(a , a ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained(a ) SCREAMING_SNAKE_CASE__ : Any = AutoProcessor.from_pretrained(a ) self.assertIsInstance(a , a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def A_ ( self : Union[str, Any] ) ->int: class _a ( lowercase__ ): """simple docstring""" snake_case_ = False class _a ( lowercase__ ): """simple docstring""" snake_case_ = False class _a ( lowercase__ ): """simple docstring""" snake_case_ = "AutoFeatureExtractor" snake_case_ = "AutoTokenizer" snake_case_ = False try: AutoConfig.register("custom" , a ) AutoFeatureExtractor.register(a , a ) AutoTokenizer.register(a , slow_tokenizer_class=a ) AutoProcessor.register(a , a ) # If remote code is not set, the default is to use local classes. SCREAMING_SNAKE_CASE__ : Optional[int] = AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor" ) self.assertEqual(processor.__class__.__name__ , "NewProcessor" ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote code is disabled, we load the local ones. SCREAMING_SNAKE_CASE__ : Tuple = AutoProcessor.from_pretrained( "hf-internal-testing/test_dynamic_processor" , trust_remote_code=a ) self.assertEqual(processor.__class__.__name__ , "NewProcessor" ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub. SCREAMING_SNAKE_CASE__ : Any = AutoProcessor.from_pretrained( "hf-internal-testing/test_dynamic_processor" , trust_remote_code=a ) self.assertEqual(processor.__class__.__name__ , "NewProcessor" ) self.assertTrue(processor.special_attribute_present ) self.assertTrue(processor.feature_extractor.special_attribute_present ) self.assertTrue(processor.tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def A_ ( self : Optional[Any] ) ->Dict: SCREAMING_SNAKE_CASE__ : Optional[int] = AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-bert" ) self.assertEqual(processor.__class__.__name__ , "BertTokenizerFast" ) def A_ ( self : Dict ) ->Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-convnext" ) self.assertEqual(processor.__class__.__name__ , "ConvNextImageProcessor" ) @is_staging_test class _a ( unittest.TestCase ): """simple docstring""" snake_case_ = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] @classmethod def A_ ( cls : List[str] ) ->Union[str, Any]: SCREAMING_SNAKE_CASE__ : int = TOKEN HfFolder.save_token(a ) @classmethod def A_ ( cls : List[str] ) ->Optional[int]: try: delete_repo(token=cls._token , repo_id="test-processor" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-processor-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-processor" ) except HTTPError: pass def A_ ( self : Dict ) ->Dict: SCREAMING_SNAKE_CASE__ : Tuple = WavaVecaProcessor.from_pretrained(a ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(a , "test-processor" ) , push_to_hub=a , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ : Optional[int] = WavaVecaProcessor.from_pretrained(f"""{USER}/test-processor""" ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(a , getattr(new_processor.feature_extractor , a ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def A_ ( self : List[str] ) ->Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] = WavaVecaProcessor.from_pretrained(a ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(a , "test-processor-org" ) , push_to_hub=a , use_auth_token=self._token , organization="valid_org" , ) SCREAMING_SNAKE_CASE__ : Dict = WavaVecaProcessor.from_pretrained("valid_org/test-processor-org" ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(a , getattr(new_processor.feature_extractor , a ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def A_ ( self : Any ) ->int: CustomFeatureExtractor.register_for_auto_class() CustomTokenizer.register_for_auto_class() CustomProcessor.register_for_auto_class() SCREAMING_SNAKE_CASE__ : Any = CustomFeatureExtractor.from_pretrained(a ) with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(a , "vocab.txt" ) with open(a , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE__ : str = CustomTokenizer(a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = CustomProcessor(a , a ) with tempfile.TemporaryDirectory() as tmp_dir: create_repo(f"""{USER}/test-dynamic-processor""" , token=self._token ) SCREAMING_SNAKE_CASE__ : str = Repository(a , clone_from=f"""{USER}/test-dynamic-processor""" , token=self._token ) processor.save_pretrained(a ) # This has added the proper auto_map field to the feature extractor config self.assertDictEqual( processor.feature_extractor.auto_map , { "AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor", "AutoProcessor": "custom_processing.CustomProcessor", } , ) # This has added the proper auto_map field to the tokenizer config with open(os.path.join(a , "tokenizer_config.json" ) ) as f: SCREAMING_SNAKE_CASE__ : str = json.load(a ) self.assertDictEqual( tokenizer_config["auto_map"] , { "AutoTokenizer": ["custom_tokenization.CustomTokenizer", None], "AutoProcessor": "custom_processing.CustomProcessor", } , ) # The code has been copied from fixtures self.assertTrue(os.path.isfile(os.path.join(a , "custom_feature_extraction.py" ) ) ) self.assertTrue(os.path.isfile(os.path.join(a , "custom_tokenization.py" ) ) ) self.assertTrue(os.path.isfile(os.path.join(a , "custom_processing.py" ) ) ) repo.push_to_hub() SCREAMING_SNAKE_CASE__ : List[Any] = AutoProcessor.from_pretrained(f"""{USER}/test-dynamic-processor""" , trust_remote_code=a ) # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module self.assertEqual(new_processor.__class__.__name__ , "CustomProcessor" )
26
0
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __lowerCAmelCase : List[str] = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" A__ : Dict = XGLMTokenizer A__ : Optional[int] = XGLMTokenizerFast A__ : int = True A__ : Optional[Any] = True def snake_case_ ( self : List[Any] ): super().setUp() # We have a SentencePiece fixture for testing __lowercase : Optional[Any] = XGLMTokenizer(_snake_case , keep_accents=_snake_case ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case_ ( self : List[Any] ): __lowercase : int = '''<pad>''' __lowercase : Optional[int] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_snake_case ) , _snake_case ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_snake_case ) , _snake_case ) def snake_case_ ( self : Dict ): __lowercase : Tuple = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(len(_snake_case ) , 1008 ) def snake_case_ ( self : List[Any] ): self.assertEqual(self.get_tokenizer().vocab_size , 1008 ) def snake_case_ ( self : Dict ): __lowercase : List[str] = XGLMTokenizer(_snake_case , keep_accents=_snake_case ) __lowercase : Union[str, Any] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(_snake_case , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_snake_case ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __lowercase : Optional[Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _snake_case , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) __lowercase : Tuple = tokenizer.convert_tokens_to_ids(_snake_case ) self.assertListEqual( _snake_case , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __lowercase : Union[str, Any] = tokenizer.convert_ids_to_tokens(_snake_case ) self.assertListEqual( _snake_case , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def snake_case_ ( self : List[str] ): return XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) def snake_case_ ( self : Any ): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(_snake_case , f.name ) __lowercase : Union[str, Any] = XGLMTokenizer(f.name , keep_accents=_snake_case ) __lowercase : List[str] = pickle.dumps(_snake_case ) pickle.loads(_snake_case ) def snake_case_ ( self : str ): if not self.test_rust_tokenizer: return __lowercase : Tuple = self.get_tokenizer() __lowercase : Optional[int] = self.get_rust_tokenizer() __lowercase : Dict = '''I was born in 92000, and this is falsé.''' __lowercase : int = tokenizer.tokenize(_snake_case ) __lowercase : int = rust_tokenizer.tokenize(_snake_case ) self.assertListEqual(_snake_case , _snake_case ) __lowercase : Dict = tokenizer.encode(_snake_case , add_special_tokens=_snake_case ) __lowercase : Tuple = rust_tokenizer.encode(_snake_case , add_special_tokens=_snake_case ) self.assertListEqual(_snake_case , _snake_case ) __lowercase : Any = self.get_rust_tokenizer() __lowercase : List[str] = tokenizer.encode(_snake_case ) __lowercase : Union[str, Any] = rust_tokenizer.encode(_snake_case ) self.assertListEqual(_snake_case , _snake_case ) @slow def snake_case_ ( self : Union[str, Any] ): __lowercase : Optional[Any] = '''Hello World!''' __lowercase : int = [2, 3_1227, 4447, 35] self.assertListEqual(_snake_case , self.big_tokenizer.encode(_snake_case ) ) @slow def snake_case_ ( self : Union[str, Any] ): __lowercase : Optional[int] = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth''' ) # fmt: off __lowercase : Any = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 7_1630, 2_8085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 1_3675, 377, 652, 7580, 1_0341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 20_2277, 1_7892, 33, 60, 87, 4, 3234, 157, 61, 2667, 5_2376, 19, 88, 23, 735] # fmt: on self.assertListEqual(_snake_case , self.big_tokenizer.encode(_snake_case ) ) @slow def snake_case_ ( self : Union[str, Any] ): # fmt: off __lowercase : Optional[Any] = { '''input_ids''': [[2, 10_8825, 1163, 15, 8_8010, 473, 1_5898, 157, 1_3672, 1857, 312, 8, 23_8021, 1163, 53, 1_3672, 1857, 312, 8, 5_3283, 18_2396, 8, 1_8566, 16, 3_6733, 4101, 8, 230, 24_4017, 12_2553, 7, 15, 13_2597, 4, 293, 1_2511, 7610, 4, 3414, 13_2597, 9, 4, 3_2361, 362, 4, 734, 2_8512, 3_2569, 18, 4, 3_2361, 2_6096, 1_4982, 73, 1_8715, 2_1433, 23_5261, 15, 492, 1_2427, 16, 53, 1_8715, 2_1433, 6_5454, 15, 2_3659, 563, 16, 278, 597, 2843, 595, 7931, 18_2396, 6_4186, 22, 886, 595, 13_2981, 53, 2_5540, 3449, 4_3982, 3_9901, 5951, 878, 330, 4, 2_7694, 8_0269, 312, 53, 6517, 1_1780, 611, 2_0408, 5], [2, 6, 13_2597, 67, 4_2897, 33, 592, 8, 16_3729, 2_5540, 361, 13_6997, 10_9514, 17_3230, 7, 501, 60, 10_2913, 196, 5631, 235, 6_3243, 473, 6, 23_1757, 74, 5277, 7905, 53, 3095, 3_7317, 22, 454, 18_3874, 5], [2, 268, 3_1298, 4_6530, 6, 13_2935, 4_3831, 7, 597, 32, 24, 3688, 9865, 5]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_snake_case , model_name='''facebook/xglm-564M''' , padding=_snake_case , )
509
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 __lowerCAmelCase : str = logging.get_logger(__name__) __lowerCAmelCase : Union[str, Any] = { "facebook/data2vec-vision-base-ft": ( "https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json" ), } class __lowerCAmelCase ( lowerCAmelCase_ ): """simple docstring""" A__ : Optional[Any] = '''data2vec-vision''' def __init__( self : str , _snake_case : str=768 , _snake_case : Tuple=12 , _snake_case : Any=12 , _snake_case : Optional[int]=3072 , _snake_case : Tuple="gelu" , _snake_case : Dict=0.0 , _snake_case : Any=0.0 , _snake_case : Tuple=0.02 , _snake_case : List[Any]=1E-1_2 , _snake_case : int=224 , _snake_case : List[str]=16 , _snake_case : List[str]=3 , _snake_case : Optional[int]=False , _snake_case : str=False , _snake_case : Tuple=False , _snake_case : Tuple=False , _snake_case : Any=0.1 , _snake_case : Any=0.1 , _snake_case : List[Any]=True , _snake_case : List[Any]=[3, 5, 7, 11] , _snake_case : List[Any]=[1, 2, 3, 6] , _snake_case : Tuple=True , _snake_case : str=0.4 , _snake_case : Any=256 , _snake_case : Any=1 , _snake_case : str=False , _snake_case : str=255 , **_snake_case : Dict , ): super().__init__(**_snake_case ) __lowercase : int = hidden_size __lowercase : Optional[int] = num_hidden_layers __lowercase : str = num_attention_heads __lowercase : List[Any] = intermediate_size __lowercase : Union[str, Any] = hidden_act __lowercase : Optional[int] = hidden_dropout_prob __lowercase : Tuple = attention_probs_dropout_prob __lowercase : Dict = initializer_range __lowercase : List[str] = layer_norm_eps __lowercase : str = image_size __lowercase : List[str] = patch_size __lowercase : Dict = num_channels __lowercase : Optional[Any] = use_mask_token __lowercase : Optional[int] = use_absolute_position_embeddings __lowercase : Tuple = use_relative_position_bias __lowercase : Dict = use_shared_relative_position_bias __lowercase : List[Any] = layer_scale_init_value __lowercase : Union[str, Any] = drop_path_rate __lowercase : Tuple = use_mean_pooling # decode head attributes (semantic segmentation) __lowercase : List[str] = out_indices __lowercase : Tuple = pool_scales # auxiliary head attributes (semantic segmentation) __lowercase : Dict = use_auxiliary_head __lowercase : str = auxiliary_loss_weight __lowercase : Union[str, Any] = auxiliary_channels __lowercase : Dict = auxiliary_num_convs __lowercase : Dict = auxiliary_concat_input __lowercase : Dict = semantic_loss_ignore_index class __lowerCAmelCase ( lowerCAmelCase_ ): """simple docstring""" A__ : int = version.parse('''1.11''' ) @property def snake_case_ ( self : str ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def snake_case_ ( self : Tuple ): return 1E-4
509
1
'''simple docstring''' import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) lowerCAmelCase_ = logging.getLogger(__name__) lowerCAmelCase_ = tf.data.AUTOTUNE def snake_case ( ): A = argparse.ArgumentParser(description='Train a masked language model on TPU.' ) parser.add_argument( '--pretrained_model_config', type=UpperCAmelCase__, default='roberta-base', help='The model config to use. Note that we don\'t copy the model\'s weights, only the config!', ) parser.add_argument( '--tokenizer', type=UpperCAmelCase__, default='unigram-tokenizer-wikitext', help='The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model\'s vocab size.', ) parser.add_argument( '--per_replica_batch_size', type=UpperCAmelCase__, default=8, help='Batch size per TPU core.', ) parser.add_argument( '--no_tpu', action='store_true', help='If set, run on CPU and don\'t try to initialize a TPU. Useful for debugging on non-TPU instances.', ) parser.add_argument( '--tpu_name', type=UpperCAmelCase__, help='Name of TPU resource to initialize. Should be blank on Colab, and \'local\' on TPU VMs.', default='local', ) parser.add_argument( '--tpu_zone', type=UpperCAmelCase__, help='Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes.', ) parser.add_argument( '--gcp_project', type=UpperCAmelCase__, help='Google cloud project name. Only used for non-Colab TPU nodes.' ) parser.add_argument( '--bfloat16', action='store_true', help='Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU.', ) parser.add_argument( '--train_dataset', type=UpperCAmelCase__, help='Path to training dataset to load. If the path begins with `gs://`' ' then the dataset will be loaded from a Google Cloud Storage bucket.', ) parser.add_argument( '--shuffle_buffer_size', type=UpperCAmelCase__, default=2**18, help='Size of the shuffle buffer (in samples)', ) parser.add_argument( '--eval_dataset', type=UpperCAmelCase__, help='Path to evaluation dataset to load. If the path begins with `gs://`' ' then the dataset will be loaded from a Google Cloud Storage bucket.', ) parser.add_argument( '--num_epochs', type=UpperCAmelCase__, default=1, help='Number of epochs to train for.', ) parser.add_argument( '--learning_rate', type=UpperCAmelCase__, default=1E-4, help='Learning rate to use for training.', ) parser.add_argument( '--weight_decay_rate', type=UpperCAmelCase__, default=1E-3, help='Weight decay rate to use for training.', ) parser.add_argument( '--max_length', type=UpperCAmelCase__, default=5_12, help='Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py', ) parser.add_argument( '--mlm_probability', type=UpperCAmelCase__, default=0.15, help='Fraction of tokens to mask during training.', ) parser.add_argument('--output_dir', type=UpperCAmelCase__, required=UpperCAmelCase__, help='Path to save model checkpoints to.' ) parser.add_argument('--hub_model_id', type=UpperCAmelCase__, help='Model ID to upload to on the Hugging Face Hub.' ) A = parser.parse_args() return args def snake_case ( UpperCAmelCase : Tuple ): try: if args.tpu_name: A = tf.distribute.cluster_resolver.TPUClusterResolver( args.tpu_name, zone=args.tpu_zone, project=args.gcp_project ) else: A = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: raise RuntimeError( 'Couldn\'t connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or ' '--gcp_project. When running on a TPU VM, use --tpu_name local.' ) tf.config.experimental_connect_to_cluster(UpperCAmelCase__ ) tf.tpu.experimental.initialize_tpu_system(UpperCAmelCase__ ) return tpu def snake_case ( UpperCAmelCase : int ): A = 0 for file in file_list: A = file.split('/' )[-1] A = re.search(r'-\d+-(\d+)\.tfrecord', UpperCAmelCase__ ).group(1 ) A = int(UpperCAmelCase__ ) num_samples += sample_count return num_samples def snake_case ( UpperCAmelCase : Tuple, UpperCAmelCase : List[str], UpperCAmelCase : str, UpperCAmelCase : Optional[int], UpperCAmelCase : List[str], UpperCAmelCase : Optional[int]=None ): A = count_samples(UpperCAmelCase__ ) A = tf.data.Dataset.from_tensor_slices(UpperCAmelCase__ ) if shuffle: A = dataset.shuffle(len(UpperCAmelCase__ ) ) A = tf.data.TFRecordDataset(UpperCAmelCase__, num_parallel_reads=UpperCAmelCase__ ) # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here A = dataset.apply(tf.data.experimental.assert_cardinality(UpperCAmelCase__ ) ) A = dataset.map(UpperCAmelCase__, num_parallel_calls=UpperCAmelCase__ ) if shuffle: assert shuffle_buffer_size is not None A = dataset.shuffle(args.shuffle_buffer_size ) A = dataset.batch(UpperCAmelCase__, drop_remainder=UpperCAmelCase__ ) A = dataset.map(UpperCAmelCase__, num_parallel_calls=UpperCAmelCase__ ) A = dataset.prefetch(UpperCAmelCase__ ) return dataset def snake_case ( UpperCAmelCase : List[str] ): if not args.no_tpu: A = initialize_tpu(UpperCAmelCase__ ) A = tf.distribute.TPUStrategy(UpperCAmelCase__ ) else: A = tf.distribute.OneDeviceStrategy(device='/gpu:0' ) if args.bfloataa: tf.keras.mixed_precision.set_global_policy('mixed_bfloat16' ) A = AutoTokenizer.from_pretrained(args.tokenizer ) A = AutoConfig.from_pretrained(args.pretrained_model_config ) A = tokenizer.vocab_size A = tf.io.gfile.glob(os.path.join(args.train_dataset, '*.tfrecord' ) ) if not training_records: raise ValueError(f'No .tfrecord files found in {args.train_dataset}.' ) A = tf.io.gfile.glob(os.path.join(args.eval_dataset, '*.tfrecord' ) ) if not eval_records: raise ValueError(f'No .tfrecord files found in {args.eval_dataset}.' ) A = count_samples(UpperCAmelCase__ ) A = num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync) A = steps_per_epoch * args.num_epochs with strategy.scope(): A = TFAutoModelForMaskedLM.from_config(UpperCAmelCase__ ) model(model.dummy_inputs ) # Pass some dummy inputs through the model to ensure all the weights are built A = create_optimizer( num_train_steps=UpperCAmelCase__, num_warmup_steps=total_train_steps // 20, init_lr=args.learning_rate, weight_decay_rate=args.weight_decay_rate, ) # Transformers models compute the right loss for their task by default when labels are passed, and will # use this for training unless you specify your own loss function in compile(). model.compile(optimizer=UpperCAmelCase__, metrics=['accuracy'] ) def decode_fn(UpperCAmelCase : Union[str, Any] ): A = { """input_ids""": tf.io.FixedLenFeature(dtype=tf.intaa, shape=(args.max_length,) ), """attention_mask""": tf.io.FixedLenFeature(dtype=tf.intaa, shape=(args.max_length,) ), } return tf.io.parse_single_example(UpperCAmelCase__, UpperCAmelCase__ ) # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can # use their methods in our data pipeline. A = DataCollatorForLanguageModeling( tokenizer=UpperCAmelCase__, mlm_probability=args.mlm_probability, mlm=UpperCAmelCase__, return_tensors='tf' ) def mask_with_collator(UpperCAmelCase : List[str] ): # TF really needs an isin() function A = ( ~tf.cast(batch['attention_mask'], tf.bool ) | (batch["""input_ids"""] == tokenizer.cls_token_id) | (batch["""input_ids"""] == tokenizer.sep_token_id) ) A = data_collator.tf_mask_tokens( batch['input_ids'], vocab_size=len(UpperCAmelCase__ ), mask_token_id=tokenizer.mask_token_id, special_tokens_mask=UpperCAmelCase__, ) return batch A = args.per_replica_batch_size * strategy.num_replicas_in_sync A = prepare_dataset( UpperCAmelCase__, decode_fn=UpperCAmelCase__, mask_fn=UpperCAmelCase__, batch_size=UpperCAmelCase__, shuffle=UpperCAmelCase__, shuffle_buffer_size=args.shuffle_buffer_size, ) A = prepare_dataset( UpperCAmelCase__, decode_fn=UpperCAmelCase__, mask_fn=UpperCAmelCase__, batch_size=UpperCAmelCase__, shuffle=UpperCAmelCase__, ) A = [] if args.hub_model_id: callbacks.append( PushToHubCallback(output_dir=args.output_dir, hub_model_id=args.hub_model_id, tokenizer=UpperCAmelCase__ ) ) model.fit( UpperCAmelCase__, validation_data=UpperCAmelCase__, epochs=args.num_epochs, callbacks=UpperCAmelCase__, ) model.save_pretrained(args.output_dir ) if __name__ == "__main__": lowerCAmelCase_ = parse_args() main(args)
708
from collections.abc import Callable class UpperCamelCase : """simple docstring""" def __init__( self : Tuple ,_SCREAMING_SNAKE_CASE : Callable | None = None ) -> None: '''simple docstring''' # Stores actual heap items. A = [] # Stores indexes of each item for supporting updates and deletion. A = {} # Stores current size of heap. A = 0 # Stores function used to evaluate the score of an item on which basis ordering # will be done. A = key or (lambda _SCREAMING_SNAKE_CASE : x) def A( self : Tuple ,_SCREAMING_SNAKE_CASE : int ) -> int | None: '''simple docstring''' return int((i - 1) / 2 ) if i > 0 else None def A( self : Union[str, Any] ,_SCREAMING_SNAKE_CASE : int ) -> int | None: '''simple docstring''' A = int(2 * i + 1 ) return left if 0 < left < self.size else None def A( self : Union[str, Any] ,_SCREAMING_SNAKE_CASE : int ) -> int | None: '''simple docstring''' A = int(2 * i + 2 ) return right if 0 < right < self.size else None def A( self : List[str] ,_SCREAMING_SNAKE_CASE : int ,_SCREAMING_SNAKE_CASE : int ) -> None: '''simple docstring''' A , A = ( self.pos_map[self.arr[j][0]], self.pos_map[self.arr[i][0]], ) # Then swap the items in the list. A , A = self.arr[j], self.arr[i] def A( self : List[str] ,_SCREAMING_SNAKE_CASE : int ,_SCREAMING_SNAKE_CASE : int ) -> bool: '''simple docstring''' return self.arr[i][1] < self.arr[j][1] def A( self : int ,_SCREAMING_SNAKE_CASE : int ) -> int: '''simple docstring''' A = self._left(_SCREAMING_SNAKE_CASE ) A = self._right(_SCREAMING_SNAKE_CASE ) A = i if left is not None and not self._cmp(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ): A = left if right is not None and not self._cmp(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ): A = right return valid_parent def A( self : Any ,_SCREAMING_SNAKE_CASE : int ) -> None: '''simple docstring''' A = self._parent(_SCREAMING_SNAKE_CASE ) while parent is not None and not self._cmp(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ): self._swap(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) A , A = parent, self._parent(_SCREAMING_SNAKE_CASE ) def A( self : List[Any] ,_SCREAMING_SNAKE_CASE : int ) -> None: '''simple docstring''' A = self._get_valid_parent(_SCREAMING_SNAKE_CASE ) while valid_parent != index: self._swap(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) A , A = valid_parent, self._get_valid_parent(_SCREAMING_SNAKE_CASE ) def A( self : Optional[Any] ,_SCREAMING_SNAKE_CASE : int ,_SCREAMING_SNAKE_CASE : int ) -> None: '''simple docstring''' if item not in self.pos_map: return A = self.pos_map[item] A = [item, self.key(_SCREAMING_SNAKE_CASE )] # Make sure heap is right in both up and down direction. # Ideally only one of them will make any change. self._heapify_up(_SCREAMING_SNAKE_CASE ) self._heapify_down(_SCREAMING_SNAKE_CASE ) def A( self : int ,_SCREAMING_SNAKE_CASE : int ) -> None: '''simple docstring''' if item not in self.pos_map: return A = self.pos_map[item] del self.pos_map[item] A = self.arr[self.size - 1] A = index self.size -= 1 # Make sure heap is right in both up and down direction. Ideally only one # of them will make any change- so no performance loss in calling both. if self.size > index: self._heapify_up(_SCREAMING_SNAKE_CASE ) self._heapify_down(_SCREAMING_SNAKE_CASE ) def A( self : Optional[Any] ,_SCREAMING_SNAKE_CASE : int ,_SCREAMING_SNAKE_CASE : int ) -> None: '''simple docstring''' A = len(self.arr ) if arr_len == self.size: self.arr.append([item, self.key(_SCREAMING_SNAKE_CASE )] ) else: A = [item, self.key(_SCREAMING_SNAKE_CASE )] A = self.size self.size += 1 self._heapify_up(self.size - 1 ) def A( self : str ) -> tuple | None: '''simple docstring''' return self.arr[0] if self.size else None def A( self : Any ) -> tuple | None: '''simple docstring''' A = self.get_top() if top_item_tuple: self.delete_item(top_item_tuple[0] ) return top_item_tuple def snake_case ( ): pass if __name__ == "__main__": import doctest doctest.testmod()
110
0
def lowerCamelCase__ ( __lowerCamelCase : int = 10**12 ): __UpperCAmelCase : Optional[Any] = 1 __UpperCAmelCase : List[str] = 0 __UpperCAmelCase : Any = 1 __UpperCAmelCase : int = 1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(f"""{solution() = }""")
63
from __future__ import annotations a : Optional[Any] = [True] * 1_000_001 a : Union[str, Any] = 2 while i * i <= 1_000_000: if seive[i]: for j in range(i * i, 1_000_001, i): a : Optional[Any] = False i += 1 def lowerCamelCase__ ( __lowerCamelCase : int ): return seive[n] def lowerCamelCase__ ( __lowerCamelCase : int ): return any(digit in """02468""" for digit in str(__lowerCamelCase ) ) def lowerCamelCase__ ( __lowerCamelCase : int = 1000000 ): __UpperCAmelCase : Optional[Any] = [2] # result already includes the number 2. for num in range(3 , limit + 1 , 2 ): if is_prime(__lowerCamelCase ) and not contains_an_even_digit(__lowerCamelCase ): __UpperCAmelCase : Tuple = str(__lowerCamelCase ) __UpperCAmelCase : List[Any] = [int(str_num[j:] + str_num[:j] ) for j in range(len(__lowerCamelCase ) )] if all(is_prime(__lowerCamelCase ) for i in list_nums ): result.append(__lowerCamelCase ) return result def lowerCamelCase__ ( ): return len(find_circular_primes() ) if __name__ == "__main__": print(f"""{len(find_circular_primes()) = }""")
63
1
import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class lowerCAmelCase__ ( a__ , a__ ): """simple docstring""" @register_to_config def __init__( self : Optional[Any] , A__ : Tuple = 1_2_8 , A__ : str = 2_5_6 , A__ : str = 2_0_0_0.0 , A__ : Optional[Any] = 7_6_8 , A__ : Tuple = 1_2 , A__ : int = 1_2 , A__ : List[Any] = 6_4 , A__ : List[str] = 2_0_4_8 , A__ : List[Any] = 0.1 , ) -> Tuple: '''simple docstring''' super().__init__() a__ : int = nn.Sequential( nn.Linear(_A , d_model * 4 , bias=_A ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=_A ) , nn.SiLU() , ) a__ : Any = nn.Embedding(_A , _A ) a__ : Tuple = False a__ : Union[str, Any] = nn.Linear(_A , _A , bias=_A ) a__ : int = nn.Dropout(p=_A ) a__ : int = nn.ModuleList() for lyr_num in range(_A ): # FiLM conditional T5 decoder a__ : Any = DecoderLayer(d_model=_A , d_kv=_A , num_heads=_A , d_ff=_A , dropout_rate=_A ) self.decoders.append(_A ) a__ : Optional[Any] = TaLayerNorm(_A ) a__ : List[str] = nn.Dropout(p=_A ) a__ : Optional[Any] = nn.Linear(_A , _A , bias=_A ) def __lowerCAmelCase ( self : int , A__ : Union[str, Any] , A__ : Optional[Any] ) -> str: '''simple docstring''' a__ : Dict = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def __lowerCAmelCase ( self : List[Any] , A__ : str , A__ : int , A__ : Optional[Any] ) -> str: '''simple docstring''' a__ : Dict = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. a__ : Any = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype ) a__ : Union[str, Any] = self.conditioning_emb(_A ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) a__ : str = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. a__ : Union[str, Any] = torch.broadcast_to( torch.arange(_A , device=decoder_input_tokens.device ) , (batch, seq_length) , ) a__ : Any = self.position_encoding(_A ) a__ : str = self.continuous_inputs_projection(_A ) inputs += position_encodings a__ : int = self.dropout(_A ) # decoder: No padding present. a__ : Union[str, Any] = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. a__ : Optional[Any] = [(x, self.encoder_decoder_mask(_A , _A )) for x, y in encodings_and_masks] # cross attend style: concat encodings a__ : Dict = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) a__ : Tuple = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: a__ : Tuple = lyr( _A , conditioning_emb=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , )[0] a__ : Any = self.decoder_norm(_A ) a__ : List[Any] = self.post_dropout(_A ) a__ : int = self.spec_out(_A ) return spec_out class lowerCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self : str , A__ : Any , A__ : Optional[int] , A__ : Optional[int] , A__ : Tuple , A__ : Any , A__ : Optional[int]=1E-6 ) -> int: '''simple docstring''' super().__init__() a__ : Optional[Any] = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=_A , d_kv=_A , num_heads=_A , dropout_rate=_A ) ) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=_A , d_kv=_A , num_heads=_A , dropout_rate=_A , layer_norm_epsilon=_A , ) ) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=_A , d_ff=_A , dropout_rate=_A , layer_norm_epsilon=_A ) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple , A__ : List[str]=None , A__ : List[Any]=None , A__ : List[Any]=None , A__ : Any=None , A__ : Tuple=None , ) -> Optional[Any]: '''simple docstring''' a__ : Any = self.layer[0]( _A , conditioning_emb=_A , attention_mask=_A , ) if encoder_hidden_states is not None: a__ : Any = torch.where(encoder_attention_mask > 0 , 0 , -1E10 ).to( encoder_hidden_states.dtype ) a__ : str = self.layer[1]( _A , key_value_states=_A , attention_mask=_A , ) # Apply Film Conditional Feed Forward layer a__ : Optional[Any] = self.layer[-1](_A , _A ) return (hidden_states,) class lowerCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self : Optional[Any] , A__ : Optional[Any] , A__ : List[Any] , A__ : List[Any] , A__ : Optional[Any] ) -> Tuple: '''simple docstring''' super().__init__() a__ : Union[str, Any] = TaLayerNorm(_A ) a__ : Any = TaFiLMLayer(in_features=d_model * 4 , out_features=_A ) a__ : Dict = Attention(query_dim=_A , heads=_A , dim_head=_A , out_bias=_A , scale_qk=_A ) a__ : Tuple = nn.Dropout(_A ) def __lowerCAmelCase ( self : Dict , A__ : Tuple , A__ : List[Any]=None , A__ : List[Any]=None , ) -> List[str]: '''simple docstring''' a__ : int = self.layer_norm(_A ) if conditioning_emb is not None: a__ : Union[str, Any] = self.FiLMLayer(_A , _A ) # Self-attention block a__ : Union[str, Any] = self.attention(_A ) a__ : Optional[Any] = hidden_states + self.dropout(_A ) return hidden_states class lowerCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self : Any , A__ : Tuple , A__ : List[Any] , A__ : Any , A__ : List[Any] , A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' super().__init__() a__ : List[str] = Attention(query_dim=_A , heads=_A , dim_head=_A , out_bias=_A , scale_qk=_A ) a__ : Optional[int] = TaLayerNorm(_A , eps=_A ) a__ : Tuple = nn.Dropout(_A ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : int , A__ : Optional[Any]=None , A__ : Union[str, Any]=None , ) -> Optional[int]: '''simple docstring''' a__ : Union[str, Any] = self.layer_norm(_A ) a__ : str = self.attention( _A , encoder_hidden_states=_A , attention_mask=attention_mask.squeeze(1 ) , ) a__ : Any = hidden_states + self.dropout(_A ) return layer_output class lowerCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self : Any , A__ : Optional[Any] , A__ : int , A__ : List[Any] , A__ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' super().__init__() a__ : Optional[int] = TaDenseGatedActDense(d_model=_A , d_ff=_A , dropout_rate=_A ) a__ : Tuple = TaFiLMLayer(in_features=d_model * 4 , out_features=_A ) a__ : Any = TaLayerNorm(_A , eps=_A ) a__ : Union[str, Any] = nn.Dropout(_A ) def __lowerCAmelCase ( self : List[str] , A__ : Tuple , A__ : int=None ) -> List[str]: '''simple docstring''' a__ : int = self.layer_norm(_A ) if conditioning_emb is not None: a__ : Union[str, Any] = self.film(_A , _A ) a__ : str = self.DenseReluDense(_A ) a__ : Tuple = hidden_states + self.dropout(_A ) return hidden_states class lowerCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self : Optional[Any] , A__ : List[str] , A__ : Optional[int] , A__ : Optional[int] ) -> List[Any]: '''simple docstring''' super().__init__() a__ : Union[str, Any] = nn.Linear(_A , _A , bias=_A ) a__ : Any = nn.Linear(_A , _A , bias=_A ) a__ : Union[str, Any] = nn.Linear(_A , _A , bias=_A ) a__ : Union[str, Any] = nn.Dropout(_A ) a__ : int = NewGELUActivation() def __lowerCAmelCase ( self : str , A__ : List[Any] ) -> int: '''simple docstring''' a__ : Tuple = self.act(self.wi_a(_A ) ) a__ : Optional[int] = self.wi_a(_A ) a__ : Union[str, Any] = hidden_gelu * hidden_linear a__ : Dict = self.dropout(_A ) a__ : Dict = self.wo(_A ) return hidden_states class lowerCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self : Optional[int] , A__ : Optional[int] , A__ : Dict=1E-6 ) -> Dict: '''simple docstring''' super().__init__() a__ : Union[str, Any] = nn.Parameter(torch.ones(_A ) ) a__ : Optional[int] = eps def __lowerCAmelCase ( self : List[Any] , A__ : Union[str, Any] ) -> Tuple: '''simple docstring''' a__ : Optional[int] = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=_A ) a__ : List[Any] = hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: a__ : Optional[int] = hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class lowerCAmelCase__ ( nn.Module ): """simple docstring""" def __lowerCAmelCase ( self : Tuple , A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.044_715 * torch.pow(_A , 3.0 )) )) class lowerCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self : List[str] , A__ : Optional[Any] , A__ : Tuple ) -> Dict: '''simple docstring''' super().__init__() a__ : List[str] = nn.Linear(_A , out_features * 2 , bias=_A ) def __lowerCAmelCase ( self : Any , A__ : int , A__ : Any ) -> Union[str, Any]: '''simple docstring''' a__ : List[Any] = self.scale_bias(_A ) a__ : List[Any] = torch.chunk(_A , 2 , -1 ) a__ : List[Any] = x * (1 + scale) + shift return x
716
'''simple docstring''' def __a ( lowerCAmelCase__ : list ): 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__ : List[str] = grid[0] for row_n in range(1 , len(lowerCAmelCase__ ) ): a__ : Tuple = grid[row_n] a__ : Union[str, Any] = fill_row(lowerCAmelCase__ , lowerCAmelCase__ ) a__ : Optional[Any] = grid[row_n] return grid[-1][-1] def __a ( lowerCAmelCase__ : list , lowerCAmelCase__ : list ): 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()
340
0
import argparse import torch from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _a ( lowercase__ : Optional[Any] , lowercase__ : Any , lowercase__ : List[Any] ): '''simple docstring''' if openai_config_file == "": SCREAMING_SNAKE_CASE__ : Optional[int] = OpenAIGPTConfig() else: SCREAMING_SNAKE_CASE__ : int = OpenAIGPTConfig.from_json_file(lowercase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = OpenAIGPTModel(lowercase__ ) # Load weights from numpy load_tf_weights_in_openai_gpt(lowercase__ , lowercase__ , lowercase__ ) # Save pytorch-model SCREAMING_SNAKE_CASE__ : str = pytorch_dump_folder_path + '/' + WEIGHTS_NAME SCREAMING_SNAKE_CASE__ : Dict = pytorch_dump_folder_path + '/' + CONFIG_NAME print(f'''Save PyTorch model to {pytorch_weights_dump_path}''' ) torch.save(model.state_dict() , lowercase__ ) print(f'''Save configuration file to {pytorch_config_dump_path}''' ) with open(lowercase__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--openai_checkpoint_folder_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--openai_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained OpenAI model. \n" "This specifies the model architecture." ), ) SCREAMING_SNAKE_CASE__ : List[str] = parser.parse_args() convert_openai_checkpoint_to_pytorch( args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path )
85
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = ["FNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["FNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FNetForMaskedLM", "FNetForMultipleChoice", "FNetForNextSentencePrediction", "FNetForPreTraining", "FNetForQuestionAnswering", "FNetForSequenceClassification", "FNetForTokenClassification", "FNetLayer", "FNetModel", "FNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _lowerCamelCase = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
714
"""simple docstring""" import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class lowerCamelCase_ ( lowercase ): """simple docstring""" def __init__( self , UpperCAmelCase__ = "▁" , UpperCAmelCase__ = True , UpperCAmelCase__ = "<unk>" , UpperCAmelCase__ = "</s>" , UpperCAmelCase__ = "<pad>" , ): SCREAMING_SNAKE_CASE__ = { "pad": {"id": 0, "token": pad_token}, "eos": {"id": 1, "token": eos_token}, "unk": {"id": 2, "token": unk_token}, } SCREAMING_SNAKE_CASE__ = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): SCREAMING_SNAKE_CASE__ = token_dict["token"] SCREAMING_SNAKE_CASE__ = Tokenizer(Unigram() ) SCREAMING_SNAKE_CASE__ = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(" {2,}" ) , " " ), normalizers.Lowercase(), ] ) SCREAMING_SNAKE_CASE__ = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ ), pre_tokenizers.Digits(individual_digits=UpperCAmelCase__ ), pre_tokenizers.Punctuation(), ] ) SCREAMING_SNAKE_CASE__ = decoders.Metaspace(replacement=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ = TemplateProcessing( single=f'''$A {self.special_tokens["eos"]["token"]}''' , special_tokens=[(self.special_tokens["eos"]["token"], self.special_tokens["eos"]["id"])] , ) SCREAMING_SNAKE_CASE__ = { "model": "SentencePieceUnigram", "replacement": replacement, "add_prefix_space": add_prefix_space, } super().__init__(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase__ ( self , UpperCAmelCase__ , UpperCAmelCase__ = 8000 , UpperCAmelCase__ = True , ): SCREAMING_SNAKE_CASE__ = trainers.UnigramTrainer( vocab_size=UpperCAmelCase__ , special_tokens=self.special_tokens_list , show_progress=UpperCAmelCase__ , ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): SCREAMING_SNAKE_CASE__ = [files] self._tokenizer.train(UpperCAmelCase__ , trainer=UpperCAmelCase__ ) self.add_unk_id() def lowerCAmelCase__ ( self , UpperCAmelCase__ , UpperCAmelCase__ = 8000 , UpperCAmelCase__ = True , ): SCREAMING_SNAKE_CASE__ = trainers.UnigramTrainer( vocab_size=UpperCAmelCase__ , special_tokens=self.special_tokens_list , show_progress=UpperCAmelCase__ , ) self._tokenizer.train_from_iterator(UpperCAmelCase__ , trainer=UpperCAmelCase__ ) self.add_unk_id() def lowerCAmelCase__ ( self ): SCREAMING_SNAKE_CASE__ = json.loads(self._tokenizer.to_str() ) SCREAMING_SNAKE_CASE__ = self.special_tokens["unk"]["id"] SCREAMING_SNAKE_CASE__ = Tokenizer.from_str(json.dumps(UpperCAmelCase__ ) )
112
0
from __future__ import annotations def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase ): __magic_name__ : Tuple =sorted(numsa + numsa ) __magic_name__ , __magic_name__ : Optional[Any] =divmod(len(lowerCamelCase ) , 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() UpperCAmelCase_ : Union[str, Any] = [float(x) for x in input("Enter the elements of first array: ").split()] UpperCAmelCase_ : Dict = [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)}""")
21
import argparse import intel_extension_for_pytorch as ipex import torch from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline __UpperCAmelCase : Optional[Any] = argparse.ArgumentParser("Stable Diffusion script with intel optimization", add_help=False) parser.add_argument("--dpm", action="store_true", help="Enable DPMSolver or not") parser.add_argument("--steps", default=None, type=int, help="Num inference steps") __UpperCAmelCase : Any = parser.parse_args() __UpperCAmelCase : str = "cpu" __UpperCAmelCase : str = "a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings" __UpperCAmelCase : Optional[Any] = "path-to-your-trained-model" __UpperCAmelCase : Dict = StableDiffusionPipeline.from_pretrained(model_id) if args.dpm: __UpperCAmelCase : str = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) __UpperCAmelCase : Optional[Any] = pipe.to(device) # to channels last __UpperCAmelCase : Optional[int] = pipe.unet.to(memory_format=torch.channels_last) __UpperCAmelCase : List[Any] = pipe.vae.to(memory_format=torch.channels_last) __UpperCAmelCase : int = pipe.text_encoder.to(memory_format=torch.channels_last) if pipe.requires_safety_checker: __UpperCAmelCase : Union[str, Any] = pipe.safety_checker.to(memory_format=torch.channels_last) # optimize with ipex __UpperCAmelCase : List[str] = torch.randn(2, 4, 6_4, 6_4) __UpperCAmelCase : Optional[int] = torch.rand(1) * 9_9_9 __UpperCAmelCase : Any = torch.randn(2, 7_7, 7_6_8) __UpperCAmelCase : List[Any] = (sample, timestep, encoder_hidden_status) try: __UpperCAmelCase : Optional[int] = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example) except Exception: __UpperCAmelCase : Tuple = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True) __UpperCAmelCase : List[str] = ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True) __UpperCAmelCase : Union[str, Any] = ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True) if pipe.requires_safety_checker: __UpperCAmelCase : str = ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True) # compute __UpperCAmelCase : Dict = 6_6_6 __UpperCAmelCase : List[Any] = torch.Generator(device).manual_seed(seed) __UpperCAmelCase : List[str] = {"generator": generator} if args.steps is not None: __UpperCAmelCase : Union[str, Any] = args.steps with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa): __UpperCAmelCase : int = pipe(prompt, **generate_kwargs).images[0] # save image image.save("generated.png")
241
0
'''simple docstring''' from manim import * class UpperCAmelCase_ ( lowerCamelCase_ ): """simple docstring""" def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: '''simple docstring''' UpperCamelCase : List[Any] = Rectangle(height=0.5 , width=0.5 ) UpperCamelCase : Optional[Any] = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) UpperCamelCase : int = [mem.copy() for i in range(6 )] UpperCamelCase : Tuple = [mem.copy() for i in range(6 )] UpperCamelCase : Tuple = VGroup(*lowerCamelCase ).arrange(lowerCamelCase , buff=0 ) UpperCamelCase : Optional[Any] = VGroup(*lowerCamelCase ).arrange(lowerCamelCase , buff=0 ) UpperCamelCase : Any = VGroup(lowerCamelCase , lowerCamelCase ).arrange(lowerCamelCase , buff=0 ) UpperCamelCase : Any = Text("CPU" , font_size=24 ) UpperCamelCase : Optional[int] = Group(lowerCamelCase , lowerCamelCase ).arrange(lowerCamelCase , buff=0.5 , aligned_edge=lowerCamelCase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(lowerCamelCase ) UpperCamelCase : Optional[int] = [mem.copy() for i in range(4 )] UpperCamelCase : Optional[Any] = VGroup(*lowerCamelCase ).arrange(lowerCamelCase , buff=0 ) UpperCamelCase : int = Text("GPU" , font_size=24 ) UpperCamelCase : Any = Group(lowerCamelCase , lowerCamelCase ).arrange(lowerCamelCase , buff=0.5 , aligned_edge=lowerCamelCase ) gpu.move_to([-1, -1, 0] ) self.add(lowerCamelCase ) UpperCamelCase : Any = [mem.copy() for i in range(6 )] UpperCamelCase : Tuple = VGroup(*lowerCamelCase ).arrange(lowerCamelCase , buff=0 ) UpperCamelCase : Tuple = Text("Model" , font_size=24 ) UpperCamelCase : Optional[Any] = Group(lowerCamelCase , lowerCamelCase ).arrange(lowerCamelCase , buff=0.5 , aligned_edge=lowerCamelCase ) model.move_to([3, -1.0, 0] ) self.add(lowerCamelCase ) UpperCamelCase : Optional[int] = [] for i, rect in enumerate(lowerCamelCase ): rect.set_stroke(lowerCamelCase ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) UpperCamelCase : str = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(lowerCamelCase , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=lowerCamelCase ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=lowerCamelCase , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=lowerCamelCase , buff=0.0 ) self.add(lowerCamelCase ) cpu_targs.append(lowerCamelCase ) UpperCamelCase : int = [mem.copy() for i in range(6 )] UpperCamelCase : List[Any] = VGroup(*lowerCamelCase ).arrange(lowerCamelCase , buff=0 ) UpperCamelCase : Any = Text("Loaded Checkpoint" , font_size=24 ) UpperCamelCase : Dict = Group(lowerCamelCase , lowerCamelCase ).arrange(lowerCamelCase , aligned_edge=lowerCamelCase , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) UpperCamelCase : Dict = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) UpperCamelCase : Dict = MarkupText( f'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(lowerCamelCase , lowerCamelCase ) UpperCamelCase : Dict = MarkupText( f'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' , font_size=18 , ) blue_text.next_to(lowerCamelCase , DOWN * 2.4 , aligned_edge=key_text.get_left() ) UpperCamelCase : List[Any] = MarkupText( f'''Next, a <i><span fgcolor="{BLUE}">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor="{BLUE}">single shard</span>.''' , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(lowerCamelCase ) , Write(lowerCamelCase ) ) self.play(Write(lowerCamelCase , run_time=1 ) , Create(lowerCamelCase , run_time=1 ) ) UpperCamelCase : int = [] UpperCamelCase : Optional[Any] = [] for i, rect in enumerate(lowerCamelCase ): UpperCamelCase : Dict = fill.copy().set_fill(lowerCamelCase , opacity=0.7 ) target.move_to(lowerCamelCase ) first_animations.append(GrowFromCenter(lowerCamelCase , run_time=1 ) ) UpperCamelCase : Tuple = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(lowerCamelCase , run_time=1.5 ) ) self.play(*lowerCamelCase ) self.play(*lowerCamelCase ) self.wait()
435
'''simple docstring''' import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCAmelCase_ ( lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE = RoCBertTokenizer __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = filter_non_english def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: '''simple docstring''' super().setUp() UpperCamelCase : Optional[int] = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] UpperCamelCase : Union[str, Any] = {} UpperCamelCase : List[Any] = {} for i, value in enumerate(lowerCamelCase ): UpperCamelCase : Any = i UpperCamelCase : List[Any] = i UpperCamelCase : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) UpperCamelCase : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) UpperCamelCase : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(lowerCamelCase , lowerCamelCase , ensure_ascii=lowerCamelCase ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(lowerCamelCase , lowerCamelCase , ensure_ascii=lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: '''simple docstring''' UpperCamelCase : List[str] = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) UpperCamelCase : Dict = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(lowerCamelCase , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(lowerCamelCase ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(lowerCamelCase ) , [5, 6, 2, 5, 7, 8] ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: '''simple docstring''' UpperCamelCase : Dict = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: '''simple docstring''' UpperCamelCase : Tuple = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: '''simple docstring''' UpperCamelCase : int = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase , strip_accents=lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: '''simple docstring''' UpperCamelCase : Any = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase , strip_accents=lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: '''simple docstring''' UpperCamelCase : List[Any] = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: '''simple docstring''' UpperCamelCase : Dict = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: '''simple docstring''' UpperCamelCase : Union[str, Any] = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase , strip_accents=lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: '''simple docstring''' UpperCamelCase : List[str] = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase , strip_accents=lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase : Tuple = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: '''simple docstring''' UpperCamelCase : Optional[int] = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] UpperCamelCase : List[str] = {} for i, token in enumerate(lowerCamelCase ): UpperCamelCase : str = i UpperCamelCase : int = RoCBertWordpieceTokenizer(vocab=lowerCamelCase , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: '''simple docstring''' self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: '''simple docstring''' self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: '''simple docstring''' self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: '''simple docstring''' UpperCamelCase : Optional[Any] = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(lowerCamelCase ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) if self.test_rust_tokenizer: UpperCamelCase : List[str] = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(lowerCamelCase ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase : List[Any] = self.rust_tokenizer_class.from_pretrained(lowerCamelCase , **lowerCamelCase ) UpperCamelCase : List[str] = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' UpperCamelCase : Tuple = tokenizer_r.encode_plus( lowerCamelCase , return_attention_mask=lowerCamelCase , return_token_type_ids=lowerCamelCase , return_offsets_mapping=lowerCamelCase , add_special_tokens=lowerCamelCase , ) UpperCamelCase : int = tokenizer_r.do_lower_case if hasattr(lowerCamelCase , "do_lower_case" ) else False UpperCamelCase : int = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "Allen"), ((21, 23), "##NL"), ((23, 24), "##P"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "allen"), ((21, 23), "##nl"), ((23, 24), "##p"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase : int = ["的", "人", "有"] UpperCamelCase : Any = "".join(lowerCamelCase ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase : Union[str, Any] = True UpperCamelCase : Union[str, Any] = self.tokenizer_class.from_pretrained(lowerCamelCase , **lowerCamelCase ) UpperCamelCase : List[str] = self.rust_tokenizer_class.from_pretrained(lowerCamelCase , **lowerCamelCase ) UpperCamelCase : List[str] = tokenizer_p.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) UpperCamelCase : str = tokenizer_r.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) UpperCamelCase : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(lowerCamelCase ) UpperCamelCase : Optional[int] = tokenizer_p.convert_ids_to_tokens(lowerCamelCase ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(lowerCamelCase , lowerCamelCase ) self.assertListEqual(lowerCamelCase , lowerCamelCase ) UpperCamelCase : Any = False UpperCamelCase : Optional[int] = self.rust_tokenizer_class.from_pretrained(lowerCamelCase , **lowerCamelCase ) UpperCamelCase : Optional[int] = self.tokenizer_class.from_pretrained(lowerCamelCase , **lowerCamelCase ) UpperCamelCase : List[str] = tokenizer_r.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) UpperCamelCase : Any = tokenizer_p.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) UpperCamelCase : Tuple = tokenizer_r.convert_ids_to_tokens(lowerCamelCase ) UpperCamelCase : List[str] = tokenizer_p.convert_ids_to_tokens(lowerCamelCase ) # it is expected that only the first Chinese character is not preceded by "##". UpperCamelCase : List[str] = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(lowerCamelCase ) ] self.assertListEqual(lowerCamelCase , lowerCamelCase ) self.assertListEqual(lowerCamelCase , lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Any: '''simple docstring''' UpperCamelCase : Tuple = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) UpperCamelCase : Optional[Any] = tokenizer.encode("你好" , add_special_tokens=lowerCamelCase ) UpperCamelCase : Any = tokenizer.encode("你是谁" , add_special_tokens=lowerCamelCase ) UpperCamelCase : List[Any] = tokenizer.build_inputs_with_special_tokens(lowerCamelCase ) UpperCamelCase : Optional[int] = tokenizer.build_inputs_with_special_tokens(lowerCamelCase , lowerCamelCase ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: '''simple docstring''' UpperCamelCase : Union[str, Any] = self.get_tokenizers(do_lower_case=lowerCamelCase ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): UpperCamelCase : List[Any] = "你好,你是谁" UpperCamelCase : Union[str, Any] = tokenizer.tokenize(lowerCamelCase ) UpperCamelCase : int = tokenizer.convert_tokens_to_ids(lowerCamelCase ) UpperCamelCase : Optional[int] = tokenizer.convert_tokens_to_shape_ids(lowerCamelCase ) UpperCamelCase : Any = tokenizer.convert_tokens_to_pronunciation_ids(lowerCamelCase ) UpperCamelCase : Optional[int] = tokenizer.prepare_for_model( lowerCamelCase , lowerCamelCase , lowerCamelCase , add_special_tokens=lowerCamelCase ) UpperCamelCase : List[Any] = tokenizer.encode_plus(lowerCamelCase , add_special_tokens=lowerCamelCase ) self.assertEqual(lowerCamelCase , lowerCamelCase )
435
1
'''simple docstring''' from __future__ import annotations import numpy as np def _a ( _lowerCamelCase ) -> tuple[np.ndarray, np.ndarray]: """simple docstring""" __snake_case , __snake_case : Optional[Any] = np.shape(_lowerCamelCase ) if rows != columns: __snake_case : int = ( """'table' has to be of square shaped array but got a """ F'''{rows}x{columns} array:\n{table}''' ) raise ValueError(_lowerCamelCase ) __snake_case : Any = np.zeros((rows, columns) ) __snake_case : List[Any] = np.zeros((rows, columns) ) for i in range(_lowerCamelCase ): for j in range(_lowerCamelCase ): __snake_case : Optional[Any] = sum(lower[i][k] * upper[k][j] for k in range(_lowerCamelCase ) ) if upper[j][j] == 0: raise ArithmeticError("""No LU decomposition exists""" ) __snake_case : Optional[Any] = (table[i][j] - total) / upper[j][j] __snake_case : List[str] = 1 for j in range(_lowerCamelCase , _lowerCamelCase ): __snake_case : Tuple = sum(lower[i][k] * upper[k][j] for k in range(_lowerCamelCase ) ) __snake_case : Optional[int] = table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
26
'''simple docstring''' 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 snake_case__ ( unittest.TestCase): def __init__( self : Optional[Any] , _A : int , _A : List[Any]=7 , _A : Tuple=3 , _A : int=18 , _A : Union[str, Any]=30 , _A : Any=4_00 , _A : List[Any]=True , _A : Optional[int]=None , _A : Optional[Any]=True , _A : Union[str, Any]=None , ) -> Optional[int]: UpperCAmelCase_ : Optional[Any] = size if size is not None else {'''shortest_edge''': 20} UpperCAmelCase_ : Dict = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} UpperCAmelCase_ : List[Any] = parent UpperCAmelCase_ : List[Any] = batch_size UpperCAmelCase_ : Optional[Any] = num_channels UpperCAmelCase_ : Optional[Any] = image_size UpperCAmelCase_ : Union[str, Any] = min_resolution UpperCAmelCase_ : List[str] = max_resolution UpperCAmelCase_ : Union[str, Any] = do_resize UpperCAmelCase_ : Any = size UpperCAmelCase_ : Union[str, Any] = do_center_crop UpperCAmelCase_ : Any = crop_size def A ( self : List[Any] ) -> List[Any]: 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 snake_case__ ( UpperCamelCase , unittest.TestCase): a_ = MobileNetVaImageProcessor if is_vision_available() else None def A ( self : List[Any] ) -> List[str]: UpperCAmelCase_ : Dict = MobileNetVaImageProcessingTester(self ) @property def A ( self : Optional[Any] ) -> Any: return self.image_processor_tester.prepare_image_processor_dict() def A ( self : List[str] ) -> Dict: UpperCAmelCase_ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , '''do_resize''' ) ) self.assertTrue(hasattr(_A , '''size''' ) ) self.assertTrue(hasattr(_A , '''do_center_crop''' ) ) self.assertTrue(hasattr(_A , '''crop_size''' ) ) def A ( self : Tuple ) -> Optional[int]: UpperCAmelCase_ : Any = 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} ) UpperCAmelCase_ : List[str] = 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 ) -> List[str]: pass def A ( self : List[Any] ) -> Optional[Any]: # Initialize image_processing UpperCAmelCase_ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase_ : Optional[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 UpperCAmelCase_ : Union[str, Any] = 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 UpperCAmelCase_ : List[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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def A ( self : str ) -> List[str]: # Initialize image_processing UpperCAmelCase_ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase_ : Any = 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 UpperCAmelCase_ : 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 UpperCAmelCase_ : List[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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def A ( self : Optional[int] ) -> Dict: # Initialize image_processing UpperCAmelCase_ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase_ : Union[str, 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 UpperCAmelCase_ : Any = 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 UpperCAmelCase_ : 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
541
0
def __lowerCAmelCase ()-> Union[str, Any]: """simple docstring""" snake_case_ = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] snake_case_ = 6 snake_case_ = 1 snake_case_ = 1901 snake_case_ = 0 while year < 2001: day += 7 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 snake_case_ = day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 snake_case_ = day - 29 else: if day > days_per_month[month - 1]: month += 1 snake_case_ = day - days_per_month[month - 2] if month > 12: year += 1 snake_case_ = 1 if year < 2001 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
531
import copy import re class lowerCAmelCase_ : '''simple docstring''' __snake_case = "hp" __snake_case = {} __snake_case = None @classmethod def UpperCamelCase__ ( cls , _UpperCAmelCase , _UpperCAmelCase ): snake_case_ = prefix snake_case_ = defaults cls.build_naming_info() @staticmethod def UpperCamelCase__ ( _UpperCAmelCase , _UpperCAmelCase ): if len(_UpperCAmelCase ) == 0: return "" snake_case_ = None if any(char.isdigit() for char in word ): raise Exception(F'''Parameters should not contain numbers: \'{word}\' contains a number''' ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(_UpperCAmelCase ) + 1 ): snake_case_ = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: snake_case_ = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(_UpperCAmelCase ): snake_case_ = '''''' while integer != 0: snake_case_ = chr(ord('''A''' ) + integer % 10 ) + s integer //= 10 return s snake_case_ = 0 while True: snake_case_ = word + '''#''' + int_to_alphabetic(_UpperCAmelCase ) if sword in info["reverse_short_word"]: continue else: snake_case_ = sword break snake_case_ = short_word snake_case_ = word return short_word @staticmethod def UpperCamelCase__ ( _UpperCAmelCase , _UpperCAmelCase ): snake_case_ = param_name.split('''_''' ) snake_case_ = [TrialShortNamer.shortname_for_word(_UpperCAmelCase , _UpperCAmelCase ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name snake_case_ = ['''''', '''_'''] for separator in separators: snake_case_ = separator.join(_UpperCAmelCase ) if shortname not in info["reverse_short_param"]: snake_case_ = shortname snake_case_ = param_name return shortname return param_name @staticmethod def UpperCamelCase__ ( _UpperCAmelCase , _UpperCAmelCase ): snake_case_ = TrialShortNamer.shortname_for_key(_UpperCAmelCase , _UpperCAmelCase ) snake_case_ = short_name snake_case_ = param_name @classmethod def UpperCamelCase__ ( cls ): if cls.NAMING_INFO is not None: return snake_case_ = { '''short_word''': {}, '''reverse_short_word''': {}, '''short_param''': {}, '''reverse_short_param''': {}, } snake_case_ = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(_UpperCAmelCase , _UpperCAmelCase ) snake_case_ = info @classmethod def UpperCamelCase__ ( cls , _UpperCAmelCase ): cls.build_naming_info() assert cls.PREFIX is not None snake_case_ = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(F'''You should provide a default value for the param name {k} with value {v}''' ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue snake_case_ = cls.NAMING_INFO['''short_param'''][k] if isinstance(_UpperCAmelCase , _UpperCAmelCase ): snake_case_ = 1 if v else 0 snake_case_ = '''''' if isinstance(_UpperCAmelCase , (int, float) ) else '''-''' snake_case_ = F'''{key}{sep}{v}''' name.append(_UpperCAmelCase ) return "_".join(_UpperCAmelCase ) @classmethod def UpperCamelCase__ ( cls , _UpperCAmelCase ): snake_case_ = repr[len(cls.PREFIX ) + 1 :] if repr == "": snake_case_ = [] else: snake_case_ = repr.split('''_''' ) snake_case_ = {} for value in values: if "-" in value: snake_case_ , snake_case_ = value.split('''-''' ) else: snake_case_ = re.sub('''[0-9.]''' , '''''' , _UpperCAmelCase ) snake_case_ = float(re.sub('''[^0-9.]''' , '''''' , _UpperCAmelCase ) ) snake_case_ = cls.NAMING_INFO['''reverse_short_param'''][p_k] snake_case_ = p_v for k in cls.DEFAULTS: if k not in parameters: snake_case_ = cls.DEFAULTS[k] return parameters
531
1
'''simple docstring''' from ...processing_utils import ProcessorMixin class __a ( _snake_case ): __UpperCamelCase : str = ['image_processor', 'feature_extractor'] __UpperCamelCase : List[str] = 'TvltImageProcessor' __UpperCamelCase : int = 'TvltFeatureExtractor' def __init__( self : List[str] ,lowerCamelCase : List[Any] ,lowerCamelCase : Any ): '''simple docstring''' super().__init__(image_processor=lowerCamelCase ,feature_extractor=lowerCamelCase ) __SCREAMING_SNAKE_CASE = image_processor __SCREAMING_SNAKE_CASE = feature_extractor def __call__( self : Union[str, Any] ,lowerCamelCase : Union[str, Any]=None ,lowerCamelCase : Optional[Any]=None ,lowerCamelCase : Any=None ,lowerCamelCase : int=None ,lowerCamelCase : Optional[int]=False ,lowerCamelCase : List[Any]=False ,*lowerCamelCase : List[str] ,**lowerCamelCase : Optional[int] ,): '''simple docstring''' if images is None and audio is None: raise ValueError("""You need to specify either an `images` or `audio` input to process.""" ) __SCREAMING_SNAKE_CASE = None if images is not None: __SCREAMING_SNAKE_CASE = self.image_processor(lowerCamelCase ,mask_pixel=lowerCamelCase ,*lowerCamelCase ,**lowerCamelCase ) if images_mixed is not None: __SCREAMING_SNAKE_CASE = self.image_processor(lowerCamelCase ,is_mixed=lowerCamelCase ,*lowerCamelCase ,**lowerCamelCase ) if audio is not None: __SCREAMING_SNAKE_CASE = self.feature_extractor( lowerCamelCase ,*lowerCamelCase ,sampling_rate=lowerCamelCase ,mask_audio=lowerCamelCase ,**lowerCamelCase ) __SCREAMING_SNAKE_CASE = {} if audio is not None: output_dict.update(lowerCamelCase ) if images is not None: output_dict.update(lowerCamelCase ) if images_mixed_dict is not None: output_dict.update(lowerCamelCase ) return output_dict @property def UpperCAmelCase__ ( self : Union[str, Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.image_processor.model_input_names __SCREAMING_SNAKE_CASE = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
109
"""simple docstring""" import inspect import os import unittest from dataclasses import dataclass import torch from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs from accelerate.state import AcceleratorState from accelerate.test_utils import execute_subprocess_async, require_cuda, require_multi_gpu from accelerate.utils import KwargsHandler @dataclass class __lowercase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = 0 __lowerCAmelCase = False __lowerCAmelCase = 3.0 class __lowercase ( unittest.TestCase ): '''simple docstring''' def _lowerCamelCase ( self ): # If no defaults are changed, `to_kwargs` returns an empty dict. self.assertDictEqual(MockClass().to_kwargs() , {} ) self.assertDictEqual(MockClass(a=2 ).to_kwargs() , {'''a''': 2} ) self.assertDictEqual(MockClass(a=2 , b=_UpperCAmelCase ).to_kwargs() , {'''a''': 2, '''b''': True} ) self.assertDictEqual(MockClass(a=2 , c=2.2_5 ).to_kwargs() , {'''a''': 2, '''c''': 2.2_5} ) @require_cuda def _lowerCamelCase ( self ): # If no defaults are changed, `to_kwargs` returns an empty dict. __a : List[Any] = GradScalerKwargs(init_scale=1024 , growth_factor=2 ) AcceleratorState._reset_state() __a : int = Accelerator(mixed_precision='''fp16''' , kwargs_handlers=[scaler_handler] ) print(accelerator.use_fpaa ) __a : Optional[Any] = accelerator.scaler # Check the kwargs have been applied self.assertEqual(scaler._init_scale , 1_0_2_4.0 ) self.assertEqual(scaler._growth_factor , 2.0 ) # Check the other values are at the default self.assertEqual(scaler._backoff_factor , 0.5 ) self.assertEqual(scaler._growth_interval , 2000 ) self.assertEqual(scaler._enabled , _UpperCAmelCase ) @require_multi_gpu def _lowerCamelCase ( self ): __a : Dict = ['''torchrun''', f"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] execute_subprocess_async(_UpperCAmelCase , env=os.environ.copy() ) if __name__ == "__main__": A = DistributedDataParallelKwargs(bucket_cap_mb=15, find_unused_parameters=True) A = Accelerator(kwargs_handlers=[ddp_scaler]) A = torch.nn.Linear(100, 200) A = accelerator.prepare(model) # Check the values changed in kwargs A = '''''' A = model.bucket_bytes_cap // (1_024 * 1_024) if observed_bucket_cap_map != 15: error_msg += F"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n" if model.find_unused_parameters is not True: error_msg += F"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n" # Check the values of the defaults if model.dim != 0: error_msg += F"Default value not respected, should have `0` but found {model.dim}.\n" if model.broadcast_buffers is not True: error_msg += F"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n" if model.gradient_as_bucket_view is not False: error_msg += F"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n" # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
52
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class lowerCAmelCase__ ( A_ , unittest.TestCase ): __a = KandinskyImgaImgPipeline __a = ["""prompt""", """image_embeds""", """negative_image_embeds""", """image"""] __a = [ """prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds""", """image""", ] __a = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """negative_prompt""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __a = False @property def lowercase ( self : List[str] ): return 32 @property def lowercase ( self : List[Any] ): return 32 @property def lowercase ( self : List[str] ): return self.time_input_dim @property def lowercase ( self : Dict ): return self.time_input_dim * 4 @property def lowercase ( self : Union[str, Any] ): return 100 @property def lowercase ( self : Union[str, Any] ): _snake_case = XLMRobertaTokenizerFast.from_pretrained('''YiYiXu/tiny-random-mclip-base''' ) return tokenizer @property def lowercase ( self : Tuple ): torch.manual_seed(0 ) _snake_case = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) _snake_case = MultilingualCLIP(_lowerCamelCase ) _snake_case = text_encoder.eval() return text_encoder @property def lowercase ( self : str ): torch.manual_seed(0 ) _snake_case = { '''in_channels''': 4, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''text_image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''text_image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } _snake_case = UNetaDConditionModel(**_lowerCamelCase ) return model @property def lowercase ( self : Optional[Any] ): return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def lowercase ( self : str ): torch.manual_seed(0 ) _snake_case = VQModel(**self.dummy_movq_kwargs ) return model def lowercase ( self : Optional[Any] ): _snake_case = self.dummy_text_encoder _snake_case = self.dummy_tokenizer _snake_case = self.dummy_unet _snake_case = self.dummy_movq _snake_case = { '''num_train_timesteps''': 1000, '''beta_schedule''': '''linear''', '''beta_start''': 0.0_0_0_8_5, '''beta_end''': 0.0_1_2, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } _snake_case = DDIMScheduler(**_lowerCamelCase ) _snake_case = { '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def lowercase ( self : Optional[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Any=0 ): _snake_case = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) _snake_case = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(_lowerCamelCase ) # create init_image _snake_case = floats_tensor((1, 3, 64, 64) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) _snake_case = image.cpu().permute(0 , 2 , 3 , 1 )[0] _snake_case = Image.fromarray(np.uinta(_lowerCamelCase ) ).convert('''RGB''' ).resize((256, 256) ) if str(_lowerCamelCase ).startswith('''mps''' ): _snake_case = torch.manual_seed(_lowerCamelCase ) else: _snake_case = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) _snake_case = { '''prompt''': '''horse''', '''image''': init_image, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 10, '''guidance_scale''': 7.0, '''strength''': 0.2, '''output_type''': '''np''', } return inputs def lowercase ( self : Optional[Any] ): _snake_case = '''cpu''' _snake_case = self.get_dummy_components() _snake_case = self.pipeline_class(**_lowerCamelCase ) _snake_case = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) _snake_case = pipe(**self.get_dummy_inputs(_lowerCamelCase ) ) _snake_case = output.images _snake_case = pipe( **self.get_dummy_inputs(_lowerCamelCase ) , return_dict=_lowerCamelCase , )[0] _snake_case = image[0, -3:, -3:, -1] _snake_case = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _snake_case = np.array( [0.6_1_4_7_4_9_4_3, 0.6_0_7_3_5_3_9, 0.4_3_3_0_8_5_4_4, 0.5_9_2_8_2_6_9, 0.4_7_4_9_3_5_9_5, 0.4_6_7_5_5_9_7_3, 0.4_6_1_3_8_3_8, 0.4_5_3_6_8_7_9_7, 0.5_0_1_1_9_2_3_3] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def lowercase ( self : int ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase ( self : Union[str, Any] ): _snake_case = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/kandinsky_img2img_frog.npy''' ) _snake_case = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) _snake_case = '''A red cartoon frog, 4k''' _snake_case = KandinskyPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-1-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(_lowerCamelCase ) _snake_case = KandinskyImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-1''' , torch_dtype=torch.floataa ) _snake_case = pipeline.to(_lowerCamelCase ) pipeline.set_progress_bar_config(disable=_lowerCamelCase ) _snake_case = torch.Generator(device='''cpu''' ).manual_seed(0 ) _snake_case , _snake_case = pipe_prior( _lowerCamelCase , generator=_lowerCamelCase , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() _snake_case = pipeline( _lowerCamelCase , image=_lowerCamelCase , image_embeds=_lowerCamelCase , negative_image_embeds=_lowerCamelCase , generator=_lowerCamelCase , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type='''np''' , ) _snake_case = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_lowerCamelCase , _lowerCamelCase )
702
"""simple docstring""" def _UpperCAmelCase ( __lowerCamelCase : int ) -> bool: if num < 0: return False _snake_case = num _snake_case = 0 while num > 0: _snake_case = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
430
0
def _SCREAMING_SNAKE_CASE ( lowercase : int , lowercase : int ): '''simple docstring''' if a < 0 or b < 0: raise ValueError('the value of both inputs must be positive' ) lowerCamelCase_ = str(bin(lowercase ) )[2:] # remove the leading "0b" lowerCamelCase_ = str(bin(lowercase ) )[2:] lowerCamelCase_ = max(len(lowercase ) , len(lowercase ) ) return "0b" + "".join( str(int('1' in (char_a, char_b) ) ) for char_a, char_b in zip(a_binary.zfill(lowercase ) , b_binary.zfill(lowercase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
70
import argparse import json import subprocess def _SCREAMING_SNAKE_CASE ( lowercase : Dict , lowercase : List[str] ): '''simple docstring''' lowerCamelCase_ = [] lowerCamelCase_ = ( f"""curl -H \"Accept: application/vnd.github+json\" -H \"Authorization: Bearer {token}\"""" ' https://api.github.com/repos/huggingface/transformers/actions/runners' ) lowerCamelCase_ = subprocess.run(lowercase , shell=lowercase , stdout=subprocess.PIPE ) lowerCamelCase_ = output.stdout.decode('utf-8' ) lowerCamelCase_ = json.loads(lowercase ) lowerCamelCase_ = status['runners'] for runner in runners: if runner["name"] in target_runners: if runner["status"] == "offline": offline_runners.append(lowercase ) # save the result so we can report them on Slack with open('offline_runners.txt' , 'w' ) as fp: fp.write(json.dumps(lowercase ) ) if len(lowercase ) > 0: lowerCamelCase_ = '\n'.join([x['name'] for x in offline_runners] ) raise ValueError(f"""The following runners are offline:\n{failed}""" ) if __name__ == "__main__": def _SCREAMING_SNAKE_CASE ( lowercase : List[str] ): '''simple docstring''' return values.split(',' ) lowerCamelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--target_runners", default=None, type=list_str, required=True, help="Comma-separated list of runners to check status.", ) parser.add_argument( "--token", default=None, type=str, required=True, help="A token that has actions:read permission." ) lowerCamelCase : Optional[int] = parser.parse_args() get_runner_status(args.target_runners, args.token)
70
1
"""simple docstring""" import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def UpperCAmelCase ( A__: List[str] , A__: Tuple ) -> int: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer __lowerCamelCase : Dict = flax_key_tuple[:-1] + ('weight',) __lowerCamelCase : Optional[int] = torch.permute(A__ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(A__ ): # linear layer __lowerCamelCase : int = flax_key_tuple[:-1] + ('weight',) __lowerCamelCase : Tuple = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: __lowerCamelCase : List[str] = flax_key_tuple[:-1] + ('weight',) return flax_key_tuple, flax_tensor def UpperCAmelCase ( A__: Union[str, Any] , A__: Union[str, Any] , A__: Union[str, Any] ) -> List[Any]: if "metadata" in layer: __lowerCamelCase : Dict = layer.split('metadata' ) __lowerCamelCase : Dict = ''.join(split_layer[0] )[:-1] __lowerCamelCase : Tuple = [tuple(('metadata' + split_layer[1]).split('/' ) )] elif "kvstore" in layer: __lowerCamelCase : Optional[int] = layer.split('kvstore' ) __lowerCamelCase : str = ''.join(split_layer[0] )[:-1] __lowerCamelCase : Tuple = [tuple(('kvstore' + split_layer[1]).split('/' ) )] else: __lowerCamelCase : str = layer.split('/' ) __lowerCamelCase : Optional[Any] = '/'.join(split_layer[:-1] ) __lowerCamelCase : str = (split_layer[-1],) if "kvstore/path" in layer: __lowerCamelCase : Union[str, Any] = f'''{switch_checkpoint_path}/{checkpoint_info[layer]}''' elif "kvstore/driver" in layer: __lowerCamelCase : int = 'file' else: __lowerCamelCase : Any = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def UpperCAmelCase ( A__: List[Any] , A__: int ) -> Union[str, Any]: __lowerCamelCase : List[Any] = rename_keys(A__ ) __lowerCamelCase : Optional[Any] = {} for k, v in current_block.items(): __lowerCamelCase : List[Any] = v __lowerCamelCase : Any = new_current_block torch.save(A__ , A__ ) def UpperCAmelCase ( A__: List[str] , A__: Tuple , A__: Union[str, Any] , A__: int , A__: str = WEIGHTS_NAME ) -> List[Any]: __lowerCamelCase : Any = convert_file_size_to_int(A__ ) __lowerCamelCase : Tuple = [] __lowerCamelCase : List[str] = {} __lowerCamelCase : Tuple = 0 __lowerCamelCase : str = 0 os.makedirs(A__ , exist_ok=A__ ) with gfile.GFile(switch_checkpoint_path + '/checkpoint' , 'rb' ) as fp: __lowerCamelCase : Dict = serialization.msgpack_restore(fp.read() )['optimizer']['target'] __lowerCamelCase : Optional[Any] = flatten_dict(A__ , sep='/' ) __lowerCamelCase : Any = {} for layer in checkpoint_info.keys(): __lowerCamelCase : Dict = get_key_and_tensorstore_dict( A__ , A__ , A__ ) if curr_real_layer_name in all_layers: __lowerCamelCase : Optional[int] = content else: __lowerCamelCase : Optional[Any] = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file __lowerCamelCase : Dict = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() __lowerCamelCase : str = torch.tensor(A__ ) __lowerCamelCase : List[str] = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts __lowerCamelCase : List[Any] = rename_base_flax_keys(tuple(key.split('/' ) ) , A__ ) __lowerCamelCase : str = '/'.join(A__ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: __lowerCamelCase : Tuple = os.path.join( A__ , weights_name.replace('.bin' , f'''-{len(A__ )+1:05d}-of-???.bin''' ) ) rename_and_save_block(A__ , A__ ) sharded_state_dicts.append(current_block.keys() ) del current_block __lowerCamelCase : Optional[Any] = {} __lowerCamelCase : Optional[Any] = 0 __lowerCamelCase : Union[str, Any] = raw_weights.to(getattr(A__ , A__ ) ) current_block_size += weight_size total_size += weight_size # Add the last block __lowerCamelCase : List[str] = os.path.join(A__ , weights_name.replace('.bin' , f'''-{len(A__ )+1:05d}-of-???.bin''' ) ) rename_and_save_block(A__ , A__ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(A__ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index __lowerCamelCase : Union[str, Any] = {} __lowerCamelCase : int = {} for idx, shard in enumerate(A__ ): __lowerCamelCase : Tuple = weights_name.replace( '.bin' , f'''-{idx+1:05d}-of-{len(A__ ):05d}.bin''' ) # len(sharded_state_dicts):05d} __lowerCamelCase : Union[str, Any] = os.path.join(A__ , weights_name.replace('.bin' , f'''-{idx+1:05d}-of-???.bin''' ) ) os.rename(A__ , os.path.join(A__ , A__ ) ) __lowerCamelCase : Dict = shard for key in shard: __lowerCamelCase : str = shard_file # Add the metadata __lowerCamelCase : List[str] = {'total_size': total_size} __lowerCamelCase : str = {'metadata': metadata, 'weight_map': weight_map} with open(os.path.join(A__ , A__ ) , 'w' , encoding='utf-8' ) as f: __lowerCamelCase : Union[str, Any] = json.dumps(A__ , indent=2 , sort_keys=A__ ) + '\n' f.write(A__ ) return metadata, index if __name__ == "__main__": a_ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--switch_t5x_checkpoint_path''', default='''/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600''', type=str, required=False, help='''Path to a directory containing a folder per layer. Follows the original Google format.''', ) parser.add_argument('''--max_shard_size''', default='''10GB''', required=False, help='''Max shard size''') parser.add_argument('''--dtype''', default='''bfloat16''', type=str, required=False, help='''dtype of the saved model''') parser.add_argument( '''--pytorch_dump_folder_path''', default='''/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted''', type=str, required=False, help='''Path to the output pytorch model.''', ) a_ : Optional[Any] = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def UpperCAmelCase ( ) -> List[Any]: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer __lowerCamelCase : str = SwitchTransformersConfig.from_pretrained('google/switch-base-8' ) config.save_pretrained('/home/arthur_huggingface_co/transformers/switch_converted' ) __lowerCamelCase : str = SwitchTransformersForConditionalGeneration.from_pretrained( '/home/arthur_huggingface_co/transformers/switch_converted' , device_map='auto' ) __lowerCamelCase : Dict = TaTokenizer.from_pretrained('t5-small' ) __lowerCamelCase : List[Any] = 'A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.' __lowerCamelCase : Any = tokenizer(A__ , return_tensors='pt' ).input_ids __lowerCamelCase : List[Any] = model.generate(A__ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
710
"""simple docstring""" import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig a_ : Tuple = logging.get_logger(__name__) # General docstring a_ : List[str] = '''PoolFormerConfig''' # Base docstring a_ : Optional[Any] = '''sail/poolformer_s12''' a_ : List[Any] = [1, 5_12, 7, 7] # Image classification docstring a_ : Any = '''sail/poolformer_s12''' a_ : Optional[int] = '''tabby, tabby cat''' a_ : Optional[Any] = [ '''sail/poolformer_s12''', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def UpperCAmelCase ( A__: Optional[Any] , A__: float = 0.0 , A__: bool = False ) -> Tuple: if drop_prob == 0.0 or not training: return input __lowerCamelCase : Dict = 1 - drop_prob __lowerCamelCase : List[Any] = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets __lowerCamelCase : List[Any] = keep_prob + torch.rand(A__ , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize __lowerCamelCase : Any = input.div(A__ ) * random_tensor return output class __lowercase( nn.Module ): '''simple docstring''' def __init__( self , __a = None ): super().__init__() __lowerCamelCase : int = drop_prob def snake_case_ ( self , __a ): return drop_path(__a , self.drop_prob , self.training ) def snake_case_ ( self ): return "p={}".format(self.drop_prob ) class __lowercase( nn.Module ): '''simple docstring''' def __init__( self , __a , __a , __a , __a , __a , __a=None ): super().__init__() __lowerCamelCase : int = patch_size if isinstance(__a , collections.abc.Iterable ) else (patch_size, patch_size) __lowerCamelCase : int = stride if isinstance(__a , collections.abc.Iterable ) else (stride, stride) __lowerCamelCase : Optional[int] = padding if isinstance(__a , collections.abc.Iterable ) else (padding, padding) __lowerCamelCase : Optional[Any] = nn.Convad(__a , __a , kernel_size=__a , stride=__a , padding=__a ) __lowerCamelCase : List[str] = norm_layer(__a ) if norm_layer else nn.Identity() def snake_case_ ( self , __a ): __lowerCamelCase : List[Any] = self.projection(__a ) __lowerCamelCase : Dict = self.norm(__a ) return embeddings class __lowercase( nn.GroupNorm ): '''simple docstring''' def __init__( self , __a , **__a ): super().__init__(1 , __a , **__a ) class __lowercase( nn.Module ): '''simple docstring''' def __init__( self , __a ): super().__init__() __lowerCamelCase : str = nn.AvgPoolad(__a , stride=1 , padding=pool_size // 2 , count_include_pad=__a ) def snake_case_ ( self , __a ): return self.pool(__a ) - hidden_states class __lowercase( nn.Module ): '''simple docstring''' def __init__( self , __a , __a , __a , __a ): super().__init__() __lowerCamelCase : Any = nn.Convad(__a , __a , 1 ) __lowerCamelCase : Dict = nn.Convad(__a , __a , 1 ) __lowerCamelCase : List[Any] = PoolFormerDropPath(__a ) if isinstance(config.hidden_act , __a ): __lowerCamelCase : List[str] = ACTaFN[config.hidden_act] else: __lowerCamelCase : str = config.hidden_act def snake_case_ ( self , __a ): __lowerCamelCase : int = self.conva(__a ) __lowerCamelCase : Dict = self.act_fn(__a ) __lowerCamelCase : List[str] = self.drop(__a ) __lowerCamelCase : int = self.conva(__a ) __lowerCamelCase : str = self.drop(__a ) return hidden_states class __lowercase( nn.Module ): '''simple docstring''' def __init__( self , __a , __a , __a , __a , __a , __a ): super().__init__() __lowerCamelCase : Tuple = PoolFormerPooling(__a ) __lowerCamelCase : Union[str, Any] = PoolFormerOutput(__a , __a , __a , __a ) __lowerCamelCase : List[Any] = PoolFormerGroupNorm(__a ) __lowerCamelCase : List[Any] = PoolFormerGroupNorm(__a ) # Useful for training neural nets __lowerCamelCase : Any = PoolFormerDropPath(__a ) if drop_path > 0.0 else nn.Identity() __lowerCamelCase : Tuple = config.use_layer_scale if config.use_layer_scale: __lowerCamelCase : List[str] = nn.Parameter( config.layer_scale_init_value * torch.ones((__a) ) , requires_grad=__a ) __lowerCamelCase : Optional[int] = nn.Parameter( config.layer_scale_init_value * torch.ones((__a) ) , requires_grad=__a ) def snake_case_ ( self , __a ): if self.use_layer_scale: __lowerCamelCase : Union[str, Any] = self.pooling(self.before_norm(__a ) ) __lowerCamelCase : Any = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection __lowerCamelCase : Optional[Any] = hidden_states + self.drop_path(__a ) __lowerCamelCase : Tuple = () __lowerCamelCase : Optional[Any] = self.output(self.after_norm(__a ) ) __lowerCamelCase : List[Any] = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection __lowerCamelCase : List[Any] = hidden_states + self.drop_path(__a ) __lowerCamelCase : Optional[Any] = (output,) + outputs return outputs else: __lowerCamelCase : Tuple = self.drop_path(self.pooling(self.before_norm(__a ) ) ) # First residual connection __lowerCamelCase : List[str] = pooling_output + hidden_states __lowerCamelCase : int = () # Second residual connection inside the PoolFormerOutput block __lowerCamelCase : List[str] = self.drop_path(self.output(self.after_norm(__a ) ) ) __lowerCamelCase : str = hidden_states + layer_output __lowerCamelCase : int = (output,) + outputs return outputs class __lowercase( nn.Module ): '''simple docstring''' def __init__( self , __a ): super().__init__() __lowerCamelCase : int = config # stochastic depth decay rule __lowerCamelCase : int = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings __lowerCamelCase : List[str] = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) __lowerCamelCase : Optional[int] = nn.ModuleList(__a ) # Transformer blocks __lowerCamelCase : Any = [] __lowerCamelCase : int = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers __lowerCamelCase : Optional[int] = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( __a , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(__a ) ) __lowerCamelCase : str = nn.ModuleList(__a ) def snake_case_ ( self , __a , __a=False , __a=True ): __lowerCamelCase : Union[str, Any] = () if output_hidden_states else None __lowerCamelCase : int = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): __lowerCamelCase , __lowerCamelCase : Any = layers # Get patch embeddings from hidden_states __lowerCamelCase : Any = embedding_layer(__a ) # Send the embeddings through the blocks for _, blk in enumerate(__a ): __lowerCamelCase : Optional[int] = blk(__a ) __lowerCamelCase : Tuple = layer_outputs[0] if output_hidden_states: __lowerCamelCase : Union[str, Any] = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=__a , hidden_states=__a ) class __lowercase( lowercase__ ): '''simple docstring''' __a : Tuple = PoolFormerConfig __a : Tuple = 'poolformer' __a : Optional[int] = 'pixel_values' __a : Optional[Any] = True def snake_case_ ( self , __a ): if isinstance(__a , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(__a , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def snake_case_ ( self , __a , __a=False ): if isinstance(__a , __a ): __lowerCamelCase : Union[str, Any] = value a_ : Union[str, Any] = R''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' a_ : List[str] = R''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`PoolFormerImageProcessor.__call__`] for details. ''' @add_start_docstrings( 'The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.' , lowercase__ , ) class __lowercase( lowercase__ ): '''simple docstring''' def __init__( self , __a ): super().__init__(__a ) __lowerCamelCase : Optional[Any] = config __lowerCamelCase : Any = PoolFormerEncoder(__a ) # Initialize weights and apply final processing self.post_init() def snake_case_ ( self ): return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(__a ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__a , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def snake_case_ ( self , __a = None , __a = None , __a = None , ): __lowerCamelCase : Union[str, Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Dict = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) __lowerCamelCase : Any = self.encoder( __a , output_hidden_states=__a , return_dict=__a , ) __lowerCamelCase : int = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=__a , hidden_states=encoder_outputs.hidden_states , ) class __lowercase( nn.Module ): '''simple docstring''' def __init__( self , __a ): super().__init__() __lowerCamelCase : Optional[Any] = nn.Linear(config.hidden_size , config.hidden_size ) def snake_case_ ( self , __a ): __lowerCamelCase : List[Any] = self.dense(__a ) return output @add_start_docstrings( '\n PoolFormer Model transformer with an image classification head on top\n ' , lowercase__ , ) class __lowercase( lowercase__ ): '''simple docstring''' def __init__( self , __a ): super().__init__(__a ) __lowerCamelCase : str = config.num_labels __lowerCamelCase : Optional[Any] = PoolFormerModel(__a ) # Final norm __lowerCamelCase : str = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head __lowerCamelCase : Optional[Any] = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__a ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def snake_case_ ( self , __a = None , __a = None , __a = None , __a = None , ): __lowerCamelCase : Any = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Tuple = self.poolformer( __a , output_hidden_states=__a , return_dict=__a , ) __lowerCamelCase : int = outputs[0] __lowerCamelCase : Optional[int] = self.classifier(self.norm(__a ).mean([-2, -1] ) ) __lowerCamelCase : Union[str, Any] = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __lowerCamelCase : Any = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __lowerCamelCase : Any = 'single_label_classification' else: __lowerCamelCase : Optional[Any] = 'multi_label_classification' if self.config.problem_type == "regression": __lowerCamelCase : int = MSELoss() if self.num_labels == 1: __lowerCamelCase : Optional[Any] = loss_fct(logits.squeeze() , labels.squeeze() ) else: __lowerCamelCase : Optional[Any] = loss_fct(__a , __a ) elif self.config.problem_type == "single_label_classification": __lowerCamelCase : Tuple = CrossEntropyLoss() __lowerCamelCase : int = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": __lowerCamelCase : List[Any] = BCEWithLogitsLoss() __lowerCamelCase : Optional[Any] = loss_fct(__a , __a ) if not return_dict: __lowerCamelCase : Optional[Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=__a , logits=__a , hidden_states=outputs.hidden_states )
263
0
"""simple docstring""" import collections import inspect import unittest from transformers import FocalNetConfig 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, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, ) from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A__ : '''simple docstring''' def __init__( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: Optional[int]=13 , _SCREAMING_SNAKE_CASE: Optional[Any]=32 , _SCREAMING_SNAKE_CASE: int=2 , _SCREAMING_SNAKE_CASE: Union[str, Any]=3 , _SCREAMING_SNAKE_CASE: List[str]=16 , _SCREAMING_SNAKE_CASE: Union[str, Any]=[32, 64, 128] , _SCREAMING_SNAKE_CASE: Dict=[1, 2, 1] , _SCREAMING_SNAKE_CASE: Optional[Any]=[2, 2, 4] , _SCREAMING_SNAKE_CASE: str=2 , _SCREAMING_SNAKE_CASE: Optional[int]=2.0 , _SCREAMING_SNAKE_CASE: Union[str, Any]=True , _SCREAMING_SNAKE_CASE: Dict=0.0 , _SCREAMING_SNAKE_CASE: Optional[int]=0.0 , _SCREAMING_SNAKE_CASE: Dict=0.1 , _SCREAMING_SNAKE_CASE: Dict="gelu" , _SCREAMING_SNAKE_CASE: int=False , _SCREAMING_SNAKE_CASE: Union[str, Any]=True , _SCREAMING_SNAKE_CASE: List[str]=0.02 , _SCREAMING_SNAKE_CASE: Union[str, Any]=1e-5 , _SCREAMING_SNAKE_CASE: str=True , _SCREAMING_SNAKE_CASE: Union[str, Any]=None , _SCREAMING_SNAKE_CASE: str=True , _SCREAMING_SNAKE_CASE: Optional[int]=10 , _SCREAMING_SNAKE_CASE: Optional[int]=8 , _SCREAMING_SNAKE_CASE: List[str]=["stage1", "stage2"] , _SCREAMING_SNAKE_CASE: Optional[int]=[1, 2] , ) -> List[Any]: """simple docstring""" __lowerCAmelCase : Optional[int] = parent __lowerCAmelCase : Any = batch_size __lowerCAmelCase : Union[str, Any] = image_size __lowerCAmelCase : str = patch_size __lowerCAmelCase : List[str] = num_channels __lowerCAmelCase : List[str] = embed_dim __lowerCAmelCase : int = hidden_sizes __lowerCAmelCase : str = depths __lowerCAmelCase : Union[str, Any] = num_heads __lowerCAmelCase : Tuple = window_size __lowerCAmelCase : str = mlp_ratio __lowerCAmelCase : Any = qkv_bias __lowerCAmelCase : int = hidden_dropout_prob __lowerCAmelCase : List[str] = attention_probs_dropout_prob __lowerCAmelCase : Optional[int] = drop_path_rate __lowerCAmelCase : Any = hidden_act __lowerCAmelCase : int = use_absolute_embeddings __lowerCAmelCase : Union[str, Any] = patch_norm __lowerCAmelCase : Tuple = layer_norm_eps __lowerCAmelCase : Optional[int] = initializer_range __lowerCAmelCase : Optional[Any] = is_training __lowerCAmelCase : Union[str, Any] = scope __lowerCAmelCase : Any = use_labels __lowerCAmelCase : Optional[Any] = type_sequence_label_size __lowerCAmelCase : Tuple = encoder_stride __lowerCAmelCase : Optional[Any] = out_features __lowerCAmelCase : List[Any] = out_indices def _SCREAMING_SNAKE_CASE ( self: List[str]) -> List[str]: """simple docstring""" __lowerCAmelCase : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __lowerCAmelCase : List[Any] = None if self.use_labels: __lowerCAmelCase : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size) __lowerCAmelCase : Dict = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self: Optional[int]) -> Union[str, Any]: """simple docstring""" return FocalNetConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , hidden_sizes=self.hidden_sizes , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def _SCREAMING_SNAKE_CASE ( self: Dict , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Tuple) -> Tuple: """simple docstring""" __lowerCAmelCase : List[str] = FocalNetModel(config=_lowerCamelCase) model.to(_lowerCamelCase) model.eval() __lowerCAmelCase : Union[str, Any] = model(_lowerCamelCase) __lowerCAmelCase : int = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1)) __lowerCAmelCase : Dict = int(config.embed_dim * 2 ** (len(config.depths) - 1)) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim)) def _SCREAMING_SNAKE_CASE ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: List[Any]) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : Optional[Any] = FocalNetBackbone(config=_lowerCamelCase) model.to(_lowerCamelCase) model.eval() __lowerCAmelCase : str = model(_lowerCamelCase) # 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.image_size, 8, 8]) # 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 __lowerCAmelCase : Optional[Any] = None __lowerCAmelCase : Optional[int] = FocalNetBackbone(config=_lowerCamelCase) model.to(_lowerCamelCase) model.eval() __lowerCAmelCase : int = model(_lowerCamelCase) # verify feature maps self.parent.assertEqual(len(result.feature_maps) , 1) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.image_size * 2, 4, 4]) # verify channels self.parent.assertEqual(len(model.channels) , 1) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]]) def _SCREAMING_SNAKE_CASE ( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: List[str] , _SCREAMING_SNAKE_CASE: Union[str, Any] , _SCREAMING_SNAKE_CASE: int) -> List[Any]: """simple docstring""" __lowerCAmelCase : Optional[int] = FocalNetForMaskedImageModeling(config=_lowerCamelCase) model.to(_lowerCamelCase) model.eval() __lowerCAmelCase : List[str] = model(_lowerCamelCase) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size)) # test greyscale images __lowerCAmelCase : Optional[int] = 1 __lowerCAmelCase : List[Any] = FocalNetForMaskedImageModeling(_lowerCamelCase) model.to(_lowerCamelCase) model.eval() __lowerCAmelCase : Tuple = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __lowerCAmelCase : Tuple = model(_lowerCamelCase) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size)) def _SCREAMING_SNAKE_CASE ( self: List[Any] , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: List[str] , _SCREAMING_SNAKE_CASE: Any) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : Any = self.type_sequence_label_size __lowerCAmelCase : Tuple = FocalNetForImageClassification(_lowerCamelCase) model.to(_lowerCamelCase) model.eval() __lowerCAmelCase : Union[str, Any] = model(_lowerCamelCase , labels=_lowerCamelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) # test greyscale images __lowerCAmelCase : Tuple = 1 __lowerCAmelCase : Optional[Any] = FocalNetForImageClassification(_lowerCamelCase) model.to(_lowerCamelCase) model.eval() __lowerCAmelCase : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __lowerCAmelCase : Tuple = model(_lowerCamelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def _SCREAMING_SNAKE_CASE ( self: Dict) -> Tuple: """simple docstring""" __lowerCAmelCase : Tuple = self.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Optional[Any] = config_and_inputs __lowerCAmelCase : List[Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class A__ ( __a , __a , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE = ( ( FocalNetModel, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetBackbone, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE = ( {'feature-extraction': FocalNetModel, 'image-classification': FocalNetForImageClassification} if is_torch_available() else {} ) SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False def _SCREAMING_SNAKE_CASE ( self: Dict) -> Optional[int]: """simple docstring""" __lowerCAmelCase : Any = FocalNetModelTester(self) __lowerCAmelCase : str = ConfigTester(self , config_class=_lowerCamelCase , embed_dim=37 , has_text_modality=_lowerCamelCase) def _SCREAMING_SNAKE_CASE ( self: Any) -> Optional[int]: """simple docstring""" 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 _SCREAMING_SNAKE_CASE ( self: int) -> List[str]: """simple docstring""" return def _SCREAMING_SNAKE_CASE ( self: Optional[Any]) -> Optional[int]: """simple docstring""" __lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase) def _SCREAMING_SNAKE_CASE ( self: Optional[int]) -> str: """simple docstring""" __lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_lowerCamelCase) def _SCREAMING_SNAKE_CASE ( self: Union[str, Any]) -> Tuple: """simple docstring""" __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCamelCase) def _SCREAMING_SNAKE_CASE ( self: Any) -> Optional[int]: """simple docstring""" __lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase) @unittest.skip(reason="FocalNet does not use inputs_embeds") def _SCREAMING_SNAKE_CASE ( self: Any) -> int: """simple docstring""" pass @unittest.skip(reason="FocalNet does not use feedforward chunking") def _SCREAMING_SNAKE_CASE ( self: int) -> str: """simple docstring""" pass def _SCREAMING_SNAKE_CASE ( self: Optional[Any]) -> List[str]: """simple docstring""" __lowerCAmelCase , __lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: __lowerCAmelCase : List[str] = model_class(_lowerCamelCase) self.assertIsInstance(model.get_input_embeddings() , (nn.Module)) __lowerCAmelCase : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCamelCase , nn.Linear)) def _SCREAMING_SNAKE_CASE ( self: int) -> str: """simple docstring""" __lowerCAmelCase , __lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: __lowerCAmelCase : Optional[Any] = model_class(_lowerCamelCase) __lowerCAmelCase : Any = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCAmelCase : Tuple = [*signature.parameters.keys()] __lowerCAmelCase : str = ["pixel_values"] self.assertListEqual(arg_names[:1] , _lowerCamelCase) def _SCREAMING_SNAKE_CASE ( self: List[Any] , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: Tuple) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : Optional[Any] = model_class(_lowerCamelCase) model.to(_lowerCamelCase) model.eval() with torch.no_grad(): __lowerCAmelCase : str = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase)) __lowerCAmelCase : List[str] = outputs.hidden_states __lowerCAmelCase : List[Any] = getattr( self.model_tester , "expected_num_hidden_layers" , len(self.model_tester.depths) + 1) self.assertEqual(len(_lowerCamelCase) , _lowerCamelCase) # FocalNet has a different seq_length __lowerCAmelCase : Any = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable) else (config.patch_size, config.patch_size) ) __lowerCAmelCase : Optional[Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [num_patches, self.model_tester.embed_dim] , ) __lowerCAmelCase : Optional[int] = outputs.reshaped_hidden_states self.assertEqual(len(_lowerCamelCase) , _lowerCamelCase) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Optional[Any] = reshaped_hidden_states[0].shape __lowerCAmelCase : Union[str, Any] = ( reshaped_hidden_states[0].view(_lowerCamelCase , _lowerCamelCase , height * width).permute(0 , 2 , 1) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:]) , [num_patches, self.model_tester.embed_dim] , ) def _SCREAMING_SNAKE_CASE ( self: List[Any]) -> Any: """simple docstring""" __lowerCAmelCase , __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase : Dict = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes[:-1]: __lowerCAmelCase : Optional[int] = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __lowerCAmelCase : Any = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase) def _SCREAMING_SNAKE_CASE ( self: Any) -> Optional[int]: """simple docstring""" __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase : Optional[int] = 3 __lowerCAmelCase : str = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable) else (self.model_tester.image_size, self.model_tester.image_size) ) __lowerCAmelCase : Optional[Any] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable) else (config.patch_size, config.patch_size) ) __lowerCAmelCase : Optional[int] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) __lowerCAmelCase : Optional[Any] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes[:-1]: __lowerCAmelCase : Union[str, Any] = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , (padded_height, padded_width)) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __lowerCAmelCase : Union[str, Any] = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , (padded_height, padded_width)) @slow def _SCREAMING_SNAKE_CASE ( self: Tuple) -> Any: """simple docstring""" for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Tuple = FocalNetModel.from_pretrained(_lowerCamelCase) self.assertIsNotNone(_lowerCamelCase) def _SCREAMING_SNAKE_CASE ( self: int) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase , __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase : Tuple = _config_zero_init(_lowerCamelCase) for model_class in self.all_model_classes: __lowerCAmelCase : Tuple = model_class(config=_lowerCamelCase) for name, param in model.named_parameters(): if "embeddings" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @require_vision @require_torch class A__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self: List[str]) -> Any: """simple docstring""" return AutoImageProcessor.from_pretrained("microsoft/focalnet-tiny") if is_vision_available() else None @slow def _SCREAMING_SNAKE_CASE ( self: List[str]) -> str: """simple docstring""" __lowerCAmelCase : str = FocalNetForImageClassification.from_pretrained("microsoft/focalnet-tiny").to(_lowerCamelCase) __lowerCAmelCase : Dict = self.default_image_processor __lowerCAmelCase : Union[str, Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") __lowerCAmelCase : str = image_processor(images=_lowerCamelCase , return_tensors="pt").to(_lowerCamelCase) # forward pass with torch.no_grad(): __lowerCAmelCase : Union[str, Any] = model(**_lowerCamelCase) # verify the logits __lowerCAmelCase : Any = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , _lowerCamelCase) __lowerCAmelCase : int = torch.tensor([0.2166, -0.4368, 0.2191]).to(_lowerCamelCase) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4)) self.assertTrue(outputs.logits.argmax(dim=-1).item() , 281) @require_torch class A__ ( __a , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE = (FocalNetBackbone,) if is_torch_available() else () SCREAMING_SNAKE_CASE = FocalNetConfig SCREAMING_SNAKE_CASE = False def _SCREAMING_SNAKE_CASE ( self: Dict) -> Any: """simple docstring""" __lowerCAmelCase : Dict = FocalNetModelTester(self)
293
'''simple docstring''' import gc import threading import time import psutil import torch class __UpperCAmelCase : def __init__( self ): lowerCAmelCase_ = psutil.Process() lowerCAmelCase_ = False def UpperCAmelCase_ ( self ): lowerCAmelCase_ = -1 while True: lowerCAmelCase_ = max(self.process.memory_info().rss , self.cpu_memory_peak ) # can't sleep or will not catch the peak right (this comment is here on purpose) if not self.peak_monitoring: break def UpperCAmelCase_ ( self ): lowerCAmelCase_ = True lowerCAmelCase_ = threading.Thread(target=self.peak_monitor ) lowerCAmelCase_ = True self.thread.start() def UpperCAmelCase_ ( self ): lowerCAmelCase_ = False self.thread.join() return self.cpu_memory_peak A_ : List[str] =PeakCPUMemory() def snake_case_ ( ) -> Tuple: # Time lowerCAmelCase_ = {'''time''': time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem lowerCAmelCase_ = psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count()): lowerCAmelCase_ = torch.cuda.memory_allocated(__snake_case) torch.cuda.reset_peak_memory_stats() return measures def snake_case_ ( __snake_case : Any) -> List[str]: # Time lowerCAmelCase_ = {'''time''': time.time() - start_measures['''time''']} gc.collect() torch.cuda.empty_cache() # CPU mem lowerCAmelCase_ = (psutil.Process().memory_info().rss - start_measures['''cpu''']) / 2**20 lowerCAmelCase_ = (cpu_peak_tracker.stop() - start_measures['''cpu''']) / 2**20 # GPU mem for i in range(torch.cuda.device_count()): lowerCAmelCase_ = (torch.cuda.memory_allocated(__snake_case) - start_measures[str(__snake_case)]) / 2**20 lowerCAmelCase_ = (torch.cuda.max_memory_allocated(__snake_case) - start_measures[str(__snake_case)]) / 2**20 return measures def snake_case_ ( __snake_case : Dict , __snake_case : Optional[int]) -> Dict: print(F'''{description}:''') print(F'''- Time: {measures['time']:.2f}s''') for i in range(torch.cuda.device_count()): print(F'''- GPU {i} allocated: {measures[str(__snake_case)]:.2f}MiB''') lowerCAmelCase_ = measures[F'''{i}-peak'''] print(F'''- GPU {i} peak: {peak:.2f}MiB''') print(F'''- CPU RAM allocated: {measures['cpu']:.2f}MiB''') print(F'''- CPU RAM peak: {measures['cpu-peak']:.2f}MiB''')
274
0
from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder lowerCamelCase_ = datasets.utils.logging.get_logger(__name__) class __a ( folder_based_builder.FolderBasedBuilderConfig ): """simple docstring""" _A : bool = None _A : bool = None class __a ( folder_based_builder.FolderBasedBuilder ): """simple docstring""" _A : List[str] = datasets.Audio() _A : Dict = "audio" _A : Union[str, Any] = AudioFolderConfig _A : List[str] # definition at the bottom of the script _A : Optional[Any] = AudioClassification(audio_column="audio" , label_column="label" ) lowerCamelCase_ = [ ".aiff", ".au", ".avr", ".caf", ".flac", ".htk", ".svx", ".mat4", ".mat5", ".mpc2k", ".ogg", ".paf", ".pvf", ".raw", ".rf64", ".sd2", ".sds", ".ircam", ".voc", ".w64", ".wav", ".nist", ".wavex", ".wve", ".xi", ".mp3", ".opus", ] lowerCamelCase_ = AUDIO_EXTENSIONS
588
import warnings from functools import wraps from typing import Callable def UpperCAmelCase_ ( __UpperCamelCase ): @wraps(__UpperCamelCase ) def _inner_fn(*__UpperCamelCase, **__UpperCamelCase ): warnings.warn( (f"""'{fn.__name__}' is experimental and might be subject to breaking changes in the future."""), __UpperCamelCase, ) return fn(*__UpperCamelCase, **__UpperCamelCase ) return _inner_fn
588
1
"""simple docstring""" from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowercase__( __SCREAMING_SNAKE_CASE : Optional[int] ): return getitem, k def lowercase__( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Dict ): return setitem, k, v def lowercase__( __SCREAMING_SNAKE_CASE : List[str] ): return delitem, k def lowercase__( __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , *__SCREAMING_SNAKE_CASE : str ): try: return fun(A__ , *A__ ), None except Exception as e: return None, e __SCREAMING_SNAKE_CASE =( _set("key_a", "val_a"), _set("key_b", "val_b"), ) __SCREAMING_SNAKE_CASE =[ _set("key_a", "val_a"), _set("key_a", "val_b"), ] __SCREAMING_SNAKE_CASE =[ _set("key_a", "val_a"), _set("key_b", "val_b"), _del("key_a"), _del("key_b"), _set("key_a", "val_a"), _del("key_a"), ] __SCREAMING_SNAKE_CASE =[ _get("key_a"), _del("key_a"), _set("key_a", "val_a"), _del("key_a"), _del("key_a"), _get("key_a"), ] __SCREAMING_SNAKE_CASE =[ *[_set(x, x) for x in range(5)], # guaranteed upsize ] __SCREAMING_SNAKE_CASE =[ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set("key_a", "val_b"), ] @pytest.mark.parametrize( 'operations' , ( pytest.param(_add_items , id='add items' ), pytest.param(_overwrite_items , id='overwrite items' ), pytest.param(_delete_items , id='delete items' ), pytest.param(_access_absent_items , id='access absent items' ), pytest.param(_add_with_resize_up , id='add with resize up' ), pytest.param(_add_with_resize_down , id='add with resize down' ), ) , ) def lowercase__( __SCREAMING_SNAKE_CASE : Union[str, Any] ): lowercase_ : List[Any] = HashMap(initial_block_size=4 ) lowercase_ : List[Any] = {} for _, (fun, *args) in enumerate(A__ ): lowercase_ : Optional[Any] = _run_operation(A__ , A__ , *A__ ) lowercase_ : Optional[int] = _run_operation(A__ , A__ , *A__ ) assert my_res == py_res assert str(A__ ) == str(A__ ) assert set(A__ ) == set(A__ ) assert len(A__ ) == len(A__ ) assert set(my.items() ) == set(py.items() ) def lowercase__( ): def is_public(__SCREAMING_SNAKE_CASE : Optional[int] ) -> bool: return not name.startswith('_' ) lowercase_ : int = {name for name in dir({} ) if is_public(A__ )} lowercase_ : Any = {name for name in dir(HashMap() ) if is_public(A__ )} assert dict_public_names > hash_public_names
425
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = torch.device('''cpu''') def snake_case ( ): UpperCAmelCase_ : str = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase_ : str = Image.open(requests.get(A__ ,stream=A__ ).raw ) return im def snake_case ( A__ ): if swiftformer_name == "swiftformer_xs": return torch.tensor([-2.1703e00, 2.1107e00, -2.0811e00, 8.8685e-01, 2.4360e-01] ) elif swiftformer_name == "swiftformer_s": return torch.tensor([3.9636e-01, 2.3478e-01, -1.6963e00, -1.7381e00, -8.6337e-01] ) elif swiftformer_name == "swiftformer_l1": return torch.tensor([-4.2768e-01, -4.7429e-01, -1.0897e00, -1.0248e00, 3.5523e-02] ) elif swiftformer_name == "swiftformer_l3": return torch.tensor([-2.5330e-01, 2.4211e-01, -6.0185e-01, -8.2789e-01, -6.0446e-02] ) def snake_case ( A__ ,A__ ,A__ ): UpperCAmelCase_ : Tuple = dct.pop(A__ ) UpperCAmelCase_ : Optional[Any] = val def snake_case ( A__ ): UpperCAmelCase_ : List[str] = [] for k in state_dict.keys(): UpperCAmelCase_ : Union[str, Any] = k if ".pwconv" in k: UpperCAmelCase_ : Dict = k_new.replace(".pwconv" ,".point_wise_conv" ) if ".dwconv" in k: UpperCAmelCase_ : Any = k_new.replace(".dwconv" ,".depth_wise_conv" ) if ".Proj." in k: UpperCAmelCase_ : Dict = k_new.replace(".Proj." ,".proj." ) if "patch_embed" in k_new: UpperCAmelCase_ : Tuple = k_new.replace("patch_embed" ,"swiftformer.patch_embed.patch_embedding" ) if "network" in k_new: UpperCAmelCase_ : List[Any] = k_new.split("." ) if ls[2].isdigit(): UpperCAmelCase_ : Tuple = "swiftformer.encoder.network." + ls[1] + ".blocks." + ls[2] + "." + ".".join(ls[3:] ) else: UpperCAmelCase_ : Optional[Any] = k_new.replace("network" ,"swiftformer.encoder.network" ) rename_keys.append((k, k_new) ) return rename_keys @torch.no_grad() def snake_case ( A__ ,A__ ,A__ ): UpperCAmelCase_ : Optional[int] = SwiftFormerConfig() # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size UpperCAmelCase_ : Optional[Any] = 10_00 UpperCAmelCase_ : str = "huggingface/label-files" UpperCAmelCase_ : str = "imagenet-1k-id2label.json" UpperCAmelCase_ : List[str] = json.load(open(hf_hub_download(A__ ,A__ ,repo_type="dataset" ) ,"r" ) ) UpperCAmelCase_ : Tuple = {int(A__ ): v for k, v in idalabel.items()} UpperCAmelCase_ : List[Any] = idalabel UpperCAmelCase_ : Optional[Any] = {v: k for k, v in idalabel.items()} # size of the architecture if swiftformer_name == "swiftformer_xs": UpperCAmelCase_ : Tuple = [3, 3, 6, 4] UpperCAmelCase_ : str = [48, 56, 1_12, 2_20] elif swiftformer_name == "swiftformer_s": UpperCAmelCase_ : Optional[Any] = [3, 3, 9, 6] UpperCAmelCase_ : Optional[Any] = [48, 64, 1_68, 2_24] elif swiftformer_name == "swiftformer_l1": UpperCAmelCase_ : int = [4, 3, 10, 5] UpperCAmelCase_ : Union[str, Any] = [48, 96, 1_92, 3_84] elif swiftformer_name == "swiftformer_l3": UpperCAmelCase_ : Dict = [4, 4, 12, 6] UpperCAmelCase_ : Optional[int] = [64, 1_28, 3_20, 5_12] # load state_dict of original model, remove and rename some keys if original_ckpt: if original_ckpt.startswith("https" ): UpperCAmelCase_ : List[Any] = torch.hub.load_state_dict_from_url(A__ ,map_location="cpu" ,check_hash=A__ ) else: UpperCAmelCase_ : Any = torch.load(A__ ,map_location="cpu" ) UpperCAmelCase_ : List[str] = checkpoint UpperCAmelCase_ : Dict = create_rename_keys(A__ ) for rename_key_src, rename_key_dest in rename_keys: rename_key(A__ ,A__ ,A__ ) # load HuggingFace model UpperCAmelCase_ : Optional[int] = SwiftFormerForImageClassification(A__ ).eval() hf_model.load_state_dict(A__ ) # prepare test inputs UpperCAmelCase_ : Tuple = prepare_img() UpperCAmelCase_ : int = ViTImageProcessor.from_pretrained("preprocessor_config" ) UpperCAmelCase_ : int = processor(images=A__ ,return_tensors="pt" ) # compare outputs from both models UpperCAmelCase_ : List[Any] = get_expected_output(A__ ) UpperCAmelCase_ : int = hf_model(inputs["pixel_values"] ).logits assert hf_logits.shape == torch.Size([1, 10_00] ) assert torch.allclose(hf_logits[0, 0:5] ,A__ ,atol=1e-3 ) Path(A__ ).mkdir(exist_ok=A__ ) print(F"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}""" ) hf_model.save_pretrained(A__ ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swiftformer_name''', default='''swiftformer_xs''', choices=['''swiftformer_xs''', '''swiftformer_s''', '''swiftformer_l1''', '''swiftformer_l3'''], type=str, help='''Name of the SwiftFormer model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default='''./converted_outputs/''', type=str, help='''Path to the output PyTorch model directory.''', ) parser.add_argument('''--original_ckpt''', default=None, type=str, help='''Path to the original model checkpoint.''') lowerCamelCase_ = parser.parse_args() convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
95
0
from pathlib import Path import fire def SCREAMING_SNAKE_CASE ( snake_case_ : str , snake_case_ : str , snake_case_ : int ): snake_case__ : Tuple = Path(snake_case_ ) snake_case__ : Optional[Any] = Path(snake_case_ ) dest_dir.mkdir(exist_ok=snake_case_ ) for path in src_dir.iterdir(): snake_case__ : Tuple = [x.rstrip() for x in list(path.open().readlines() )][:n] snake_case__ : Optional[int] = dest_dir.joinpath(path.name ) print(snake_case_ ) dest_path.open("w" ).write("\n".join(snake_case_ ) ) if __name__ == "__main__": fire.Fire(minify)
25
def SCREAMING_SNAKE_CASE ( snake_case_ : list ): if len(snake_case_ ) <= 1: return lst snake_case__ : List[Any] = 1 while i < len(snake_case_ ): if lst[i - 1] <= lst[i]: i += 1 else: snake_case__, snake_case__ : Tuple = lst[i], lst[i - 1] i -= 1 if i == 0: snake_case__ : Union[str, Any] = 1 return lst if __name__ == "__main__": __lowerCamelCase : Dict = input("""Enter numbers separated by a comma:\n""").strip() __lowerCamelCase : Tuple = [int(item) for item in user_input.split(""",""")] print(gnome_sort(unsorted))
25
1
def _lowerCamelCase( __snake_case , __snake_case ) -> str: if not (isinstance(__snake_case , __snake_case ) and isinstance(__snake_case , __snake_case )): raise ValueError("longest_common_substring() takes two strings for inputs" ) __snake_case = len(__snake_case ) __snake_case = len(__snake_case ) __snake_case = [[0] * (texta_length + 1) for _ in range(texta_length + 1 )] __snake_case = 0 __snake_case = 0 for i in range(1 , texta_length + 1 ): for j in range(1 , texta_length + 1 ): if texta[i - 1] == texta[j - 1]: __snake_case = 1 + dp[i - 1][j - 1] if dp[i][j] > ans_length: __snake_case = i __snake_case = dp[i][j] return texta[ans_index - ans_length : ans_index] if __name__ == "__main__": import doctest doctest.testmod()
524
# limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( 'pipelines_utils', '0.22.0', 'Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.', standard_warn=False, stacklevel=3, )
524
1
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib UpperCamelCase_ = { '''debug''': logging.DEBUG, '''info''': logging.INFO, '''warning''': logging.WARNING, '''error''': logging.ERROR, '''critical''': logging.CRITICAL, } UpperCamelCase_ = logging.WARNING def lowerCamelCase_ ( ): '''simple docstring''' UpperCAmelCase_ : str = os.getenv("""DATASETS_VERBOSITY""" , _a ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( F'''Unknown option DATASETS_VERBOSITY={env_level_str}, ''' F'''has to be one of: { ', '.join(log_levels.keys() ) }''' ) return _default_log_level def lowerCamelCase_ ( ): '''simple docstring''' return __name__.split(""".""" )[0] def lowerCamelCase_ ( ): '''simple docstring''' return logging.getLogger(_get_library_name() ) def lowerCamelCase_ ( ): '''simple docstring''' UpperCAmelCase_ : Any = _get_library_root_logger() library_root_logger.setLevel(_get_default_logging_level() ) def lowerCamelCase_ ( ): '''simple docstring''' UpperCAmelCase_ : List[Any] = _get_library_root_logger() library_root_logger.setLevel(logging.NOTSET ) def lowerCamelCase_ ( _a : Optional[str] = None ): '''simple docstring''' if name is None: UpperCAmelCase_ : List[Any] = _get_library_name() return logging.getLogger(_a ) def lowerCamelCase_ ( ): '''simple docstring''' return _get_library_root_logger().getEffectiveLevel() def lowerCamelCase_ ( _a : int ): '''simple docstring''' _get_library_root_logger().setLevel(_a ) def lowerCamelCase_ ( ): '''simple docstring''' return set_verbosity(_a ) def lowerCamelCase_ ( ): '''simple docstring''' return set_verbosity(_a ) def lowerCamelCase_ ( ): '''simple docstring''' return set_verbosity(_a ) def lowerCamelCase_ ( ): '''simple docstring''' return set_verbosity(_a ) def lowerCamelCase_ ( ): '''simple docstring''' UpperCAmelCase_ : List[Any] = False def lowerCamelCase_ ( ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = True # Configure the library root logger at the module level (singleton-like) _configure_library_root_logger() class _snake_case : '''simple docstring''' def __init__( self: Optional[int] ,*lowerCamelCase_: Optional[int] ,**lowerCamelCase_: Optional[int] ) -> Any: # pylint: disable=unused-argument UpperCAmelCase_ : Any = args[0] if args else None def __iter__( self: Any ) -> Union[str, Any]: return iter(self._iterator ) def __getattr__( self: int ,lowerCamelCase_: Optional[Any] ) -> List[Any]: def empty_fn(*lowerCamelCase_: str ,**lowerCamelCase_: str ): # pylint: disable=unused-argument return return empty_fn def __enter__( self: Tuple ) -> Union[str, Any]: return self def __exit__( self: List[str] ,lowerCamelCase_: List[Any] ,lowerCamelCase_: Optional[Any] ,lowerCamelCase_: Any ) -> Optional[Any]: return UpperCamelCase_ = True class _snake_case : '''simple docstring''' def __call__( self: str ,*lowerCamelCase_: Tuple ,lowerCamelCase_: List[Any]=False ,**lowerCamelCase_: Optional[int] ) -> int: if _tqdm_active and not disable: return tqdm_lib.tqdm(*lowerCamelCase_ ,**lowerCamelCase_ ) else: return EmptyTqdm(*lowerCamelCase_ ,**lowerCamelCase_ ) def A__ ( self: Tuple ,*lowerCamelCase_: Union[str, Any] ,**lowerCamelCase_: Union[str, Any] ) -> Optional[int]: UpperCAmelCase_ : Optional[int] = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*lowerCamelCase_ ,**lowerCamelCase_ ) def A__ ( self: Tuple ) -> Union[str, Any]: if _tqdm_active: return tqdm_lib.tqdm.get_lock() UpperCamelCase_ = _tqdm_cls() def lowerCamelCase_ ( ): '''simple docstring''' global _tqdm_active return bool(_tqdm_active ) def lowerCamelCase_ ( ): '''simple docstring''' global _tqdm_active UpperCAmelCase_ : Any = True def lowerCamelCase_ ( ): '''simple docstring''' global _tqdm_active UpperCAmelCase_ : Union[str, Any] = False
322
import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--original_config_file''', type=str, required=True, help='''The YAML config file corresponding to the original architecture.''', ) parser.add_argument( '''--num_in_channels''', default=None, type=int, help='''The number of input channels. If `None` number of input channels will be automatically inferred.''', ) parser.add_argument( '''--image_size''', default=512, type=int, help=( '''The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2''' ''' Base. Use 768 for Stable Diffusion v2.''' ), ) parser.add_argument( '''--extract_ema''', action='''store_true''', help=( '''Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights''' ''' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield''' ''' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.''' ), ) parser.add_argument( '''--upcast_attention''', action='''store_true''', help=( '''Whether the attention computation should always be upcasted. This is necessary when running stable''' ''' diffusion 2.1.''' ), ) parser.add_argument( '''--from_safetensors''', action='''store_true''', help='''If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.''', ) parser.add_argument( '''--to_safetensors''', action='''store_true''', help='''Whether to store pipeline in safetensors format or not.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument('''--device''', type=str, help='''Device to use (e.g. cpu, cuda:0, cuda:1, etc.)''') def lowerCamelCase_ ( _a : Optional[int] ): '''simple docstring''' if string == "True": return True elif string == "False": return False else: raise ValueError(F'''could not parse string as bool {string}''' ) parser.add_argument( '''--use_linear_projection''', help='''Override for use linear projection''', required=False, type=parse_bool ) parser.add_argument('''--cross_attention_dim''', help='''Override for cross attention_dim''', required=False, type=int) UpperCamelCase_ = parser.parse_args() UpperCamelCase_ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
322
1
from collections.abc import Iterable from typing import Generic, TypeVar __a: List[str] = TypeVar('''_T''') class SCREAMING_SNAKE_CASE__ ( Generic[_T] ): '''simple docstring''' def __init__( self : str , lowerCamelCase : Iterable[_T] | None = None ) -> None: """simple docstring""" _UpperCAmelCase = list(iterable or [] ) _UpperCAmelCase = [] def __len__( self : int ) -> int: """simple docstring""" return len(self._stacka ) + len(self._stacka ) def __repr__( self : Any ) -> str: """simple docstring""" return f"""Queue({tuple(self._stacka[::-1] + self._stacka )})""" def lowerCamelCase ( self : str , lowerCamelCase : _T ) -> None: """simple docstring""" self._stacka.append(lowerCamelCase ) def lowerCamelCase ( self : str ) -> _T: """simple docstring""" _UpperCAmelCase = self._stacka.pop _UpperCAmelCase = self._stacka.append if not self._stacka: while self._stacka: stacka_append(stacka_pop() ) if not self._stacka: raise IndexError("""Queue is empty""" ) return self._stacka.pop() if __name__ == "__main__": from doctest import testmod testmod()
108
'''simple docstring''' import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class a__: def __init__( self , _UpperCAmelCase , _UpperCAmelCase=13 , _UpperCAmelCase=7 , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=99 , _UpperCAmelCase=16 , _UpperCAmelCase=36 , _UpperCAmelCase=6 , _UpperCAmelCase=6 , _UpperCAmelCase=6 , _UpperCAmelCase=37 , _UpperCAmelCase="gelu" , _UpperCAmelCase=0.1 , _UpperCAmelCase=0.1 , _UpperCAmelCase=512 , _UpperCAmelCase=16 , _UpperCAmelCase=2 , _UpperCAmelCase=0.02 , _UpperCAmelCase=3 , _UpperCAmelCase=4 , _UpperCAmelCase=None , ) -> Dict: snake_case__ =parent snake_case__ =batch_size snake_case__ =seq_length snake_case__ =is_training snake_case__ =use_input_mask snake_case__ =use_token_type_ids snake_case__ =use_labels snake_case__ =vocab_size snake_case__ =embedding_size snake_case__ =hidden_size snake_case__ =num_hidden_layers snake_case__ =num_hidden_groups snake_case__ =num_attention_heads snake_case__ =intermediate_size snake_case__ =hidden_act snake_case__ =hidden_dropout_prob snake_case__ =attention_probs_dropout_prob snake_case__ =max_position_embeddings snake_case__ =type_vocab_size snake_case__ =type_sequence_label_size snake_case__ =initializer_range snake_case__ =num_labels snake_case__ =num_choices snake_case__ =scope def _lowercase ( self ) -> Tuple: snake_case__ =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case__ =None if self.use_input_mask: snake_case__ =random_attention_mask([self.batch_size, self.seq_length] ) snake_case__ =None if self.use_token_type_ids: snake_case__ =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case__ =None snake_case__ =None snake_case__ =None if self.use_labels: snake_case__ =ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case__ =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case__ =ids_tensor([self.batch_size] , self.num_choices ) snake_case__ =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self ) -> Union[str, Any]: return AlbertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , ) def _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> List[str]: snake_case__ =AlbertModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() snake_case__ =model(_UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase ) snake_case__ =model(_UpperCAmelCase , token_type_ids=_UpperCAmelCase ) snake_case__ =model(_UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Dict: snake_case__ =AlbertForPreTraining(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() snake_case__ =model( _UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , labels=_UpperCAmelCase , sentence_order_label=_UpperCAmelCase , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels) ) def _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> List[str]: snake_case__ =AlbertForMaskedLM(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() snake_case__ =model(_UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> List[str]: snake_case__ =AlbertForQuestionAnswering(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() snake_case__ =model( _UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , start_positions=_UpperCAmelCase , end_positions=_UpperCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Optional[int]: snake_case__ =self.num_labels snake_case__ =AlbertForSequenceClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() snake_case__ =model(_UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Any: snake_case__ =self.num_labels snake_case__ =AlbertForTokenClassification(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() snake_case__ =model(_UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Dict: snake_case__ =self.num_choices snake_case__ =AlbertForMultipleChoice(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() snake_case__ =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case__ =token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case__ =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case__ =model( _UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , labels=_UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _lowercase ( self ) -> List[Any]: snake_case__ =self.prepare_config_and_inputs() ( ( snake_case__ ) , ( snake_case__ ) , ( snake_case__ ) , ( snake_case__ ) , ( snake_case__ ) , ( snake_case__ ) , ( snake_case__ ) , ) =config_and_inputs snake_case__ ={'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a__( snake_case__ , snake_case__ , unittest.TestCase ): a_ : Optional[int] = ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) a_ : List[str] = ( { '''feature-extraction''': AlbertModel, '''fill-mask''': AlbertForMaskedLM, '''question-answering''': AlbertForQuestionAnswering, '''text-classification''': AlbertForSequenceClassification, '''token-classification''': AlbertForTokenClassification, '''zero-shot''': AlbertForSequenceClassification, } if is_torch_available() else {} ) a_ : int = True def _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=False ) -> Any: snake_case__ =super()._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase , return_labels=_UpperCAmelCase ) if return_labels: if model_class in get_values(_UpperCAmelCase ): snake_case__ =torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_UpperCAmelCase ) snake_case__ =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_UpperCAmelCase ) return inputs_dict def _lowercase ( self ) -> int: snake_case__ =AlbertModelTester(self ) snake_case__ =ConfigTester(self , config_class=_UpperCAmelCase , hidden_size=37 ) def _lowercase ( self ) -> Dict: self.config_tester.run_common_tests() def _lowercase ( self ) -> str: snake_case__ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def _lowercase ( self ) -> Optional[int]: snake_case__ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_UpperCAmelCase ) def _lowercase ( self ) -> Optional[Any]: snake_case__ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_UpperCAmelCase ) def _lowercase ( self ) -> Tuple: snake_case__ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_UpperCAmelCase ) def _lowercase ( self ) -> List[str]: snake_case__ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_UpperCAmelCase ) def _lowercase ( self ) -> Optional[int]: snake_case__ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_UpperCAmelCase ) def _lowercase ( self ) -> List[str]: snake_case__ =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case__ =type self.model_tester.create_and_check_model(*_UpperCAmelCase ) @slow def _lowercase ( self ) -> Union[str, Any]: for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case__ =AlbertModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) @require_torch class a__( unittest.TestCase ): @slow def _lowercase ( self ) -> str: snake_case__ =AlbertModel.from_pretrained('albert-base-v2' ) snake_case__ =torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) snake_case__ =torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): snake_case__ =model(_UpperCAmelCase , attention_mask=_UpperCAmelCase )[0] snake_case__ =torch.Size((1, 11, 768) ) self.assertEqual(output.shape , _UpperCAmelCase ) snake_case__ =torch.tensor( [[[-0.6_513, 1.5_035, -0.2_766], [-0.6_515, 1.5_046, -0.2_780], [-0.6_512, 1.5_049, -0.2_784]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _UpperCAmelCase , atol=1E-4 ) )
538
0
"""simple docstring""" import os import time import numpy as np import onnxruntime as ort lowerCAmelCase__ = '''1''' lowerCAmelCase__ = '''0''' lowerCAmelCase__ = '''1''' lowerCAmelCase__ = ort.SessionOptions() lowerCAmelCase__ = ort.GraphOptimizationLevel.ORT_DISABLE_ALL print('''Create inference session...''') lowerCAmelCase__ = ['''TensorrtExecutionProvider''', '''CUDAExecutionProvider'''] lowerCAmelCase__ = ort.InferenceSession('''model.onnx''', sess_options=sess_opt, providers=execution_provider) lowerCAmelCase__ = ort.RunOptions() lowerCAmelCase__ = 128 lowerCAmelCase__ = 1 lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) print('''Warm up phase...''') sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('''Start inference...''') lowerCAmelCase__ = time.time() lowerCAmelCase__ = 2000 lowerCAmelCase__ = {} for iter in range(max_iters): lowerCAmelCase__ = sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('''Average Inference Time = {:.3f} ms'''.format((time.time() - start_time) * 1000 / max_iters))
719
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def snake_case ( A__ ,A__ ,A__ ,A__ ,A__ ,A__ ): # prepare kernel # the kernel size have to be odd if (ksize % 2) == 0: UpperCAmelCase_ : List[Any] = ksize + 1 UpperCAmelCase_ : Optional[Any] = np.zeros((ksize, ksize) ,dtype=np.floataa ) # each value for y in range(A__ ): for x in range(A__ ): # distance from center UpperCAmelCase_ : Tuple = x - ksize // 2 UpperCAmelCase_ : Any = y - ksize // 2 # degree to radiant UpperCAmelCase_ : int = theta / 1_80 * np.pi UpperCAmelCase_ : Optional[int] = np.cos(_theta ) UpperCAmelCase_ : Union[str, Any] = np.sin(_theta ) # get kernel x UpperCAmelCase_ : Tuple = cos_theta * px + sin_theta * py # get kernel y UpperCAmelCase_ : List[str] = -sin_theta * px + cos_theta * py # fill kernel UpperCAmelCase_ : Dict = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image lowerCamelCase_ = imread('''../image_data/lena.jpg''') # turn image in gray scale value lowerCamelCase_ = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges lowerCamelCase_ = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 120, 150]: lowerCamelCase_ = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) lowerCamelCase_ = out / out.max() * 255 lowerCamelCase_ = out.astype(np.uinta) imshow('''Original''', gray) imshow('''Gabor filter with 20x20 mask and 6 directions''', out) waitKey(0)
463
0
def lowercase__ ( _UpperCamelCase , _UpperCamelCase) -> Optional[Any]: """simple docstring""" if b == 0: return 1 if (b % 2) == 0: return actual_power(_lowercase , int(b / 2)) * actual_power(_lowercase , int(b / 2)) else: return a * actual_power(_lowercase , int(b / 2)) * actual_power(_lowercase , int(b / 2)) def lowercase__ ( _UpperCamelCase , _UpperCamelCase) -> float: """simple docstring""" if b < 0: return 1 / actual_power(_lowercase , _lowercase) return actual_power(_lowercase , _lowercase) if __name__ == "__main__": print(power(-2, -3))
280
"""simple docstring""" import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaProcessor, is_apex_available, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse('1.6'): lowercase_ = True from torch.cuda.amp import autocast lowercase_ = logging.getLogger(__name__) def UpperCAmelCase ( _lowercase : Optional[Any]=None , _lowercase : str=None ) -> List[str]: """simple docstring""" return field(default_factory=lambda: default , metadata=_lowercase ) @dataclass class __a : lowerCamelCase : str =field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) lowerCamelCase : Optional[str] =field( default=__snake_case , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) lowerCamelCase : Optional[bool] =field( default=__snake_case , metadata={'help': 'Whether to freeze the feature extractor layers of the model.'} ) lowerCamelCase : Optional[float] =field( default=0.1 , metadata={'help': 'The dropout ratio for the attention probabilities.'} ) lowerCamelCase : Optional[float] =field( default=0.1 , metadata={'help': 'The dropout ratio for activations inside the fully connected layer.'} ) lowerCamelCase : Optional[float] =field( default=0.1 , metadata={ 'help': 'The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.' } , ) lowerCamelCase : Optional[float] =field( default=0.1 , metadata={'help': 'The dropout probabilitiy for all 1D convolutional layers in feature extractor.'} , ) lowerCamelCase : Optional[float] =field( default=0.05 , metadata={ 'help': ( 'Propability of each feature vector along the time axis to be chosen as the start of the vector' 'span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature' 'vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.' ) } , ) lowerCamelCase : Optional[float] =field(default=0.0 , metadata={'help': 'The LayerDrop probability.'} ) @dataclass class __a : lowerCamelCase : Optional[str] =field( default=__snake_case , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) lowerCamelCase : Optional[str] =field( default='train+validation' , metadata={ 'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\'' } , ) lowerCamelCase : bool =field( default=__snake_case , metadata={'help': 'Overwrite the cached preprocessed datasets or not.'} ) lowerCamelCase : Optional[int] =field( default=__snake_case , metadata={'help': 'The number of processes to use for the preprocessing.'} , ) lowerCamelCase : Optional[int] =field( default=__snake_case , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) lowerCamelCase : Optional[int] =field( default=__snake_case , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of validation examples to this ' 'value if set.' ) } , ) lowerCamelCase : List[str] =list_field( default=[',', '?', '.', '!', '-', ';', ':', '""', '%', '\'', '"', '�'] , metadata={'help': 'A list of characters to remove from the transcripts.'} , ) @dataclass class __a : lowerCamelCase : WavaVecaProcessor lowerCamelCase : Union[bool, str] =True lowerCamelCase : Optional[int] =None lowerCamelCase : Optional[int] =None lowerCamelCase : Optional[int] =None lowerCamelCase : Optional[int] =None def __call__( self , UpperCAmelCase ): '''simple docstring''' lowerCAmelCase_ = [{'''input_values''': feature['''input_values''']} for feature in features] lowerCAmelCase_ = [{'''input_ids''': feature['''labels''']} for feature in features] lowerCAmelCase_ = self.processor.pad( UpperCAmelCase , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' , ) lowerCAmelCase_ = self.processor.pad( labels=UpperCAmelCase , padding=self.padding , max_length=self.max_length_labels , pad_to_multiple_of=self.pad_to_multiple_of_labels , return_tensors='''pt''' , ) # replace padding with -100 to ignore loss correctly lowerCAmelCase_ = labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1 ) , -100 ) lowerCAmelCase_ = labels return batch class __a ( __snake_case ): def lowerCamelCase_ ( self , UpperCAmelCase , UpperCAmelCase ): '''simple docstring''' model.train() lowerCAmelCase_ = self._prepare_inputs(UpperCAmelCase ) if self.use_amp: with autocast(): lowerCAmelCase_ = self.compute_loss(UpperCAmelCase , UpperCAmelCase ) else: lowerCAmelCase_ = self.compute_loss(UpperCAmelCase , UpperCAmelCase ) if self.args.n_gpu > 1: if model.module.config.ctc_loss_reduction == "mean": lowerCAmelCase_ = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": lowerCAmelCase_ = loss.sum() / (inputs['''labels'''] >= 0).sum() else: raise ValueError(F"""{model.config.ctc_loss_reduction} is not valid. Choose one of ['mean', 'sum']""" ) if self.args.gradient_accumulation_steps > 1: lowerCAmelCase_ = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(UpperCAmelCase ).backward() elif self.use_apex: with amp.scale_loss(UpperCAmelCase , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(UpperCAmelCase ) else: loss.backward() return loss.detach() def UpperCAmelCase ( ) -> Tuple: """simple docstring""" lowerCAmelCase_ = 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. lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = parser.parse_args_into_dataclasses() # Detecting last checkpoint. lowerCAmelCase_ = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: lowerCAmelCase_ = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , _lowercase ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: lowerCAmelCase_ = datasets.load_dataset( '''common_voice''' , data_args.dataset_config_name , split=data_args.train_split_name ) lowerCAmelCase_ = datasets.load_dataset('''common_voice''' , data_args.dataset_config_name , split='''test''' ) # Create and save tokenizer lowerCAmelCase_ = F"""[{"".join(data_args.chars_to_ignore )}]""" def remove_special_characters(_lowercase : List[str] ): lowerCAmelCase_ = re.sub(_lowercase , '''''' , batch['''sentence'''] ).lower() + ''' ''' return batch lowerCAmelCase_ = train_dataset.map(_lowercase , remove_columns=['''sentence'''] ) lowerCAmelCase_ = eval_dataset.map(_lowercase , remove_columns=['''sentence'''] ) def extract_all_chars(_lowercase : str ): lowerCAmelCase_ = ''' '''.join(batch['''text'''] ) lowerCAmelCase_ = list(set(_lowercase ) ) return {"vocab": [vocab], "all_text": [all_text]} lowerCAmelCase_ = train_dataset.map( _lowercase , batched=_lowercase , batch_size=-1 , keep_in_memory=_lowercase , remove_columns=train_dataset.column_names , ) lowerCAmelCase_ = train_dataset.map( _lowercase , batched=_lowercase , batch_size=-1 , keep_in_memory=_lowercase , remove_columns=eval_dataset.column_names , ) lowerCAmelCase_ = list(set(vocab_train['''vocab'''][0] ) | set(vocab_test['''vocab'''][0] ) ) lowerCAmelCase_ = {v: k for k, v in enumerate(_lowercase )} lowerCAmelCase_ = vocab_dict[''' '''] del vocab_dict[" "] lowerCAmelCase_ = len(_lowercase ) lowerCAmelCase_ = len(_lowercase ) with open('''vocab.json''' , '''w''' ) as vocab_file: json.dump(_lowercase , _lowercase ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase_ = WavaVecaCTCTokenizer( '''vocab.json''' , unk_token='''[UNK]''' , pad_token='''[PAD]''' , word_delimiter_token='''|''' , ) lowerCAmelCase_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0.0 , do_normalize=_lowercase , return_attention_mask=_lowercase ) lowerCAmelCase_ = WavaVecaProcessor(feature_extractor=_lowercase , tokenizer=_lowercase ) lowerCAmelCase_ = WavaVecaForCTC.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , activation_dropout=model_args.activation_dropout , attention_dropout=model_args.attention_dropout , hidden_dropout=model_args.hidden_dropout , feat_proj_dropout=model_args.feat_proj_dropout , mask_time_prob=model_args.mask_time_prob , gradient_checkpointing=training_args.gradient_checkpointing , layerdrop=model_args.layerdrop , ctc_loss_reduction='''mean''' , pad_token_id=processor.tokenizer.pad_token_id , vocab_size=len(processor.tokenizer ) , ) if data_args.max_train_samples is not None: lowerCAmelCase_ = min(len(_lowercase ) , data_args.max_train_samples ) lowerCAmelCase_ = train_dataset.select(range(_lowercase ) ) if data_args.max_val_samples is not None: lowerCAmelCase_ = eval_dataset.select(range(data_args.max_val_samples ) ) lowerCAmelCase_ = torchaudio.transforms.Resample(4_8_0_0_0 , 1_6_0_0_0 ) # Preprocessing the datasets. # We need to read the aduio files as arrays and tokenize the targets. def speech_file_to_array_fn(_lowercase : Union[str, Any] ): lowerCAmelCase_ , lowerCAmelCase_ = torchaudio.load(batch['''path'''] ) lowerCAmelCase_ = resampler(_lowercase ).squeeze().numpy() lowerCAmelCase_ = 1_6_0_0_0 lowerCAmelCase_ = batch['''text'''] return batch lowerCAmelCase_ = train_dataset.map( _lowercase , remove_columns=train_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) lowerCAmelCase_ = eval_dataset.map( _lowercase , remove_columns=eval_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) def prepare_dataset(_lowercase : str ): # check that all files have the correct sampling rate assert ( len(set(batch['''sampling_rate'''] ) ) == 1 ), F"""Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.""" lowerCAmelCase_ = processor( audio=batch['''speech'''] , text=batch['''target_text'''] , sampling_rate=batch['''sampling_rate'''][0] ) batch.update(_lowercase ) return batch lowerCAmelCase_ = train_dataset.map( _lowercase , remove_columns=train_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=_lowercase , num_proc=data_args.preprocessing_num_workers , ) lowerCAmelCase_ = eval_dataset.map( _lowercase , remove_columns=eval_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=_lowercase , num_proc=data_args.preprocessing_num_workers , ) # Metric lowerCAmelCase_ = datasets.load_metric('''wer''' ) def compute_metrics(_lowercase : Optional[int] ): lowerCAmelCase_ = pred.predictions lowerCAmelCase_ = np.argmax(_lowercase , axis=-1 ) lowerCAmelCase_ = processor.tokenizer.pad_token_id lowerCAmelCase_ = processor.batch_decode(_lowercase ) # we do not want to group tokens when computing the metrics lowerCAmelCase_ = processor.batch_decode(pred.label_ids , group_tokens=_lowercase ) lowerCAmelCase_ = wer_metric.compute(predictions=_lowercase , references=_lowercase ) return {"wer": wer} if model_args.freeze_feature_extractor: model.freeze_feature_extractor() # Data collator lowerCAmelCase_ = DataCollatorCTCWithPadding(processor=_lowercase , padding=_lowercase ) # Initialize our Trainer lowerCAmelCase_ = CTCTrainer( model=_lowercase , data_collator=_lowercase , args=_lowercase , compute_metrics=_lowercase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=processor.feature_extractor , ) # Training if training_args.do_train: if last_checkpoint is not None: lowerCAmelCase_ = last_checkpoint elif os.path.isdir(model_args.model_name_or_path ): lowerCAmelCase_ = model_args.model_name_or_path else: lowerCAmelCase_ = None # Save the feature_extractor and the tokenizer if is_main_process(training_args.local_rank ): processor.save_pretrained(training_args.output_dir ) lowerCAmelCase_ = trainer.train(resume_from_checkpoint=_lowercase ) trainer.save_model() lowerCAmelCase_ = train_result.metrics lowerCAmelCase_ = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(_lowercase ) ) lowerCAmelCase_ = min(_lowercase , len(_lowercase ) ) trainer.log_metrics('''train''' , _lowercase ) trainer.save_metrics('''train''' , _lowercase ) trainer.save_state() # Evaluation lowerCAmelCase_ = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) lowerCAmelCase_ = trainer.evaluate() lowerCAmelCase_ = data_args.max_val_samples if data_args.max_val_samples is not None else len(_lowercase ) lowerCAmelCase_ = min(_lowercase , len(_lowercase ) ) trainer.log_metrics('''eval''' , _lowercase ) trainer.save_metrics('''eval''' , _lowercase ) return results if __name__ == "__main__": main()
552
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def lowerCAmelCase_ ( A_): UpperCamelCase__: int = [2, 2, 6, 2] if "tiny" in model_name else [2, 2, 18, 2] UpperCamelCase__: Tuple = True if "large" in model_name or "huge" in model_name else False UpperCamelCase__: int = True if "large" in model_name or "huge" in model_name else False UpperCamelCase__: Dict = True if "large" in model_name or "huge" in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: UpperCamelCase__: Optional[int] = [3, 3, 3, 3] UpperCamelCase__: Optional[int] = [5, 5, 5, 5] elif "fl4" in model_name: UpperCamelCase__: str = [4, 4, 4, 4] UpperCamelCase__: Optional[Any] = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: UpperCamelCase__: Dict = [3, 3, 3, 3] if "lrf" in model_name: UpperCamelCase__: List[str] = [3, 3, 3, 3] else: UpperCamelCase__: Optional[int] = [2, 2, 2, 2] if "tiny" in model_name: UpperCamelCase__: List[str] = 96 elif "small" in model_name: UpperCamelCase__: List[str] = 96 elif "base" in model_name: UpperCamelCase__: List[str] = 1_28 elif "large" in model_name: UpperCamelCase__: Union[str, Any] = 1_92 elif "xlarge" in model_name: UpperCamelCase__: List[Any] = 2_56 elif "huge" in model_name: UpperCamelCase__: Union[str, Any] = 3_52 # set label information UpperCamelCase__: str = "huggingface/label-files" if "large" in model_name or "huge" in model_name: UpperCamelCase__: List[Any] = "imagenet-22k-id2label.json" else: UpperCamelCase__: Dict = "imagenet-1k-id2label.json" UpperCamelCase__: Optional[Any] = json.load(open(hf_hub_download(A_ ,A_ ,repo_type="dataset") ,"r")) UpperCamelCase__: Tuple = {int(A_): v for k, v in idalabel.items()} UpperCamelCase__: Dict = {v: k for k, v in idalabel.items()} UpperCamelCase__: List[Any] = FocalNetConfig( embed_dim=A_ ,depths=A_ ,focal_levels=A_ ,focal_windows=A_ ,use_conv_embed=A_ ,idalabel=A_ ,labelaid=A_ ,use_post_layernorm=A_ ,use_layerscale=A_ ,) return config def lowerCAmelCase_ ( A_): if "patch_embed.proj" in name: UpperCamelCase__: List[str] = name.replace("patch_embed.proj" ,"embeddings.patch_embeddings.projection") if "patch_embed.norm" in name: UpperCamelCase__: Optional[int] = name.replace("patch_embed.norm" ,"embeddings.norm") if "layers" in name: UpperCamelCase__: List[Any] = "encoder." + name if "encoder.layers" in name: UpperCamelCase__: Optional[Any] = name.replace("encoder.layers" ,"encoder.stages") if "downsample.proj" in name: UpperCamelCase__: Optional[int] = name.replace("downsample.proj" ,"downsample.projection") if "blocks" in name: UpperCamelCase__: Dict = name.replace("blocks" ,"layers") if "modulation.f.weight" in name or "modulation.f.bias" in name: UpperCamelCase__: Union[str, Any] = name.replace("modulation.f" ,"modulation.projection_in") if "modulation.h.weight" in name or "modulation.h.bias" in name: UpperCamelCase__: Tuple = name.replace("modulation.h" ,"modulation.projection_context") if "modulation.proj.weight" in name or "modulation.proj.bias" in name: UpperCamelCase__: Dict = name.replace("modulation.proj" ,"modulation.projection_out") if name == "norm.weight": UpperCamelCase__: Union[str, Any] = "layernorm.weight" if name == "norm.bias": UpperCamelCase__: int = "layernorm.bias" if "head" in name: UpperCamelCase__: Optional[Any] = name.replace("head" ,"classifier") else: UpperCamelCase__: str = "focalnet." + name return name def lowerCAmelCase_ ( A_ ,A_ ,A_=False): UpperCamelCase__: Any = { "focalnet-tiny": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth", "focalnet-tiny-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth", "focalnet-small": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth", "focalnet-small-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth", "focalnet-base": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth", "focalnet-base-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth", "focalnet-large-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth", "focalnet-large-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth", "focalnet-xlarge-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth", "focalnet-xlarge-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth", } # fmt: on UpperCamelCase__: Tuple = model_name_to_url[model_name] print("Checkpoint URL: " ,A_) UpperCamelCase__: Union[str, Any] = torch.hub.load_state_dict_from_url(A_ ,map_location="cpu")["model"] # rename keys for key in state_dict.copy().keys(): UpperCamelCase__: List[str] = state_dict.pop(A_) UpperCamelCase__: int = val UpperCamelCase__: Any = get_focalnet_config(A_) UpperCamelCase__: Union[str, Any] = FocalNetForImageClassification(A_) model.eval() # load state dict model.load_state_dict(A_) # verify conversion UpperCamelCase__: Any = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCamelCase__: List[Any] = BitImageProcessor( do_resize=A_ ,size={"shortest_edge": 2_56} ,resample=PILImageResampling.BILINEAR ,do_center_crop=A_ ,crop_size=2_24 ,do_normalize=A_ ,image_mean=A_ ,image_std=A_ ,) UpperCamelCase__: Optional[int] = Image.open(requests.get(A_ ,stream=A_).raw) UpperCamelCase__: int = processor(images=A_ ,return_tensors="pt") UpperCamelCase__: int = transforms.Compose( [ transforms.Resize(2_56), transforms.CenterCrop(2_24), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406] ,std=[0.229, 0.224, 0.225]), ]) UpperCamelCase__: Optional[Any] = image_transforms(A_).unsqueeze(0) # verify pixel_values assert torch.allclose(inputs.pixel_values ,A_ ,atol=1e-4) UpperCamelCase__: Any = model(**A_) UpperCamelCase__: List[Any] = outputs.logits.argmax(-1).item() print("Predicted class:" ,model.config.idalabel[predicted_class_idx]) print("First values of logits:" ,outputs.logits[0, :3]) if model_name == "focalnet-tiny": UpperCamelCase__: Any = torch.tensor([0.2166, -0.4368, 0.2191]) elif model_name == "focalnet-tiny-lrf": UpperCamelCase__: List[str] = torch.tensor([1.1669, 0.0125, -0.1695]) elif model_name == "focalnet-small": UpperCamelCase__: Any = torch.tensor([0.4917, -0.0430, 0.1341]) elif model_name == "focalnet-small-lrf": UpperCamelCase__: Union[str, Any] = torch.tensor([-0.2588, -0.5342, -0.2331]) elif model_name == "focalnet-base": UpperCamelCase__: Any = torch.tensor([-0.1655, -0.4090, -0.1730]) elif model_name == "focalnet-base-lrf": UpperCamelCase__: Dict = torch.tensor([0.5306, -0.0483, -0.3928]) assert torch.allclose(outputs.logits[0, :3] ,A_ ,atol=1e-4) print("Looks ok!") if pytorch_dump_folder_path is not None: print(F"Saving model and processor of {model_name} to {pytorch_dump_folder_path}") model.save_pretrained(A_) processor.save_pretrained(A_) if push_to_hub: print(F"Pushing model and processor of {model_name} to the hub...") model.push_to_hub(F"{model_name}") processor.push_to_hub(F"{model_name}") if __name__ == "__main__": A__: Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''focalnet-tiny''', type=str, help='''Name of the FocalNet model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether to push the model and processor to the hub.''', ) A__: Optional[int] = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
717
import math import flax.linen as nn import jax.numpy as jnp def lowerCAmelCase_ ( A_ ,A_ ,A_ = 1 ,A_ = 1 ,A_ = 1.0e4 ,A_ = False ,A_ = 1.0 ,): assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F"Embedding dimension {embedding_dim} should be even" UpperCamelCase__: Tuple = float(embedding_dim // 2) UpperCamelCase__: List[Any] = math.log(max_timescale / min_timescale) / (num_timescales - freq_shift) UpperCamelCase__: Any = min_timescale * jnp.exp(jnp.arange(A_ ,dtype=jnp.floataa) * -log_timescale_increment) UpperCamelCase__: Any = jnp.expand_dims(A_ ,1) * jnp.expand_dims(A_ ,0) # scale embeddings UpperCamelCase__: List[Any] = scale * emb if flip_sin_to_cos: UpperCamelCase__: List[Any] = jnp.concatenate([jnp.cos(A_), jnp.sin(A_)] ,axis=1) else: UpperCamelCase__: str = jnp.concatenate([jnp.sin(A_), jnp.cos(A_)] ,axis=1) UpperCamelCase__: List[Any] = jnp.reshape(A_ ,[jnp.shape(A_)[0], embedding_dim]) return signal class _a ( nn.Module): """simple docstring""" UpperCamelCase__ = 32 UpperCamelCase__ = jnp.floataa @nn.compact def __call__( self: Dict , __lowerCamelCase: int ): '''simple docstring''' UpperCamelCase__: Union[str, Any] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_1" )(__lowerCamelCase ) UpperCamelCase__: List[str] = nn.silu(__lowerCamelCase ) UpperCamelCase__: Union[str, Any] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_2" )(__lowerCamelCase ) return temb class _a ( nn.Module): """simple docstring""" UpperCamelCase__ = 32 UpperCamelCase__ = False UpperCamelCase__ = 1 @nn.compact def __call__( self: str , __lowerCamelCase: Dict ): '''simple docstring''' return get_sinusoidal_embeddings( __lowerCamelCase , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
221
0
import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ): '''simple docstring''' @register_to_config def __init__( self : Any , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : float , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : str , lowerCamelCase : bool = False , ) -> Any: """simple docstring""" super().__init__() _UpperCAmelCase = nn.Embedding(lowerCamelCase , lowerCamelCase ) _UpperCAmelCase = nn.Embedding(lowerCamelCase , lowerCamelCase ) _UpperCAmelCase = False _UpperCAmelCase = nn.Dropout(p=lowerCamelCase ) _UpperCAmelCase = TaConfig( vocab_size=lowerCamelCase , d_model=lowerCamelCase , num_heads=lowerCamelCase , d_kv=lowerCamelCase , d_ff=lowerCamelCase , dropout_rate=lowerCamelCase , feed_forward_proj=lowerCamelCase , is_decoder=lowerCamelCase , is_encoder_decoder=lowerCamelCase , ) _UpperCAmelCase = nn.ModuleList() for lyr_num in range(lowerCamelCase ): _UpperCAmelCase = TaBlock(lowerCamelCase ) self.encoders.append(lowerCamelCase ) _UpperCAmelCase = TaLayerNorm(lowerCamelCase ) _UpperCAmelCase = nn.Dropout(p=lowerCamelCase ) def lowerCamelCase ( self : List[str] , lowerCamelCase : int , lowerCamelCase : Tuple ) -> int: """simple docstring""" _UpperCAmelCase = self.token_embedder(lowerCamelCase ) _UpperCAmelCase = encoder_input_tokens.shape[1] _UpperCAmelCase = torch.arange(lowerCamelCase , device=encoder_input_tokens.device ) x += self.position_encoding(lowerCamelCase ) _UpperCAmelCase = self.dropout_pre(lowerCamelCase ) # inverted the attention mask _UpperCAmelCase = encoder_input_tokens.size() _UpperCAmelCase = self.get_extended_attention_mask(lowerCamelCase , lowerCamelCase ) for lyr in self.encoders: _UpperCAmelCase = lyr(lowerCamelCase , lowerCamelCase )[0] _UpperCAmelCase = self.layer_norm(lowerCamelCase ) return self.dropout_post(lowerCamelCase ), encoder_inputs_mask
108
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class UpperCamelCase : def __init__( self : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : str=13 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : List[Any]=99 , UpperCAmelCase__ : str=32 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : str=37 , UpperCAmelCase__ : List[Any]="gelu" , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : str=0.1 , UpperCAmelCase__ : List[str]=512 , UpperCAmelCase__ : Any=16 , UpperCAmelCase__ : Tuple=2 , UpperCAmelCase__ : Dict=0.0_2 , UpperCAmelCase__ : Optional[int]=3 , UpperCAmelCase__ : Any=4 , UpperCAmelCase__ : Optional[Any]=None , ) -> Union[str, Any]: _a : str = parent _a : List[str] = batch_size _a : List[str] = seq_length _a : Any = is_training _a : Any = use_token_type_ids _a : Tuple = use_labels _a : Optional[Any] = vocab_size _a : Optional[int] = hidden_size _a : Union[str, Any] = num_hidden_layers _a : Optional[int] = num_attention_heads _a : List[Any] = intermediate_size _a : Any = hidden_act _a : Optional[int] = hidden_dropout_prob _a : Any = attention_probs_dropout_prob _a : int = max_position_embeddings _a : Tuple = type_vocab_size _a : str = type_sequence_label_size _a : Dict = initializer_range _a : List[Any] = num_labels _a : Union[str, Any] = num_choices _a : List[Any] = scope _a : List[Any] = self.vocab_size - 1 def _lowercase ( self : Any ) -> int: _a : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : Optional[Any] = None if self.use_token_type_ids: _a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _a : List[Any] = None _a : List[Any] = None _a : Union[str, Any] = None if self.use_labels: _a : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) _a : Union[str, Any] = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) _a : Tuple = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def _lowercase ( self : List[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , *UpperCAmelCase__ : Tuple ) -> List[str]: _a : Optional[int] = OpenAIGPTModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : Optional[Any] = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , head_mask=UpperCAmelCase__ ) _a : List[str] = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) _a : Optional[Any] = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , *UpperCAmelCase__ : Optional[int] ) -> List[str]: _a : str = OpenAIGPTLMHeadModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : Optional[int] = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self : Tuple , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Union[str, Any] ) -> Any: _a : int = OpenAIGPTDoubleHeadsModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : Tuple = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self : Tuple , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Any ) -> List[Any]: _a : Dict = self.num_labels _a : str = OpenAIGPTForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : Optional[int] = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase ( self : List[str] ) -> Union[str, Any]: _a : Optional[Any] = self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Optional[int] = config_and_inputs _a : Any = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask, } return config, inputs_dict @require_torch class UpperCamelCase ( snake_case_ , snake_case_ , snake_case_ , unittest.TestCase ): UpperCamelCase : Dict = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) UpperCamelCase : Dict = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly UpperCamelCase : Optional[Any] = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def _lowercase ( self : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : str ) -> Optional[int]: if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def _lowercase ( self : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int]=False ) -> List[Any]: _a : Optional[Any] = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": _a : List[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase__ , ) _a : Dict = inputs_dict["""labels"""] _a : List[Any] = inputs_dict["""labels"""] _a : List[str] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=UpperCAmelCase__ , ) _a : List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) return inputs_dict def _lowercase ( self : Dict ) -> List[Any]: _a : Dict = OpenAIGPTModelTester(self ) _a : Any = ConfigTester(self , config_class=UpperCAmelCase__ , n_embd=37 ) def _lowercase ( self : Tuple ) -> Optional[Any]: self.config_tester.run_common_tests() def _lowercase ( self : Optional[int] ) -> Any: _a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*UpperCAmelCase__ ) def _lowercase ( self : List[Any] ) -> int: _a : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*UpperCAmelCase__ ) def _lowercase ( self : Optional[int] ) -> int: _a : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*UpperCAmelCase__ ) def _lowercase ( self : Dict ) -> Any: _a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*UpperCAmelCase__ ) @slow def _lowercase ( self : str ) -> List[str]: for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : str = OpenAIGPTModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @require_torch class UpperCamelCase ( unittest.TestCase ): @slow def _lowercase ( self : Union[str, Any] ) -> List[Any]: _a : List[str] = OpenAIGPTLMHeadModel.from_pretrained("""openai-gpt""" ) model.to(UpperCAmelCase__ ) _a : Any = torch.tensor([[481, 4735, 544]] , dtype=torch.long , device=UpperCAmelCase__ ) # the president is _a : List[Any] = [ 481, 4735, 544, 246, 963, 870, 762, 239, 244, 40477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the _a : List[str] = model.generate(UpperCAmelCase__ , do_sample=UpperCAmelCase__ ) self.assertListEqual(output_ids[0].tolist() , UpperCAmelCase__ )
389
0
from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class __lowerCamelCase ( snake_case_ ): """simple docstring""" lowerCAmelCase__ = 42 class __lowerCamelCase ( nn.Module ): """simple docstring""" def __init__( self , UpperCAmelCase=3 , UpperCAmelCase=3 , UpperCAmelCase=("DownEncoderBlock2D",) , UpperCAmelCase=(64,) , UpperCAmelCase=2 , UpperCAmelCase=32 , UpperCAmelCase="silu" , UpperCAmelCase=True , ) -> Tuple: '''simple docstring''' super().__init__() lowercase_ = layers_per_block lowercase_ = torch.nn.Convad( UpperCAmelCase , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) lowercase_ = None lowercase_ = nn.ModuleList([] ) # down lowercase_ = block_out_channels[0] for i, down_block_type in enumerate(UpperCAmelCase ): lowercase_ = output_channel lowercase_ = block_out_channels[i] lowercase_ = i == len(UpperCAmelCase ) - 1 lowercase_ = get_down_block( UpperCAmelCase , num_layers=self.layers_per_block , in_channels=UpperCAmelCase , out_channels=UpperCAmelCase , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=UpperCAmelCase , resnet_groups=UpperCAmelCase , attention_head_dim=UpperCAmelCase , temb_channels=UpperCAmelCase , ) self.down_blocks.append(UpperCAmelCase ) # mid lowercase_ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=UpperCAmelCase , output_scale_factor=1 , resnet_time_scale_shift="default" , attention_head_dim=block_out_channels[-1] , resnet_groups=UpperCAmelCase , temb_channels=UpperCAmelCase , ) # out lowercase_ = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=UpperCAmelCase , eps=1e-6 ) lowercase_ = nn.SiLU() lowercase_ = 2 * out_channels if double_z else out_channels lowercase_ = nn.Convad(block_out_channels[-1] , UpperCAmelCase , 3 , padding=1 ) lowercase_ = False def A__ ( self , UpperCAmelCase ) -> Tuple: '''simple docstring''' lowercase_ = x lowercase_ = self.conv_in(UpperCAmelCase ) if self.training and self.gradient_checkpointing: def create_custom_forward(UpperCAmelCase ): def custom_forward(*UpperCAmelCase ): return module(*UpperCAmelCase ) return custom_forward # down if is_torch_version(">=" , "1.11.0" ): for down_block in self.down_blocks: lowercase_ = torch.utils.checkpoint.checkpoint( create_custom_forward(UpperCAmelCase ) , UpperCAmelCase , use_reentrant=UpperCAmelCase ) # middle lowercase_ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , UpperCAmelCase , use_reentrant=UpperCAmelCase ) else: for down_block in self.down_blocks: lowercase_ = torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCAmelCase ) , UpperCAmelCase ) # middle lowercase_ = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , UpperCAmelCase ) else: # down for down_block in self.down_blocks: lowercase_ = down_block(UpperCAmelCase ) # middle lowercase_ = self.mid_block(UpperCAmelCase ) # post-process lowercase_ = self.conv_norm_out(UpperCAmelCase ) lowercase_ = self.conv_act(UpperCAmelCase ) lowercase_ = self.conv_out(UpperCAmelCase ) return sample class __lowerCamelCase ( nn.Module ): """simple docstring""" def __init__( self , UpperCAmelCase=3 , UpperCAmelCase=3 , UpperCAmelCase=("UpDecoderBlock2D",) , UpperCAmelCase=(64,) , UpperCAmelCase=2 , UpperCAmelCase=32 , UpperCAmelCase="silu" , UpperCAmelCase="group" , ) -> int: '''simple docstring''' super().__init__() lowercase_ = layers_per_block lowercase_ = nn.Convad( UpperCAmelCase , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) lowercase_ = None lowercase_ = nn.ModuleList([] ) lowercase_ = in_channels if norm_type == "spatial" else None # mid lowercase_ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=UpperCAmelCase , output_scale_factor=1 , resnet_time_scale_shift="default" if norm_type == "group" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=UpperCAmelCase , temb_channels=UpperCAmelCase , ) # up lowercase_ = list(reversed(UpperCAmelCase ) ) lowercase_ = reversed_block_out_channels[0] for i, up_block_type in enumerate(UpperCAmelCase ): lowercase_ = output_channel lowercase_ = reversed_block_out_channels[i] lowercase_ = i == len(UpperCAmelCase ) - 1 lowercase_ = get_up_block( UpperCAmelCase , num_layers=self.layers_per_block + 1 , in_channels=UpperCAmelCase , out_channels=UpperCAmelCase , prev_output_channel=UpperCAmelCase , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=UpperCAmelCase , resnet_groups=UpperCAmelCase , attention_head_dim=UpperCAmelCase , temb_channels=UpperCAmelCase , resnet_time_scale_shift=UpperCAmelCase , ) self.up_blocks.append(UpperCAmelCase ) lowercase_ = output_channel # out if norm_type == "spatial": lowercase_ = SpatialNorm(block_out_channels[0] , UpperCAmelCase ) else: lowercase_ = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=UpperCAmelCase , eps=1e-6 ) lowercase_ = nn.SiLU() lowercase_ = nn.Convad(block_out_channels[0] , UpperCAmelCase , 3 , padding=1 ) lowercase_ = False def A__ ( self , UpperCAmelCase , UpperCAmelCase=None ) -> Dict: '''simple docstring''' lowercase_ = z lowercase_ = self.conv_in(UpperCAmelCase ) lowercase_ = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(UpperCAmelCase ): def custom_forward(*UpperCAmelCase ): return module(*UpperCAmelCase ) return custom_forward if is_torch_version(">=" , "1.11.0" ): # middle lowercase_ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , UpperCAmelCase , UpperCAmelCase , use_reentrant=UpperCAmelCase ) lowercase_ = sample.to(UpperCAmelCase ) # up for up_block in self.up_blocks: lowercase_ = torch.utils.checkpoint.checkpoint( create_custom_forward(UpperCAmelCase ) , UpperCAmelCase , UpperCAmelCase , use_reentrant=UpperCAmelCase ) else: # middle lowercase_ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , UpperCAmelCase , UpperCAmelCase ) lowercase_ = sample.to(UpperCAmelCase ) # up for up_block in self.up_blocks: lowercase_ = torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCAmelCase ) , UpperCAmelCase , UpperCAmelCase ) else: # middle lowercase_ = self.mid_block(UpperCAmelCase , UpperCAmelCase ) lowercase_ = sample.to(UpperCAmelCase ) # up for up_block in self.up_blocks: lowercase_ = up_block(UpperCAmelCase , UpperCAmelCase ) # post-process if latent_embeds is None: lowercase_ = self.conv_norm_out(UpperCAmelCase ) else: lowercase_ = self.conv_norm_out(UpperCAmelCase , UpperCAmelCase ) lowercase_ = self.conv_act(UpperCAmelCase ) lowercase_ = self.conv_out(UpperCAmelCase ) return sample class __lowerCamelCase ( nn.Module ): """simple docstring""" def __init__( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase="random" , UpperCAmelCase=False , UpperCAmelCase=True ) -> str: '''simple docstring''' super().__init__() lowercase_ = n_e lowercase_ = vq_embed_dim lowercase_ = beta lowercase_ = legacy lowercase_ = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) lowercase_ = remap if self.remap is not None: self.register_buffer("used" , torch.tensor(np.load(self.remap ) ) ) lowercase_ = self.used.shape[0] lowercase_ = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": lowercase_ = self.re_embed lowercase_ = self.re_embed + 1 print( F'Remapping {self.n_e} indices to {self.re_embed} indices. ' F'Using {self.unknown_index} for unknown indices.' ) else: lowercase_ = n_e lowercase_ = sane_index_shape def A__ ( self , UpperCAmelCase ) -> List[str]: '''simple docstring''' lowercase_ = inds.shape assert len(UpperCAmelCase ) > 1 lowercase_ = inds.reshape(ishape[0] , -1 ) lowercase_ = self.used.to(UpperCAmelCase ) lowercase_ = (inds[:, :, None] == used[None, None, ...]).long() lowercase_ = match.argmax(-1 ) lowercase_ = match.sum(2 ) < 1 if self.unknown_index == "random": lowercase_ = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: lowercase_ = self.unknown_index return new.reshape(UpperCAmelCase ) def A__ ( self , UpperCAmelCase ) -> List[Any]: '''simple docstring''' lowercase_ = inds.shape assert len(UpperCAmelCase ) > 1 lowercase_ = inds.reshape(ishape[0] , -1 ) lowercase_ = self.used.to(UpperCAmelCase ) if self.re_embed > self.used.shape[0]: # extra token lowercase_ = 0 # simply set to zero lowercase_ = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , UpperCAmelCase ) return back.reshape(UpperCAmelCase ) def A__ ( self , UpperCAmelCase ) -> List[Any]: '''simple docstring''' lowercase_ = z.permute(0 , 2 , 3 , 1 ).contiguous() lowercase_ = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z lowercase_ = torch.argmin(torch.cdist(UpperCAmelCase , self.embedding.weight ) , dim=1 ) lowercase_ = self.embedding(UpperCAmelCase ).view(z.shape ) lowercase_ = None lowercase_ = None # compute loss for embedding if not self.legacy: lowercase_ = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: lowercase_ = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients lowercase_ = z + (z_q - z).detach() # reshape back to match original input shape lowercase_ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: lowercase_ = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis lowercase_ = self.remap_to_used(UpperCAmelCase ) lowercase_ = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: lowercase_ = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def A__ ( self , UpperCAmelCase , UpperCAmelCase ) -> int: '''simple docstring''' if self.remap is not None: lowercase_ = indices.reshape(shape[0] , -1 ) # add batch axis lowercase_ = self.unmap_to_all(UpperCAmelCase ) lowercase_ = indices.reshape(-1 ) # flatten again # get quantized latent vectors lowercase_ = self.embedding(UpperCAmelCase ) if shape is not None: lowercase_ = z_q.view(UpperCAmelCase ) # reshape back to match original input shape lowercase_ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class __lowerCamelCase ( snake_case_ ): """simple docstring""" def __init__( self , UpperCAmelCase , UpperCAmelCase=False ) -> List[Any]: '''simple docstring''' lowercase_ = parameters lowercase_ , lowercase_ = torch.chunk(UpperCAmelCase , 2 , dim=1 ) lowercase_ = torch.clamp(self.logvar , -30.0 , 20.0 ) lowercase_ = deterministic lowercase_ = torch.exp(0.5 * self.logvar ) lowercase_ = torch.exp(self.logvar ) if self.deterministic: lowercase_ = lowercase_ = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def A__ ( self , UpperCAmelCase = None ) -> torch.FloatTensor: '''simple docstring''' lowercase_ = randn_tensor( self.mean.shape , generator=UpperCAmelCase , device=self.parameters.device , dtype=self.parameters.dtype ) lowercase_ = self.mean + self.std * sample return x def A__ ( self , UpperCAmelCase=None ) -> Tuple: '''simple docstring''' if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def A__ ( self , UpperCAmelCase , UpperCAmelCase=[1, 2, 3] ) -> Tuple: '''simple docstring''' if self.deterministic: return torch.Tensor([0.0] ) lowercase_ = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=UpperCAmelCase ) def A__ ( self ) -> Tuple: '''simple docstring''' return self.mean
601
import os # Precomputes a list of the 100 first triangular numbers SCREAMING_SNAKE_CASE__ = [int(0.5 * n * (n + 1)) for n in range(1, 1_0_1)] def SCREAMING_SNAKE_CASE_ ( ): '''simple docstring''' lowercase_ = os.path.dirname(os.path.realpath(__lowerCamelCase ) ) lowercase_ = os.path.join(__lowerCamelCase , "words.txt" ) lowercase_ = "" with open(__lowerCamelCase ) as f: lowercase_ = f.readline() lowercase_ = [word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowercase_ = [ word for word in [sum(ord(__lowerCamelCase ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(__lowerCamelCase ) if __name__ == "__main__": print(solution())
601
1
import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class __lowerCAmelCase ( A_ ): _UpperCamelCase : Any = """facebook/bart-large-mnli""" _UpperCamelCase : Tuple = ( """This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which """ """should be the text to classify, and `labels`, which should be the list of labels to use for classification. """ """It returns the most likely label in the list of provided `labels` for the input text.""" ) _UpperCamelCase : List[Any] = """text_classifier""" _UpperCamelCase : Any = AutoTokenizer _UpperCamelCase : List[str] = AutoModelForSequenceClassification _UpperCamelCase : Union[str, Any] = ["""text""", ["""text"""]] _UpperCamelCase : Dict = ["""text"""] def _snake_case ( self ) -> Union[str, Any]: """simple docstring""" super().setup() a__ : List[Any] = self.model.config a__ : Union[str, Any] = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("entail" ): a__ : Tuple = int(snake_case ) if self.entailment_id == -1: raise ValueError("Could not determine the entailment ID from the model config, please pass it at init." ) def _snake_case ( self , snake_case , snake_case ) -> Any: """simple docstring""" a__ : Union[str, Any] = labels return self.pre_processor( [text] * len(snake_case ) , [F"""This example is {label}""" for label in labels] , return_tensors="pt" , padding="max_length" , ) def _snake_case ( self , snake_case ) -> Any: """simple docstring""" a__ : int = outputs.logits a__ : List[Any] = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
112
"""simple docstring""" def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : str = len(__snake_case ) _lowerCamelCase : Union[str, Any] = len(__snake_case ) _lowerCamelCase : int = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] _lowerCamelCase : Union[str, Any] = True for i in range(__snake_case ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: _lowerCamelCase : Tuple = True if a[i].islower(): _lowerCamelCase : Tuple = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
88
0
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def UpperCamelCase ( __lowercase : List[Any] ): '''simple docstring''' return sum(param.float().sum() if 'encoder.embeddings' not in key else 0 for key, param in state_dict.items() ) def UpperCamelCase ( __lowercase : List[str] ,__lowercase : Optional[Any] ): '''simple docstring''' A_ : Dict = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue A_ : Optional[Any] = key.replace('heads.cmd.mim_head.cls.predictions' ,'mmm_image_head' ) A_ : Optional[Any] = key.replace('heads.cmd.mlm_head.cls.predictions' ,'mmm_text_head' ) A_ : Tuple = key.replace('heads.cmd.itm_head.cls' ,'itm_head' ) A_ : List[str] = key.replace('heads.cmd.itm_head.pooler' ,'itm_head.pooler' ) A_ : Optional[int] = key.replace('heads.cmd.clip_head.logit_scale' ,'flava.logit_scale' ) A_ : Union[str, Any] = key.replace('heads.fairseq_mlm.cls.predictions' ,'mlm_head' ) A_ : List[Any] = key.replace('heads.imagenet.mim_head.cls.predictions' ,'mim_head' ) A_ : List[str] = key.replace('mm_text_projection' ,'flava.text_to_mm_projection' ) A_ : Tuple = key.replace('mm_image_projection' ,'flava.image_to_mm_projection' ) A_ : Optional[int] = key.replace('image_encoder.module' ,'flava.image_model' ) A_ : Union[str, Any] = key.replace('text_encoder.module' ,'flava.text_model' ) A_ : Dict = key.replace('mm_encoder.module.encoder.cls_token' ,'flava.multimodal_model.cls_token' ) A_ : int = key.replace('mm_encoder.module' ,'flava.multimodal_model' ) A_ : List[Any] = key.replace('text_projection' ,'flava.text_projection' ) A_ : Optional[int] = key.replace('image_projection' ,'flava.image_projection' ) A_ : List[str] = value.float() for key, value in codebook_state_dict.items(): A_ : int = value return upgrade @torch.no_grad() def UpperCamelCase ( __lowercase : int ,__lowercase : Tuple ,__lowercase : Tuple ,__lowercase : Tuple=None ): '''simple docstring''' if config_path is not None: A_ : List[str] = FlavaConfig.from_pretrained(__lowercase ) else: A_ : Dict = FlavaConfig() A_ : Union[str, Any] = FlavaForPreTraining(__lowercase ).eval() A_ : int = convert_dalle_checkpoint(__lowercase ,__lowercase ,save_checkpoint=__lowercase ) if os.path.exists(__lowercase ): A_ : str = torch.load(__lowercase ,map_location='cpu' ) else: A_ : Optional[int] = torch.hub.load_state_dict_from_url(__lowercase ,map_location='cpu' ) A_ : Any = upgrade_state_dict(__lowercase ,__lowercase ) hf_model.load_state_dict(__lowercase ) A_ : Optional[int] = hf_model.state_dict() A_ : List[str] = count_parameters(__lowercase ) A_ : int = count_parameters(__lowercase ) + count_parameters(__lowercase ) assert torch.allclose(__lowercase ,__lowercase ,atol=1e-3 ) hf_model.save_pretrained(__lowercase ) if __name__ == "__main__": _UpperCAmelCase = 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 flava checkpoint""") parser.add_argument("""--codebook_path""", default=None, type=str, help="""Path to flava codebook checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") _UpperCAmelCase = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
703
def UpperCamelCase ( __lowercase : str ): '''simple docstring''' A_ : int = len(__lowercase ) A_ : List[Any] = sum(__lowercase ) A_ : List[str] = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 ,n + 1 ): A_ : Optional[Any] = True for i in range(1 ,s + 1 ): A_ : Tuple = False for i in range(1 ,n + 1 ): for j in range(1 ,s + 1 ): A_ : Dict = dp[i][j - 1] if arr[i - 1] <= j: A_ : Dict = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) ,-1 ,-1 ): if dp[n][j] is True: A_ : List[Any] = s - 2 * j break return diff
70
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowerCamelCase : Tuple = logging.get_logger(__name__) __lowerCamelCase : Optional[Any] = { """xlm-mlm-en-2048""": """https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json""", """xlm-mlm-ende-1024""": """https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json""", """xlm-mlm-enfr-1024""": """https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json""", """xlm-mlm-enro-1024""": """https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json""", """xlm-mlm-tlm-xnli15-1024""": """https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json""", """xlm-mlm-xnli15-1024""": """https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json""", """xlm-clm-enfr-1024""": """https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json""", """xlm-clm-ende-1024""": """https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json""", """xlm-mlm-17-1280""": """https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json""", """xlm-mlm-100-1280""": """https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json""", } class lowerCAmelCase__ ( UpperCamelCase__ ): A = "xlm" A = { "hidden_size": "emb_dim", "num_attention_heads": "n_heads", "num_hidden_layers": "n_layers", "n_words": "vocab_size", # For backward compatibility } def __init__( self : str , UpperCamelCase_ : int=30_145 , UpperCamelCase_ : Dict=2_048 , UpperCamelCase_ : Optional[Any]=12 , UpperCamelCase_ : Optional[int]=16 , UpperCamelCase_ : Optional[int]=0.1 , UpperCamelCase_ : Optional[Any]=0.1 , UpperCamelCase_ : Optional[Any]=True , UpperCamelCase_ : Optional[Any]=False , UpperCamelCase_ : Any=False , UpperCamelCase_ : List[str]=False , UpperCamelCase_ : Optional[int]=1 , UpperCamelCase_ : Union[str, Any]=True , UpperCamelCase_ : Dict=512 , UpperCamelCase_ : Union[str, Any]=2_048**-0.5 , UpperCamelCase_ : Optional[int]=1e-1_2 , UpperCamelCase_ : Tuple=0.02 , UpperCamelCase_ : Any=0 , UpperCamelCase_ : Optional[Any]=1 , UpperCamelCase_ : Union[str, Any]=2 , UpperCamelCase_ : Tuple=3 , UpperCamelCase_ : Union[str, Any]=5 , UpperCamelCase_ : Tuple=True , UpperCamelCase_ : Dict="first" , UpperCamelCase_ : Optional[Any]=True , UpperCamelCase_ : List[Any]=None , UpperCamelCase_ : Tuple=True , UpperCamelCase_ : List[Any]=0.1 , UpperCamelCase_ : Union[str, Any]=5 , UpperCamelCase_ : int=5 , UpperCamelCase_ : Optional[int]=0 , UpperCamelCase_ : int=0 , UpperCamelCase_ : int=2 , UpperCamelCase_ : Optional[int]=0 , **UpperCamelCase_ : Optional[Any] , ) -> Dict: """simple docstring""" lowerCamelCase_ : Optional[Any] = vocab_size lowerCamelCase_ : Optional[Any] = emb_dim lowerCamelCase_ : List[Any] = n_layers lowerCamelCase_ : Tuple = n_heads lowerCamelCase_ : List[Any] = dropout lowerCamelCase_ : Union[str, Any] = attention_dropout lowerCamelCase_ : List[str] = gelu_activation lowerCamelCase_ : Optional[int] = sinusoidal_embeddings lowerCamelCase_ : List[Any] = causal lowerCamelCase_ : Optional[Any] = asm lowerCamelCase_ : Optional[int] = n_langs lowerCamelCase_ : Tuple = use_lang_emb lowerCamelCase_ : Any = layer_norm_eps lowerCamelCase_ : Optional[Any] = bos_index lowerCamelCase_ : Any = eos_index lowerCamelCase_ : Optional[int] = pad_index lowerCamelCase_ : Dict = unk_index lowerCamelCase_ : List[Any] = mask_index lowerCamelCase_ : List[str] = is_encoder lowerCamelCase_ : Dict = max_position_embeddings lowerCamelCase_ : Any = embed_init_std lowerCamelCase_ : List[str] = init_std lowerCamelCase_ : List[Any] = summary_type lowerCamelCase_ : Union[str, Any] = summary_use_proj lowerCamelCase_ : Optional[Any] = summary_activation lowerCamelCase_ : Optional[Any] = summary_proj_to_labels lowerCamelCase_ : Union[str, Any] = summary_first_dropout lowerCamelCase_ : Optional[int] = start_n_top lowerCamelCase_ : str = end_n_top lowerCamelCase_ : Any = mask_token_id lowerCamelCase_ : Tuple = lang_id if "n_words" in kwargs: lowerCamelCase_ : Tuple = kwargs['''n_words'''] super().__init__(pad_token_id=snake_case_ , bos_token_id=snake_case_ , **snake_case_ ) class lowerCAmelCase__ ( UpperCamelCase__ ): @property def __UpperCamelCase ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": lowerCamelCase_ : Tuple = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: lowerCamelCase_ : Optional[int] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
501
import math import tensorflow as tf from packaging import version def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] =tf.convert_to_tensor(__a ) SCREAMING_SNAKE_CASE : Union[str, Any] =0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) )) return x * cdf def lowerCAmelCase_ ( __a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] =tf.convert_to_tensor(__a ) SCREAMING_SNAKE_CASE : str =tf.cast(math.pi , x.dtype ) SCREAMING_SNAKE_CASE : Optional[Any] =tf.cast(0.044715 , x.dtype ) SCREAMING_SNAKE_CASE : Dict =0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(__a , 3 )) )) return x * cdf def lowerCAmelCase_ ( __a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple =tf.convert_to_tensor(__a ) return x * tf.tanh(tf.math.softplus(__a ) ) def lowerCAmelCase_ ( __a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Any =tf.convert_to_tensor(__a ) SCREAMING_SNAKE_CASE : Optional[Any] =tf.cast(0.044715 , x.dtype ) SCREAMING_SNAKE_CASE : Union[str, Any] =tf.cast(0.7978845608 , x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] =tf.convert_to_tensor(__a ) SCREAMING_SNAKE_CASE : List[str] =tf.cast(1.702 , x.dtype ) return x * tf.math.sigmoid(coeff * x ) def lowerCAmelCase_ ( __a ) -> str: """simple docstring""" return tf.clip_by_value(_gelu(__a ) , -10 , 10 ) def lowerCAmelCase_ ( __a , __a=-1 ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] =tf.split(__a , 2 , axis=__a ) return a * tf.math.sigmoid(__a ) if version.parse(tf.version.VERSION) >= version.parse("""2.4"""): def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" return tf.keras.activations.gelu(__a , approximate=__a ) _A = tf.keras.activations.gelu _A = approximate_gelu_wrap else: _A = _gelu _A = _gelu_new _A = { """gelu""": gelu, """gelu_10""": gelu_aa, """gelu_fast""": gelu_fast, """gelu_new""": gelu_new, """glu""": glu, """mish""": mish, """quick_gelu""": quick_gelu, """relu""": tf.keras.activations.relu, """sigmoid""": tf.keras.activations.sigmoid, """silu""": tf.keras.activations.swish, """swish""": tf.keras.activations.swish, """tanh""": tf.keras.activations.tanh, } def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(f'function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}' )
258
0
'''simple docstring''' import os from collections.abc import Iterator def __lowerCamelCase ( snake_case__ = "." ) -> int: """simple docstring""" for dir_path, dir_names, filenames in os.walk(A__ ): _SCREAMING_SNAKE_CASE = [d for d in dir_names if d != """scripts""" and d[0] not in """._"""] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(A__ )[1] in (".py", ".ipynb"): yield os.path.join(A__ ,A__ ).lstrip("""./""" ) def __lowerCamelCase ( snake_case__ ) -> str: """simple docstring""" return F'{i * " "}*' if i else "\n##" def __lowerCamelCase ( snake_case__ ,snake_case__ ) -> List[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE = old_path.split(os.sep ) for i, new_part in enumerate(new_path.split(os.sep ) ): if (i + 1 > len(A__ ) or old_parts[i] != new_part) and new_part: print(F'{md_prefix(A__ )} {new_part.replace("_" ," " ).title()}' ) return new_path def __lowerCamelCase ( snake_case__ = "." ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE = """""" for filepath in sorted(good_file_paths(A__ ) ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = os.path.split(A__ ) if filepath != old_path: _SCREAMING_SNAKE_CASE = print_path(A__ ,A__ ) _SCREAMING_SNAKE_CASE = (filepath.count(os.sep ) + 1) if filepath else 0 _SCREAMING_SNAKE_CASE = F'{filepath}/{filename}'.replace(""" """ ,"""%20""" ) _SCREAMING_SNAKE_CASE = os.path.splitext(filename.replace("""_""" ,""" """ ).title() )[0] print(F'{md_prefix(A__ )} [{filename}]({url})' ) if __name__ == "__main__": print_directory_md('''.''')
714
from ..utils import is_flax_available, is_torch_available if is_torch_available(): from .autoencoder_kl import AutoencoderKL from .controlnet import ControlNetModel from .dual_transformer_ad import DualTransformeraDModel from .modeling_utils import ModelMixin from .prior_transformer import PriorTransformer from .ta_film_transformer import TaFilmDecoder from .transformer_ad import TransformeraDModel from .unet_ad import UNetaDModel from .unet_ad import UNetaDModel from .unet_ad_condition import UNetaDConditionModel from .unet_ad_condition import UNetaDConditionModel from .vq_model import VQModel if is_flax_available(): from .controlnet_flax import FlaxControlNetModel from .unet_ad_condition_flax import FlaxUNetaDConditionModel from .vae_flax import FlaxAutoencoderKL
569
0
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. __SCREAMING_SNAKE_CASE = {'LayoutLMv2Config', 'LayoutLMv3Config'} @is_pipeline_test class __UpperCamelCase ( unittest.TestCase ): lowercase_ : List[Any] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING lowercase_ : Optional[int] = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: lowercase_ : List[str] = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: lowercase_ : List[Any] = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def UpperCAmelCase__ ( self : Any ) -> Any: lowerCAmelCase :Optional[int] = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='pt' ) lowerCAmelCase :int = text_classifier('This is great !' ) self.assertEqual(nested_simplify(UpperCAmelCase ) , [{'label': 'LABEL_0', 'score': 0.5_0_4}] ) lowerCAmelCase :Dict = text_classifier('This is great !' , top_k=2 ) self.assertEqual( nested_simplify(UpperCAmelCase ) , [{'label': 'LABEL_0', 'score': 0.5_0_4}, {'label': 'LABEL_1', 'score': 0.4_9_6}] ) lowerCAmelCase :Dict = text_classifier(['This is great !', 'This is bad'] , top_k=2 ) self.assertEqual( nested_simplify(UpperCAmelCase ) , [ [{'label': 'LABEL_0', 'score': 0.5_0_4}, {'label': 'LABEL_1', 'score': 0.4_9_6}], [{'label': 'LABEL_0', 'score': 0.5_0_4}, {'label': 'LABEL_1', 'score': 0.4_9_6}], ] , ) lowerCAmelCase :int = text_classifier('This is great !' , top_k=1 ) self.assertEqual(nested_simplify(UpperCAmelCase ) , [{'label': 'LABEL_0', 'score': 0.5_0_4}] ) # Legacy behavior lowerCAmelCase :List[Any] = text_classifier('This is great !' , return_all_scores=UpperCAmelCase ) self.assertEqual(nested_simplify(UpperCAmelCase ) , [{'label': 'LABEL_0', 'score': 0.5_0_4}] ) lowerCAmelCase :List[str] = text_classifier('This is great !' , return_all_scores=UpperCAmelCase ) self.assertEqual( nested_simplify(UpperCAmelCase ) , [[{'label': 'LABEL_0', 'score': 0.5_0_4}, {'label': 'LABEL_1', 'score': 0.4_9_6}]] ) lowerCAmelCase :List[Any] = text_classifier(['This is great !', 'Something else'] , return_all_scores=UpperCAmelCase ) self.assertEqual( nested_simplify(UpperCAmelCase ) , [ [{'label': 'LABEL_0', 'score': 0.5_0_4}, {'label': 'LABEL_1', 'score': 0.4_9_6}], [{'label': 'LABEL_0', 'score': 0.5_0_4}, {'label': 'LABEL_1', 'score': 0.4_9_6}], ] , ) lowerCAmelCase :Dict = text_classifier(['This is great !', 'Something else'] , return_all_scores=UpperCAmelCase ) self.assertEqual( nested_simplify(UpperCAmelCase ) , [ {'label': 'LABEL_0', 'score': 0.5_0_4}, {'label': 'LABEL_0', 'score': 0.5_0_4}, ] , ) @require_torch def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[int]: import torch lowerCAmelCase :List[str] = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='pt' , device=torch.device('cpu' ) , ) lowerCAmelCase :List[Any] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(UpperCAmelCase ) , [{'label': 'LABEL_0', 'score': 0.5_0_4}] ) @require_tf def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: lowerCAmelCase :Any = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='tf' ) lowerCAmelCase :Optional[int] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(UpperCAmelCase ) , [{'label': 'LABEL_0', 'score': 0.5_0_4}] ) @slow @require_torch def UpperCAmelCase__ ( self : int ) -> Tuple: lowerCAmelCase :Optional[Any] = pipeline('text-classification' ) lowerCAmelCase :str = text_classifier('This is great !' ) self.assertEqual(nested_simplify(UpperCAmelCase ) , [{'label': 'POSITIVE', 'score': 1.0}] ) lowerCAmelCase :Dict = text_classifier('This is bad !' ) self.assertEqual(nested_simplify(UpperCAmelCase ) , [{'label': 'NEGATIVE', 'score': 1.0}] ) lowerCAmelCase :int = text_classifier('Birds are a type of animal' ) self.assertEqual(nested_simplify(UpperCAmelCase ) , [{'label': 'POSITIVE', 'score': 0.9_8_8}] ) @slow @require_tf def UpperCAmelCase__ ( self : List[Any] ) -> Dict: lowerCAmelCase :List[str] = pipeline('text-classification' , framework='tf' ) lowerCAmelCase :Tuple = text_classifier('This is great !' ) self.assertEqual(nested_simplify(UpperCAmelCase ) , [{'label': 'POSITIVE', 'score': 1.0}] ) lowerCAmelCase :Any = text_classifier('This is bad !' ) self.assertEqual(nested_simplify(UpperCAmelCase ) , [{'label': 'NEGATIVE', 'score': 1.0}] ) lowerCAmelCase :str = text_classifier('Birds are a type of animal' ) self.assertEqual(nested_simplify(UpperCAmelCase ) , [{'label': 'POSITIVE', 'score': 0.9_8_8}] ) def UpperCAmelCase__ ( self : List[str] , UpperCAmelCase : int , UpperCAmelCase : List[str] , UpperCAmelCase : List[str] ) -> Any: lowerCAmelCase :Any = TextClassificationPipeline(model=UpperCAmelCase , tokenizer=UpperCAmelCase ) return text_classifier, ["HuggingFace is in", "This is another test"] def UpperCAmelCase__ ( self : List[str] , UpperCAmelCase : Dict , UpperCAmelCase : Dict ) -> Optional[int]: lowerCAmelCase :int = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 lowerCAmelCase :List[Any] = 'HuggingFace is in' lowerCAmelCase :Optional[int] = text_classifier(UpperCAmelCase ) self.assertEqual(nested_simplify(UpperCAmelCase ) , [{'label': ANY(UpperCAmelCase ), 'score': ANY(UpperCAmelCase )}] ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() ) lowerCAmelCase :Any = ['HuggingFace is in ', 'Paris is in France'] lowerCAmelCase :str = text_classifier(UpperCAmelCase ) self.assertEqual( nested_simplify(UpperCAmelCase ) , [{'label': ANY(UpperCAmelCase ), 'score': ANY(UpperCAmelCase )}, {'label': ANY(UpperCAmelCase ), 'score': ANY(UpperCAmelCase )}] , ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() ) self.assertTrue(outputs[1]['label'] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format lowerCAmelCase :Tuple = text_classifier(UpperCAmelCase , top_k=UpperCAmelCase ) lowerCAmelCase :Dict = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(UpperCAmelCase ) , [[{'label': ANY(UpperCAmelCase ), 'score': ANY(UpperCAmelCase )}] * N, [{'label': ANY(UpperCAmelCase ), 'score': ANY(UpperCAmelCase )}] * N] , ) lowerCAmelCase :int = {'text': 'HuggingFace is in ', 'text_pair': 'Paris is in France'} lowerCAmelCase :Union[str, Any] = text_classifier(UpperCAmelCase ) self.assertEqual( nested_simplify(UpperCAmelCase ) , {'label': ANY(UpperCAmelCase ), 'score': ANY(UpperCAmelCase )} , ) self.assertTrue(outputs['label'] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. lowerCAmelCase :Union[str, Any] = [['HuggingFace is in ', 'Paris is in France']] with self.assertRaises(UpperCAmelCase ): text_classifier(UpperCAmelCase ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility lowerCAmelCase :Optional[int] = text_classifier([[['HuggingFace is in ', 'Paris is in France']]] ) self.assertEqual( nested_simplify(UpperCAmelCase ) , [{'label': ANY(UpperCAmelCase ), 'score': ANY(UpperCAmelCase )}] , ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() )
553
"""simple docstring""" import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase ( a__ , a__ , a__ ): '''simple docstring''' lowerCAmelCase :Tuple = MobileBertConfig.from_json_file(a__ ) print(F"""Building PyTorch model from configuration: {config}""" ) lowerCAmelCase :Tuple = MobileBertForPreTraining(a__ ) # Load weights from tf checkpoint lowerCAmelCase :Any = load_tf_weights_in_mobilebert(a__ , a__ , a__ ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , a__ ) if __name__ == "__main__": __SCREAMING_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.' ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
553
1
"""simple docstring""" import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) __lowerCAmelCase : List[str] = { '''sample_size''': 32, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 2, '''num_class_embeds''': 1000, '''block_out_channels''': [32, 64], '''attention_head_dim''': 8, '''down_block_types''': [ '''ResnetDownsampleBlock2D''', '''AttnDownBlock2D''', ], '''up_block_types''': [ '''AttnUpBlock2D''', '''ResnetUpsampleBlock2D''', ], '''resnet_time_scale_shift''': '''scale_shift''', '''upsample_type''': '''resnet''', '''downsample_type''': '''resnet''', } __lowerCAmelCase : List[str] = { '''sample_size''': 64, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 3, '''num_class_embeds''': 1000, '''block_out_channels''': [192, 192 * 2, 192 * 3, 192 * 4], '''attention_head_dim''': 64, '''down_block_types''': [ '''ResnetDownsampleBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', ], '''up_block_types''': [ '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''ResnetUpsampleBlock2D''', ], '''resnet_time_scale_shift''': '''scale_shift''', '''upsample_type''': '''resnet''', '''downsample_type''': '''resnet''', } __lowerCAmelCase : List[Any] = { '''sample_size''': 256, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 2, '''num_class_embeds''': None, '''block_out_channels''': [256, 256, 256 * 2, 256 * 2, 256 * 4, 256 * 4], '''attention_head_dim''': 64, '''down_block_types''': [ '''ResnetDownsampleBlock2D''', '''ResnetDownsampleBlock2D''', '''ResnetDownsampleBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', ], '''up_block_types''': [ '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''ResnetUpsampleBlock2D''', '''ResnetUpsampleBlock2D''', '''ResnetUpsampleBlock2D''', ], '''resnet_time_scale_shift''': '''default''', '''upsample_type''': '''resnet''', '''downsample_type''': '''resnet''', } __lowerCAmelCase : Union[str, Any] = { '''num_train_timesteps''': 40, '''sigma_min''': 0.002, '''sigma_max''': 80.0, } __lowerCAmelCase : List[Any] = { '''num_train_timesteps''': 201, '''sigma_min''': 0.002, '''sigma_max''': 80.0, } __lowerCAmelCase : Optional[Any] = { '''num_train_timesteps''': 151, '''sigma_min''': 0.002, '''sigma_max''': 80.0, } def __snake_case ( UpperCamelCase ) -> List[Any]: """simple docstring""" if isinstance(UpperCamelCase , UpperCamelCase ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError('''boolean value expected''' ) def __snake_case ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase=False ) -> Optional[Any]: """simple docstring""" a__ = checkpoint[f"{old_prefix}.in_layers.0.weight"] a__ = checkpoint[f"{old_prefix}.in_layers.0.bias"] a__ = checkpoint[f"{old_prefix}.in_layers.2.weight"] a__ = checkpoint[f"{old_prefix}.in_layers.2.bias"] a__ = checkpoint[f"{old_prefix}.emb_layers.1.weight"] a__ = checkpoint[f"{old_prefix}.emb_layers.1.bias"] a__ = checkpoint[f"{old_prefix}.out_layers.0.weight"] a__ = checkpoint[f"{old_prefix}.out_layers.0.bias"] a__ = checkpoint[f"{old_prefix}.out_layers.3.weight"] a__ = checkpoint[f"{old_prefix}.out_layers.3.bias"] if has_skip: a__ = checkpoint[f"{old_prefix}.skip_connection.weight"] a__ = checkpoint[f"{old_prefix}.skip_connection.bias"] return new_checkpoint def __snake_case ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase=None ) -> List[Any]: """simple docstring""" a__ , a__ , a__ = checkpoint[f"{old_prefix}.qkv.weight"].chunk(3 , dim=0 ) a__ , a__ , a__ = checkpoint[f"{old_prefix}.qkv.bias"].chunk(3 , dim=0 ) a__ = checkpoint[f"{old_prefix}.norm.weight"] a__ = checkpoint[f"{old_prefix}.norm.bias"] a__ = weight_q.squeeze(-1 ).squeeze(-1 ) a__ = bias_q.squeeze(-1 ).squeeze(-1 ) a__ = weight_k.squeeze(-1 ).squeeze(-1 ) a__ = bias_k.squeeze(-1 ).squeeze(-1 ) a__ = weight_v.squeeze(-1 ).squeeze(-1 ) a__ = bias_v.squeeze(-1 ).squeeze(-1 ) a__ = ( checkpoint[f"{old_prefix}.proj_out.weight"].squeeze(-1 ).squeeze(-1 ) ) a__ = checkpoint[f"{old_prefix}.proj_out.bias"].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def __snake_case ( UpperCamelCase , UpperCamelCase ) -> Tuple: """simple docstring""" a__ = torch.load(UpperCamelCase , map_location='''cpu''' ) a__ = {} a__ = checkpoint['''time_embed.0.weight'''] a__ = checkpoint['''time_embed.0.bias'''] a__ = checkpoint['''time_embed.2.weight'''] a__ = checkpoint['''time_embed.2.bias'''] if unet_config["num_class_embeds"] is not None: a__ = checkpoint['''label_emb.weight'''] a__ = checkpoint['''input_blocks.0.0.weight'''] a__ = checkpoint['''input_blocks.0.0.bias'''] a__ = unet_config['''down_block_types'''] a__ = unet_config['''layers_per_block'''] a__ = unet_config['''attention_head_dim'''] a__ = unet_config['''block_out_channels'''] a__ = 1 a__ = channels_list[0] for i, layer_type in enumerate(UpperCamelCase ): a__ = channels_list[i] a__ = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(UpperCamelCase ): a__ = f"down_blocks.{i}.resnets.{j}" a__ = f"input_blocks.{current_layer}.0" a__ = True if j == 0 and downsample_block_has_skip else False a__ = convert_resnet(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , has_skip=UpperCamelCase ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(UpperCamelCase ): a__ = f"down_blocks.{i}.resnets.{j}" a__ = f"input_blocks.{current_layer}.0" a__ = True if j == 0 and downsample_block_has_skip else False a__ = convert_resnet(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , has_skip=UpperCamelCase ) a__ = f"down_blocks.{i}.attentions.{j}" a__ = f"input_blocks.{current_layer}.1" a__ = convert_attention( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) current_layer += 1 if i != len(UpperCamelCase ) - 1: a__ = f"down_blocks.{i}.downsamplers.0" a__ = f"input_blocks.{current_layer}.0" a__ = convert_resnet(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) current_layer += 1 a__ = current_channels # hardcoded the mid-block for now a__ = '''mid_block.resnets.0''' a__ = '''middle_block.0''' a__ = convert_resnet(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) a__ = '''mid_block.attentions.0''' a__ = '''middle_block.1''' a__ = convert_attention(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) a__ = '''mid_block.resnets.1''' a__ = '''middle_block.2''' a__ = convert_resnet(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) a__ = 0 a__ = unet_config['''up_block_types'''] for i, layer_type in enumerate(UpperCamelCase ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): a__ = f"up_blocks.{i}.resnets.{j}" a__ = f"output_blocks.{current_layer}.0" a__ = convert_resnet(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , has_skip=UpperCamelCase ) current_layer += 1 if i != len(UpperCamelCase ) - 1: a__ = f"up_blocks.{i}.upsamplers.0" a__ = f"output_blocks.{current_layer-1}.1" a__ = convert_resnet(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): a__ = f"up_blocks.{i}.resnets.{j}" a__ = f"output_blocks.{current_layer}.0" a__ = convert_resnet(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , has_skip=UpperCamelCase ) a__ = f"up_blocks.{i}.attentions.{j}" a__ = f"output_blocks.{current_layer}.1" a__ = convert_attention( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) current_layer += 1 if i != len(UpperCamelCase ) - 1: a__ = f"up_blocks.{i}.upsamplers.0" a__ = f"output_blocks.{current_layer-1}.2" a__ = convert_resnet(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) a__ = checkpoint['''out.0.weight'''] a__ = checkpoint['''out.0.bias'''] a__ = checkpoint['''out.2.weight'''] a__ = checkpoint['''out.2.bias'''] return new_checkpoint if __name__ == "__main__": __lowerCAmelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument('''--unet_path''', default=None, type=str, required=True, help='''Path to the unet.pt to convert.''') parser.add_argument( '''--dump_path''', default=None, type=str, required=True, help='''Path to output the converted UNet model.''' ) parser.add_argument('''--class_cond''', default=True, type=str, help='''Whether the model is class-conditional.''') __lowerCAmelCase : str = parser.parse_args() __lowerCAmelCase : Union[str, Any] = strabool(args.class_cond) __lowerCAmelCase : int = os.path.basename(args.unet_path) print(f"Checkpoint: {ckpt_name}") # Get U-Net config if "imagenet64" in ckpt_name: __lowerCAmelCase : List[str] = IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): __lowerCAmelCase : Optional[Any] = LSUN_256_UNET_CONFIG elif "test" in ckpt_name: __lowerCAmelCase : Optional[Any] = TEST_UNET_CONFIG else: raise ValueError(f"Checkpoint type {ckpt_name} is not currently supported.") if not args.class_cond: __lowerCAmelCase : int = None __lowerCAmelCase : List[str] = con_pt_to_diffuser(args.unet_path, unet_config) __lowerCAmelCase : Union[str, Any] = UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: __lowerCAmelCase : Union[str, Any] = CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: __lowerCAmelCase : int = CT_IMAGENET_64_SCHEDULER_CONFIG elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): __lowerCAmelCase : Any = CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(f"Checkpoint type {ckpt_name} is not currently supported.") __lowerCAmelCase : Any = CMStochasticIterativeScheduler(**scheduler_config) __lowerCAmelCase : Optional[Any] = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
158
"""simple docstring""" from __future__ import annotations __lowerCAmelCase : Optional[int] = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def __snake_case ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , ) -> tuple[list[list[int]], list[list[int]]]: """simple docstring""" a__ = [ [0 for col in range(len(grid[0] ) )] for row in range(len(UpperCamelCase ) ) ] # the reference grid a__ = 1 a__ = [ [0 for col in range(len(grid[0] ) )] for row in range(len(UpperCamelCase ) ) ] # the action grid a__ = init[0] a__ = init[1] a__ = 0 a__ = g + heuristic[x][y] # cost from starting cell to destination cell a__ = [[f, g, x, y]] a__ = False # flag that is set when search is complete a__ = False # flag set if we can't find expand while not found and not resign: if len(UpperCamelCase ) == 0: raise ValueError('''Algorithm is unable to find solution''' ) else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() a__ = cell.pop() a__ = next_cell[2] a__ = next_cell[3] a__ = next_cell[1] if x == goal[0] and y == goal[1]: a__ = True else: for i in range(len(UpperCamelCase ) ): # to try out different valid actions a__ = x + DIRECTIONS[i][0] a__ = y + DIRECTIONS[i][1] if xa >= 0 and xa < len(UpperCamelCase ) and ya >= 0 and ya < len(grid[0] ): if closed[xa][ya] == 0 and grid[xa][ya] == 0: a__ = g + cost a__ = ga + heuristic[xa][ya] cell.append([fa, ga, xa, ya] ) a__ = 1 a__ = i a__ = [] a__ = goal[0] a__ = goal[1] invpath.append([x, y] ) # we get the reverse path from here while x != init[0] or y != init[1]: a__ = x - DIRECTIONS[action[x][y]][0] a__ = y - DIRECTIONS[action[x][y]][1] a__ = xa a__ = ya invpath.append([x, y] ) a__ = [] for i in range(len(UpperCamelCase ) ): path.append(invpath[len(UpperCamelCase ) - 1 - i] ) return path, action if __name__ == "__main__": __lowerCAmelCase : Any = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] __lowerCAmelCase : Optional[Any] = [0, 0] # all coordinates are given in format [y,x] __lowerCAmelCase : Optional[Any] = [len(grid) - 1, len(grid[0]) - 1] __lowerCAmelCase : Optional[int] = 1 # the cost map which pushes the path closer to the goal __lowerCAmelCase : str = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): __lowerCAmelCase : Optional[int] = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map __lowerCAmelCase : Optional[Any] = 99 __lowerCAmelCase ,__lowerCAmelCase : Optional[int] = search(grid, init, goal, cost, heuristic) print('''ACTION MAP''') for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
158
1
"""simple docstring""" import unittest from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow if is_flax_available(): import jax from transformers.models.auto.modeling_flax_auto import FlaxAutoModel from transformers.models.bert.modeling_flax_bert import FlaxBertModel from transformers.models.roberta.modeling_flax_roberta import FlaxRobertaModel @require_flax class a_ ( unittest.TestCase ): @slow def _snake_case ( self : List[str] ) ->Dict: '''simple docstring''' for model_name in ["bert-base-cased", "bert-large-uncased"]: with self.subTest(__UpperCamelCase ): _UpperCAmelCase = AutoConfig.from_pretrained(__UpperCamelCase ) self.assertIsNotNone(__UpperCamelCase ) self.assertIsInstance(__UpperCamelCase , __UpperCamelCase ) _UpperCAmelCase = FlaxAutoModel.from_pretrained(__UpperCamelCase ) self.assertIsNotNone(__UpperCamelCase ) self.assertIsInstance(__UpperCamelCase , __UpperCamelCase ) @slow def _snake_case ( self : Union[str, Any] ) ->Union[str, Any]: '''simple docstring''' for model_name in ["roberta-base", "roberta-large"]: with self.subTest(__UpperCamelCase ): _UpperCAmelCase = AutoConfig.from_pretrained(__UpperCamelCase ) self.assertIsNotNone(__UpperCamelCase ) self.assertIsInstance(__UpperCamelCase , __UpperCamelCase ) _UpperCAmelCase = FlaxAutoModel.from_pretrained(__UpperCamelCase ) self.assertIsNotNone(__UpperCamelCase ) self.assertIsInstance(__UpperCamelCase , __UpperCamelCase ) @slow def _snake_case ( self : Optional[Any] ) ->Tuple: '''simple docstring''' for model_name in ["bert-base-cased", "bert-large-uncased"]: _UpperCAmelCase = AutoTokenizer.from_pretrained(__UpperCamelCase ) _UpperCAmelCase = FlaxBertModel.from_pretrained(__UpperCamelCase ) _UpperCAmelCase = tokenizer("""Do you support jax jitted function?""" , return_tensors=TensorType.JAX ) @jax.jit def eval(**__UpperCamelCase : Tuple ): return model(**__UpperCamelCase ) eval(**__UpperCamelCase ).block_until_ready() @slow def _snake_case ( self : Optional[int] ) ->Union[str, Any]: '''simple docstring''' for model_name in ["roberta-base", "roberta-large"]: _UpperCAmelCase = AutoTokenizer.from_pretrained(__UpperCamelCase ) _UpperCAmelCase = FlaxRobertaModel.from_pretrained(__UpperCamelCase ) _UpperCAmelCase = tokenizer("""Do you support jax jitted function?""" , return_tensors=TensorType.JAX ) @jax.jit def eval(**__UpperCamelCase : Union[str, Any] ): return model(**__UpperCamelCase ) eval(**__UpperCamelCase ).block_until_ready() def _snake_case ( self : Optional[int] ) ->Optional[int]: '''simple docstring''' with self.assertRaisesRegex( __UpperCamelCase , """bert-base is not a local folder and is not a valid model identifier""" ): _UpperCAmelCase = FlaxAutoModel.from_pretrained("""bert-base""" ) def _snake_case ( self : Tuple ) ->Optional[Any]: '''simple docstring''' with self.assertRaisesRegex( __UpperCamelCase , r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): _UpperCAmelCase = FlaxAutoModel.from_pretrained(__UpperCamelCase , revision="""aaaaaa""" ) def _snake_case ( self : Dict ) ->str: '''simple docstring''' with self.assertRaisesRegex( __UpperCamelCase , """hf-internal-testing/config-no-model does not appear to have a file named flax_model.msgpack""" , ): _UpperCAmelCase = FlaxAutoModel.from_pretrained("""hf-internal-testing/config-no-model""" ) def _snake_case ( self : Dict ) ->List[Any]: '''simple docstring''' with self.assertRaisesRegex(__UpperCamelCase , """Use `from_pt=True` to load this model""" ): _UpperCAmelCase = FlaxAutoModel.from_pretrained("""hf-internal-testing/tiny-bert-pt-only""" )
555
"""simple docstring""" import importlib import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Union import torch from ..utils import BaseOutput a : int = '''scheduler_config.json''' class a_ ( _UpperCAmelCase ): a : List[Any] = 1 a : Tuple = 2 a : Dict = 3 a : str = 4 a : Optional[int] = 5 a : Any = 6 a : int = 7 a : Any = 8 a : List[Any] = 9 a : Any = 10 a : List[str] = 11 a : Optional[int] = 12 a : Any = 13 a : Dict = 14 @dataclass class a_ ( _UpperCAmelCase ): a : torch.FloatTensor class a_ : a : Dict = SCHEDULER_CONFIG_NAME a : List[str] = [] a : Optional[int] = True @classmethod def _snake_case ( cls : List[str] , __UpperCamelCase : Dict[str, Any] = None , __UpperCamelCase : Optional[str] = None , __UpperCamelCase : List[str]=False , **__UpperCamelCase : int , ) ->Dict: '''simple docstring''' _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase = cls.load_config( pretrained_model_name_or_path=__UpperCamelCase , subfolder=__UpperCamelCase , return_unused_kwargs=__UpperCamelCase , return_commit_hash=__UpperCamelCase , **__UpperCamelCase , ) return cls.from_config(__UpperCamelCase , return_unused_kwargs=__UpperCamelCase , **__UpperCamelCase ) def _snake_case ( self : Tuple , __UpperCamelCase : Union[str, os.PathLike] , __UpperCamelCase : bool = False , **__UpperCamelCase : List[str] ) ->Any: '''simple docstring''' self.save_config(save_directory=__UpperCamelCase , push_to_hub=__UpperCamelCase , **__UpperCamelCase ) @property def _snake_case ( self : Optional[int] ) ->List[Any]: '''simple docstring''' return self._get_compatibles() @classmethod def _snake_case ( cls : List[str] ) ->Dict: '''simple docstring''' _UpperCAmelCase = list(set([cls.__name__] + cls._compatibles ) ) _UpperCAmelCase = importlib.import_module(__name__.split(""".""" )[0] ) _UpperCAmelCase = [ getattr(__UpperCamelCase , __UpperCamelCase ) for c in compatible_classes_str if hasattr(__UpperCamelCase , __UpperCamelCase ) ] return compatible_classes
555
1
'''simple docstring''' def lowerCamelCase ( UpperCAmelCase__ : int = 5_0 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ :List[Any] = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(f"{solution() = }")
320
'''simple docstring''' UpperCamelCase_ = {'''a''': ['''c''', '''b'''], '''b''': ['''d''', '''e'''], '''c''': [], '''d''': [], '''e''': []} UpperCamelCase_ = ['''a''', '''b''', '''c''', '''d''', '''e'''] def lowerCamelCase ( UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ :Any = start # add current to visited visited.append(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ :int = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: SCREAMING_SNAKE_CASE__ :Dict = topological_sort(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # if all neighbors visited add current to sort sort.append(UpperCAmelCase__ ) # if all vertices haven't been visited select a new one to visit if len(UpperCAmelCase__ ) != len(UpperCAmelCase__ ): for vertice in vertices: if vertice not in visited: SCREAMING_SNAKE_CASE__ :Optional[int] = topological_sort(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # return sort return sort if __name__ == "__main__": UpperCamelCase_ = topological_sort('''a''', [], []) print(sort)
320
1