code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import datasets import numpy as np import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, EvalPrediction, HfArgumentParser, PreTrainedTokenizer, TFAutoModelForSequenceClassification, TFTrainer, TFTrainingArguments, ) from transformers.utils import logging as hf_logging hf_logging.set_verbosity_info() hf_logging.enable_default_handler() hf_logging.enable_explicit_format() def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ = None , ): '''simple docstring''' A : Optional[int] = {} if train_file is not None: A : int = [train_file] if eval_file is not None: A : List[str] = [eval_file] if test_file is not None: A : Optional[Any] = [test_file] A : Union[str, Any] = datasets.load_dataset('''csv''' , data_files=snake_case__ ) A : int = list(ds[list(files.keys() )[0]].features.keys() ) A : Optional[int] = features_name.pop(snake_case__ ) A : List[Any] = list(set(ds[list(files.keys() )[0]][label_name] ) ) A : Dict = {label: i for i, label in enumerate(snake_case__ )} A : List[str] = tokenizer.model_input_names A : List[Any] = {} if len(snake_case__ ) == 1: for k in files.keys(): A : Any = ds[k].map( lambda snake_case__ : tokenizer.batch_encode_plus( example[features_name[0]] , truncation=snake_case__ , max_length=snake_case__ , padding='''max_length''' ) , batched=snake_case__ , ) elif len(snake_case__ ) == 2: for k in files.keys(): A : Tuple = ds[k].map( lambda snake_case__ : tokenizer.batch_encode_plus( (example[features_name[0]], example[features_name[1]]) , truncation=snake_case__ , max_length=snake_case__ , padding='''max_length''' , ) , batched=snake_case__ , ) def gen_train(): for ex in transformed_ds[datasets.Split.TRAIN]: A : Union[str, Any] = {k: v for k, v in ex.items() if k in input_names} A : Dict = labelaid[ex[label_name]] yield (d, label) def gen_val(): for ex in transformed_ds[datasets.Split.VALIDATION]: A : List[str] = {k: v for k, v in ex.items() if k in input_names} A : Optional[Any] = labelaid[ex[label_name]] yield (d, label) def gen_test(): for ex in transformed_ds[datasets.Split.TEST]: A : Union[str, Any] = {k: v for k, v in ex.items() if k in input_names} A : Tuple = labelaid[ex[label_name]] yield (d, label) A : int = ( tf.data.Dataset.from_generator( snake_case__ , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TRAIN in transformed_ds else None ) if train_ds is not None: A : int = train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN] ) ) ) A : Union[str, Any] = ( tf.data.Dataset.from_generator( snake_case__ , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.VALIDATION in transformed_ds else None ) if val_ds is not None: A : str = val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION] ) ) ) A : Union[str, Any] = ( tf.data.Dataset.from_generator( snake_case__ , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TEST in transformed_ds else None ) if test_ds is not None: A : Optional[Any] = test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST] ) ) ) return train_ds, val_ds, test_ds, labelaid lowercase : List[str] = logging.getLogger(__name__) @dataclass class A : __magic_name__ = field(metadata={'''help''': '''Which column contains the label'''} ) __magic_name__ = field(default=__snake_case , metadata={'''help''': '''The path of the training file'''} ) __magic_name__ = field(default=__snake_case , metadata={'''help''': '''The path of the development file'''} ) __magic_name__ = field(default=__snake_case , metadata={'''help''': '''The path of the test file'''} ) __magic_name__ = field( default=128 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) __magic_name__ = field( default=__snake_case , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) @dataclass class A : __magic_name__ = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) __magic_name__ = field( default=__snake_case , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) __magic_name__ = field( default=__snake_case , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) __magic_name__ = field(default=__snake_case , metadata={'''help''': '''Set this flag to use fast tokenization.'''} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. __magic_name__ = field( default=__snake_case , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) def lowerCAmelCase_ ( ): '''simple docstring''' A : Tuple = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments) ) A, A, A : Any = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO , ) logger.info( F'n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1 )}, ' F'16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. A : Optional[Any] = 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 , ) A, A, A, A : List[Any] = get_tfds( train_file=data_args.train_file , eval_file=data_args.dev_file , test_file=data_args.test_file , tokenizer=snake_case__ , label_column_id=data_args.label_column_id , max_seq_length=data_args.max_seq_length , ) A : Union[str, Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=len(snake_case__ ) , labelaid=snake_case__ , idalabel={id: label for label, id in labelaid.items()} , finetuning_task='''text-classification''' , cache_dir=model_args.cache_dir , ) with training_args.strategy.scope(): A : Union[str, Any] = TFAutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_pt=bool('''.bin''' in model_args.model_name_or_path ) , config=snake_case__ , cache_dir=model_args.cache_dir , ) def compute_metrics(snake_case__ ) -> Dict: A : Optional[int] = np.argmax(p.predictions , axis=1 ) return {"acc": (preds == p.label_ids).mean()} # Initialize our Trainer A : Optional[int] = TFTrainer( model=snake_case__ , args=snake_case__ , train_dataset=snake_case__ , eval_dataset=snake_case__ , compute_metrics=snake_case__ , ) # Training if training_args.do_train: trainer.train() trainer.save_model() tokenizer.save_pretrained(training_args.output_dir ) # Evaluation A : Any = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) A : int = trainer.evaluate() A : str = os.path.join(training_args.output_dir , '''eval_results.txt''' ) with open(snake_case__ , '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(F' {key} = {value}' ) writer.write(F'{key} = {value}\n' ) results.update(snake_case__ ) return results if __name__ == "__main__": main()
311
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : Optional[int] = logging.get_logger(__name__) lowercase : Tuple = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class A ( __snake_case ): __magic_name__ = '''pix2struct_text_model''' __magic_name__ = ['''past_key_values'''] __magic_name__ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , SCREAMING_SNAKE_CASE=50244 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Optional[Any]: """simple docstring""" A : str = vocab_size A : List[str] = hidden_size A : List[Any] = d_kv A : Optional[Any] = d_ff A : Dict = num_layers A : Dict = num_heads A : Optional[int] = relative_attention_num_buckets A : Optional[Any] = relative_attention_max_distance A : Dict = dropout_rate A : Dict = layer_norm_epsilon A : Tuple = initializer_factor A : Union[str, Any] = use_cache A : int = eos_token_id A : List[str] = decoder_start_token_id # for backwards compatibility A : int = dense_act_fn super().__init__( pad_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , decoder_start_token_id=SCREAMING_SNAKE_CASE , tie_word_embeddings=SCREAMING_SNAKE_CASE , is_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) A, A : Optional[Any] = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": A : Union[str, Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A ( __snake_case ): __magic_name__ = '''pix2struct_vision_model''' def __init__( self , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=1e-10 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=4096 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=128 , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) A : List[str] = hidden_size A : Optional[Any] = patch_embed_hidden_size A : Union[str, Any] = d_ff A : Dict = dropout_rate A : str = num_hidden_layers A : Dict = num_attention_heads A : Tuple = initializer_range A : List[str] = initializer_factor A : Union[str, Any] = attention_dropout A : Tuple = layer_norm_eps A : int = dense_act_fn A : Optional[int] = seq_len A : Tuple = relative_attention_num_buckets A : str = relative_attention_max_distance A : Optional[Any] = d_kv @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) A, A : int = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": A : Optional[Any] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A ( __snake_case ): __magic_name__ = '''pix2struct''' __magic_name__ = True def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(tie_word_embeddings=SCREAMING_SNAKE_CASE , is_encoder_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) if text_config is None: A : Dict = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: A : str = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) A : Dict = PixaStructTextConfig(**SCREAMING_SNAKE_CASE ) A : Any = PixaStructVisionConfig(**SCREAMING_SNAKE_CASE ) A : Any = self.text_config.decoder_start_token_id A : Any = self.text_config.pad_token_id A : Dict = self.text_config.eos_token_id A : Union[str, Any] = initializer_factor A : Tuple = initializer_range A : Optional[Any] = self.initializer_range A : int = self.initializer_range A : Tuple = is_vqa @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Tuple = copy.deepcopy(self.__dict__ ) A : Dict = self.text_config.to_dict() A : int = self.vision_config.to_dict() A : Any = self.__class__.model_type return output
311
1
'''simple docstring''' import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if ( (cp >= 0X4E00 and cp <= 0X9FFF) or (cp >= 0X3400 and cp <= 0X4DBF) # or (cp >= 0X20000 and cp <= 0X2A6DF) # or (cp >= 0X2A700 and cp <= 0X2B73F) # or (cp >= 0X2B740 and cp <= 0X2B81F) # or (cp >= 0X2B820 and cp <= 0X2CEAF) # or (cp >= 0XF900 and cp <= 0XFAFF) or (cp >= 0X2F800 and cp <= 0X2FA1F) # ): # return True return False def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for char in word: A : List[str] = ord(snake_case__ ) if not _is_chinese_char(snake_case__ ): return 0 return 1 def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Union[str, Any] = set() for token in tokens: A : str = len(snake_case__ ) > 1 and is_chinese(snake_case__ ) if chinese_word: word_set.add(snake_case__ ) A : Optional[Any] = list(snake_case__ ) return word_list def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if not chinese_word_set: return bert_tokens A : int = max([len(snake_case__ ) for w in chinese_word_set] ) A : Any = bert_tokens A, A : int = 0, len(snake_case__ ) while start < end: A : Optional[int] = True if is_chinese(bert_word[start] ): A : Union[str, Any] = min(end - start , snake_case__ ) for i in range(snake_case__ , 1 , -1 ): A : List[str] = ''''''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): A : str = '''##''' + bert_word[j] A : Dict = start + i A : Optional[int] = False break if single_word: start += 1 return bert_word def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : List[Any] = [] for i in range(0 , len(snake_case__ ) , 100 ): A : Union[str, Any] = ltp_tokenizer.pipeline(lines[i : i + 100] , tasks=['''cws'''] ).cws A : str = [get_chinese_word(snake_case__ ) for r in res] ltp_res.extend(snake_case__ ) assert len(snake_case__ ) == len(snake_case__ ) A : Optional[Any] = [] for i in range(0 , len(snake_case__ ) , 100 ): A : Union[str, Any] = bert_tokenizer(lines[i : i + 100] , add_special_tokens=snake_case__ , truncation=snake_case__ , max_length=512 ) bert_res.extend(res['''input_ids'''] ) assert len(snake_case__ ) == len(snake_case__ ) A : List[str] = [] for input_ids, chinese_word in zip(snake_case__ , snake_case__ ): A : int = [] for id in input_ids: A : Dict = bert_tokenizer._convert_id_to_token(snake_case__ ) input_tokens.append(snake_case__ ) A : Union[str, Any] = add_sub_symbol(snake_case__ , snake_case__ ) A : str = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(snake_case__ ): if token[:2] == "##": A : Tuple = token[2:] # save chinese tokens' pos if len(snake_case__ ) == 1 and _is_chinese_char(ord(snake_case__ ) ): ref_id.append(snake_case__ ) ref_ids.append(snake_case__ ) assert len(snake_case__ ) == len(snake_case__ ) return ref_ids def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' with open(args.file_name , '''r''' , encoding='''utf-8''' ) as f: A : Optional[int] = f.readlines() A : Dict = [line.strip() for line in data if len(snake_case__ ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' A : int = LTP(args.ltp ) # faster in GPU device A : Any = BertTokenizer.from_pretrained(args.bert ) A : int = prepare_ref(snake_case__ , snake_case__ , snake_case__ ) with open(args.save_path , '''w''' , encoding='''utf-8''' ) as f: A : Tuple = [json.dumps(snake_case__ ) + '''\n''' for ref in ref_ids] f.writelines(snake_case__ ) if __name__ == "__main__": lowercase : Tuple = argparse.ArgumentParser(description='prepare_chinese_ref') parser.add_argument( '--file_name', required=False, type=str, default='./resources/chinese-demo.txt', help='file need process, same as training data in lm', ) parser.add_argument( '--ltp', required=False, type=str, default='./resources/ltp', help='resources for LTP tokenizer, usually a path', ) parser.add_argument( '--bert', required=False, type=str, default='./resources/robert', help='resources for Bert tokenizer', ) parser.add_argument( '--save_path', required=False, type=str, default='./resources/ref.txt', help='path to save res', ) lowercase : Optional[Any] = parser.parse_args() main(args)
311
'''simple docstring''' from __future__ import annotations def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : List[str] = 2 A : Dict = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(snake_case__ ) if n > 1: factors.append(snake_case__ ) return factors if __name__ == "__main__": import doctest doctest.testmod()
311
1
'''simple docstring''' # limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 50 , SCREAMING_SNAKE_CASE = "pil" , SCREAMING_SNAKE_CASE = True , **SCREAMING_SNAKE_CASE , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" A : List[Any] = torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=SCREAMING_SNAKE_CASE , ) A : Optional[Any] = image.to(self.device ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output A : Tuple = self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 A : List[Any] = self.scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample A : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) A : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": A : List[Any] = self.numpy_to_pil(SCREAMING_SNAKE_CASE ) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE ), "This is a local test"
311
'''simple docstring''' # Function to print upper half of diamond (pyramid) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for i in range(0 , snake_case__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(''' ''' , end='''''' ) for _ in range(0 , i + 1 ): # printing stars print('''* ''' , end='''''' ) print() def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for i in range(snake_case__ , 0 , -1 ): for _ in range(snake_case__ , 0 , -1 ): # printing stars print('''* ''' , end='''''' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(''' ''' , end='''''' ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if n <= 0: print(''' ... .... nothing printing :(''' ) return floyd(snake_case__ ) # upper half reverse_floyd(snake_case__ ) # lower half if __name__ == "__main__": print(R'| /\ | |- | |- |--| |\ /| |-') print(R'|/ \| |- |_ |_ |__| | \/ | |_') lowercase : List[str] = 1 while K: lowercase : List[Any] = int(input('enter the number and , and see the magic : ')) print() pretty_print(user_number) lowercase : Any = int(input('press 0 to exit... and 1 to continue...')) print('Good Bye...')
311
1
'''simple docstring''' import argparse from collections import defaultdict import yaml lowercase : List[Any] = 'docs/source/en/_toctree.yml' def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Tuple = defaultdict(snake_case__ ) for doc in model_doc: counts[doc["local"]] += 1 A : List[str] = [key for key, value in counts.items() if value > 1] A : Dict = [] for duplicate_key in duplicates: A : Union[str, Any] = list({doc['''title'''] for doc in model_doc if doc['''local'''] == duplicate_key} ) if len(snake_case__ ) > 1: raise ValueError( F'{duplicate_key} is present several times in the documentation table of content at ' '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ''' '''others.''' ) # Only add this once new_doc.append({'''local''': duplicate_key, '''title''': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc['''local''']] == 1] ) # Sort return sorted(snake_case__ , key=lambda snake_case__ : s["title"].lower() ) def lowerCAmelCase_ ( snake_case__=False ): '''simple docstring''' with open(snake_case__ , encoding='''utf-8''' ) as f: A : int = yaml.safe_load(f.read() ) # Get to the API doc A : Optional[Any] = 0 while content[api_idx]["title"] != "API": api_idx += 1 A : Optional[Any] = content[api_idx]['''sections'''] # Then to the model doc A : Any = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 A : Optional[int] = api_doc[model_idx]['''sections'''] A : Optional[Any] = [(idx, section) for idx, section in enumerate(snake_case__ ) if '''sections''' in section] A : Optional[Any] = False for idx, modality_doc in modalities_docs: A : Tuple = modality_doc['''sections'''] A : Tuple = clean_model_doc_toc(snake_case__ ) if old_modality_doc != new_modality_doc: A : Union[str, Any] = True if overwrite: A : List[Any] = new_modality_doc if diff: if overwrite: A : int = model_doc A : Dict = api_doc with open(snake_case__ , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(snake_case__ , allow_unicode=snake_case__ ) ) else: raise ValueError( '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.''' ) if __name__ == "__main__": lowercase : Dict = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') lowercase : List[str] = parser.parse_args() check_model_doc(args.fix_and_overwrite)
311
'''simple docstring''' # limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 50 , SCREAMING_SNAKE_CASE = "pil" , SCREAMING_SNAKE_CASE = True , **SCREAMING_SNAKE_CASE , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" A : List[Any] = torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=SCREAMING_SNAKE_CASE , ) A : Optional[Any] = image.to(self.device ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output A : Tuple = self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 A : List[Any] = self.scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample A : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) A : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": A : List[Any] = self.numpy_to_pil(SCREAMING_SNAKE_CASE ) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE ), "This is a local test"
311
1
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class A ( __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = IFInpaintingSuperResolutionPipeline __magic_name__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''width''', '''height'''} __magic_name__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({'''original_image'''} ) __magic_name__ = PipelineTesterMixin.required_optional_params - {'''latents'''} def __lowerCAmelCase ( self ) -> int: """simple docstring""" return self._get_superresolution_dummy_components() def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0 ) -> List[Any]: """simple docstring""" if str(SCREAMING_SNAKE_CASE ).startswith('''mps''' ): A : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE ) else: A : Optional[int] = torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(SCREAMING_SNAKE_CASE ) A : List[Any] = floats_tensor((1, 3, 16, 16) , rng=random.Random(SCREAMING_SNAKE_CASE ) ).to(SCREAMING_SNAKE_CASE ) A : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE ) ).to(SCREAMING_SNAKE_CASE ) A : Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE ) ).to(SCREAMING_SNAKE_CASE ) A : Tuple = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''original_image''': original_image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" self._test_save_load_local() def __lowerCAmelCase ( self ) -> int: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
311
'''simple docstring''' import unittest from transformers import BertGenerationConfig, 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 BertGenerationDecoder, BertGenerationEncoder class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=50 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=None , ) -> str: """simple docstring""" A : Any = parent A : List[Any] = batch_size A : Union[str, Any] = seq_length A : Any = is_training A : int = use_input_mask A : Union[str, Any] = vocab_size A : List[Any] = hidden_size A : List[Any] = num_hidden_layers A : Optional[int] = num_attention_heads A : str = intermediate_size A : Tuple = hidden_act A : Union[str, Any] = hidden_dropout_prob A : Union[str, Any] = attention_probs_dropout_prob A : int = max_position_embeddings A : Optional[int] = initializer_range A : Any = use_labels A : Optional[int] = scope def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Optional[int] = None if self.use_input_mask: A : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: A : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Dict = self.get_config() return config, input_ids, input_mask, token_labels def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" return BertGenerationConfig( 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 , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" ( ( A ), ( A ), ( A ), ( A ), ) : Any = self.prepare_config_and_inputs() A : Tuple = True A : int = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A : str = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" A : List[str] = BertGenerationEncoder(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) A : int = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> Union[str, Any]: """simple docstring""" A : List[str] = True A : Union[str, Any] = BertGenerationEncoder(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , ) A : List[Any] = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" A : Optional[Any] = True A : Tuple = True A : Optional[int] = BertGenerationDecoder(config=SCREAMING_SNAKE_CASE ).to(SCREAMING_SNAKE_CASE ).eval() # first forward pass A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , use_cache=SCREAMING_SNAKE_CASE , ) A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A : List[str] = ids_tensor((self.batch_size, 3) , config.vocab_size ) A : Tuple = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and A : Dict = torch.cat([input_ids, next_tokens] , dim=-1 ) A : List[str] = torch.cat([input_mask, next_mask] , dim=-1 ) A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE , )['''hidden_states'''][0] A : Any = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , past_key_values=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE , )['''hidden_states'''][0] # select random slice A : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() A : List[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() A : str = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" A : Optional[Any] = BertGenerationDecoder(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Optional[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A, A, A, A : Optional[int] = self.prepare_config_and_inputs() A : str = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class A ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () __magic_name__ = (BertGenerationDecoder,) if is_torch_available() else () __magic_name__ = ( {'''feature-extraction''': BertGenerationEncoder, '''text-generation''': BertGenerationDecoder} if is_torch_available() else {} ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : List[str] = BertGenerationEncoderTester(self ) A : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A, A, A, A : Tuple = self.model_tester.prepare_config_and_inputs() A : str = '''bert''' self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : int = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" ( ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ) : Tuple = self.model_tester.prepare_config_and_inputs_for_decoder() A : Union[str, Any] = None self.model_tester.create_and_check_model_as_decoder( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*SCREAMING_SNAKE_CASE ) @slow def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Optional[Any] = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) A : Optional[Any] = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]] ) with torch.no_grad(): A : Dict = model(SCREAMING_SNAKE_CASE )[0] A : Optional[Any] = torch.Size([1, 8, 1024] ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : Dict = torch.tensor( [[[0.1_775, 0.0_083, -0.0_321], [1.6_002, 0.1_287, 0.3_912], [2.1_473, 0.5_791, 0.6_066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[Any] = BertGenerationDecoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) A : Dict = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]] ) with torch.no_grad(): A : Optional[Any] = model(SCREAMING_SNAKE_CASE )[0] A : Optional[Any] = torch.Size([1, 8, 50358] ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : Any = torch.tensor( [[[-0.5_788, -2.5_994, -3.7_054], [0.0_438, 4.7_997, 1.8_795], [1.5_862, 6.6_409, 4.4_638]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
1
'''simple docstring''' lowercase : Any = tuple[float, float, float] lowercase : Any = tuple[float, float, float] def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : Optional[int] = end_pointa[0] - end_pointa[0] A : Tuple = end_pointa[1] - end_pointa[1] A : int = end_pointa[2] - end_pointa[2] return (x, y, z) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : Any = ab[1] * ac[2] - ab[2] * ac[1] # *i A : List[Any] = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j A : Any = ab[0] * ac[1] - ab[1] * ac[0] # *k return (x, y, z) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' return tuple(round(snake_case__ , snake_case__ ) for x in vector ) == (0, 0, 0) def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ = 10 ): '''simple docstring''' A : Optional[int] = create_vector(snake_case__ , snake_case__ ) A : Optional[int] = create_vector(snake_case__ , snake_case__ ) return is_zero_vector(get_ad_vectors_cross(snake_case__ , snake_case__ ) , snake_case__ )
311
'''simple docstring''' import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' return 1.0 / (1.0 + np.exp(-_outputs )) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Optional[int] = np.max(_outputs , axis=-1 , keepdims=snake_case__ ) A : Any = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=snake_case__ ) class A ( __snake_case ): __magic_name__ = '''sigmoid''' __magic_name__ = '''softmax''' __magic_name__ = '''none''' @add_end_docstrings( __snake_case , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class A ( __snake_case ): __magic_name__ = False __magic_name__ = ClassificationFunction.NONE def __init__( self , **SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE="" , **SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" A : Optional[Any] = tokenizer_kwargs A : int = {} if hasattr(self.model.config , '''return_all_scores''' ) and return_all_scores is None: A : int = self.model.config.return_all_scores if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) or top_k is None: A : Union[str, Any] = top_k A : Dict = False elif return_all_scores is not None: warnings.warn( '''`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of''' ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.''' , SCREAMING_SNAKE_CASE , ) if return_all_scores: A : Optional[int] = None else: A : Dict = 1 if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : Dict = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: A : int = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : str = super().__call__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. A : Any = '''top_k''' not in kwargs if isinstance(args[0] , SCREAMING_SNAKE_CASE ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Dict[str, GenericTensor]: """simple docstring""" A : List[Any] = self.framework if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): return self.tokenizer(**SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and len(SCREAMING_SNAKE_CASE ) == 1 and isinstance(inputs[0] , SCREAMING_SNAKE_CASE ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a''' ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.''' ) return self.tokenizer(SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" return self.model(**SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=True ) -> List[str]: """simple docstring""" if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: A : Optional[int] = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: A : Any = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , '''function_to_apply''' ) and function_to_apply is None: A : Optional[int] = self.model.config.function_to_apply else: A : Optional[int] = ClassificationFunction.NONE A : Any = model_outputs['''logits'''][0] A : List[Any] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: A : int = sigmoid(SCREAMING_SNAKE_CASE ) elif function_to_apply == ClassificationFunction.SOFTMAX: A : Any = softmax(SCREAMING_SNAKE_CASE ) elif function_to_apply == ClassificationFunction.NONE: A : int = outputs else: raise ValueError(F'Unrecognized `function_to_apply` argument: {function_to_apply}' ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} A : int = [ {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(SCREAMING_SNAKE_CASE ) ] if not _legacy: dict_scores.sort(key=lambda SCREAMING_SNAKE_CASE : x["score"] , reverse=SCREAMING_SNAKE_CASE ) if top_k is not None: A : Union[str, Any] = dict_scores[:top_k] return dict_scores
311
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 torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class A ( __snake_case ): __magic_name__ = '''facebook/bart-large-mnli''' __magic_name__ = ( '''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.''' ) __magic_name__ = '''text_classifier''' __magic_name__ = AutoTokenizer __magic_name__ = AutoModelForSequenceClassification __magic_name__ = ['''text''', ['''text''']] __magic_name__ = ['''text'''] def __lowerCAmelCase ( self ) -> int: """simple docstring""" super().setup() A : Optional[int] = self.model.config A : str = -1 for idx, label in config.idalabel.items(): if label.lower().startswith('''entail''' ): A : Tuple = int(SCREAMING_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 __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" A : List[str] = labels return self.pre_processor( [text] * len(SCREAMING_SNAKE_CASE ) , [F'This example is {label}' for label in labels] , return_tensors='''pt''' , padding='''max_length''' , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" A : str = outputs.logits A : str = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
311
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCAmelCase_ ( snake_case__ = "laptop" ): '''simple docstring''' A : Tuple = F'https://www.amazon.in/laptop/s?k={product}' A : Optional[int] = { '''User-Agent''': '''Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36''', '''Accept-Language''': '''en-US, en;q=0.5''', } A : Any = BeautifulSoup(requests.get(snake_case__ , headers=snake_case__ ).text ) # Initialize a Pandas dataframe with the column titles A : List[str] = DataFrame( columns=[ '''Product Title''', '''Product Link''', '''Current Price of the product''', '''Product Rating''', '''MRP of the product''', '''Discount''', ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( '''div''' , attrs={'''class''': '''s-result-item''', '''data-component-type''': '''s-search-result'''} , ) , soup.find_all('''div''' , attrs={'''class''': '''a-row a-size-base a-color-base'''} ) , ): try: A : Optional[Any] = item.ha.text A : Union[str, Any] = '''https://www.amazon.in/''' + item.ha.a['''href'''] A : Tuple = item.find('''span''' , attrs={'''class''': '''a-offscreen'''} ).text try: A : int = item.find('''span''' , attrs={'''class''': '''a-icon-alt'''} ).text except AttributeError: A : Optional[int] = '''Not available''' try: A : str = ( '''₹''' + item.find( '''span''' , attrs={'''class''': '''a-price a-text-price'''} ).text.split('''₹''' )[1] ) except AttributeError: A : List[Any] = '''''' try: A : Dict = float( ( ( float(product_mrp.strip('''₹''' ).replace(''',''' , '''''' ) ) - float(product_price.strip('''₹''' ).replace(''',''' , '''''' ) ) ) / float(product_mrp.strip('''₹''' ).replace(''',''' , '''''' ) ) ) * 100 ) except ValueError: A : str = float('''nan''' ) except AttributeError: pass A : Union[str, Any] = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] A : List[str] = ''' ''' A : Optional[Any] = ''' ''' data_frame.index += 1 return data_frame if __name__ == "__main__": lowercase : Union[str, Any] = 'headphones' get_amazon_product_data(product).to_csv(f'''Amazon Product Data for {product}.csv''')
311
1
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : int = logging.get_logger(__name__) lowercase : int = { 'asapp/sew-tiny-100k': 'https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json', # See all SEW models at https://huggingface.co/models?filter=sew } class A ( __snake_case ): __magic_name__ = '''sew''' def __init__( self , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-5 , SCREAMING_SNAKE_CASE="group" , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , SCREAMING_SNAKE_CASE=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=0.05 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE="mean" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=256 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=2 , **SCREAMING_SNAKE_CASE , ) -> Tuple: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE , pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE ) A : Optional[Any] = hidden_size A : Any = feat_extract_norm A : Optional[int] = feat_extract_activation A : Tuple = list(SCREAMING_SNAKE_CASE ) A : List[str] = list(SCREAMING_SNAKE_CASE ) A : List[str] = list(SCREAMING_SNAKE_CASE ) A : int = conv_bias A : List[Any] = num_conv_pos_embeddings A : Tuple = num_conv_pos_embedding_groups A : int = len(self.conv_dim ) A : Dict = num_hidden_layers A : Optional[int] = intermediate_size A : Any = squeeze_factor A : int = hidden_act A : str = num_attention_heads A : Dict = hidden_dropout A : Optional[Any] = attention_dropout A : List[str] = activation_dropout A : Union[str, Any] = feat_proj_dropout A : Union[str, Any] = final_dropout A : int = layerdrop A : Optional[Any] = layer_norm_eps A : Any = initializer_range A : Tuple = vocab_size 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)`,''' F'but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)' F'= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 A : Optional[Any] = apply_spec_augment A : Optional[Any] = mask_time_prob A : Union[str, Any] = mask_time_length A : Optional[Any] = mask_time_min_masks A : str = mask_feature_prob A : Tuple = mask_feature_length A : Any = mask_feature_min_masks # ctc loss A : List[Any] = ctc_loss_reduction A : Dict = ctc_zero_infinity # sequence classification A : int = use_weighted_layer_sum A : Optional[int] = classifier_proj_size @property def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
311
'''simple docstring''' import colorsys from PIL import Image # type: ignore def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : Optional[int] = x A : str = y for step in range(snake_case__ ): # noqa: B007 A : str = a * a - b * b + x A : List[str] = 2 * a * b + y A : str = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255 ) for i in colorsys.hsv_to_rgb(snake_case__ , 1 , 1 ) ) def lowerCAmelCase_ ( snake_case__ = 800 , snake_case__ = 600 , snake_case__ = -0.6 , snake_case__ = 0 , snake_case__ = 3.2 , snake_case__ = 50 , snake_case__ = True , ): '''simple docstring''' A : List[Any] = Image.new('''RGB''' , (image_width, image_height) ) A : Tuple = img.load() # loop through the image-coordinates for image_x in range(snake_case__ ): for image_y in range(snake_case__ ): # determine the figure-coordinates based on the image-coordinates A : Optional[int] = figure_width / image_width * image_height A : Tuple = figure_center_x + (image_x / image_width - 0.5) * figure_width A : List[str] = figure_center_y + (image_y / image_height - 0.5) * figure_height A : str = get_distance(snake_case__ , snake_case__ , snake_case__ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: A : str = get_color_coded_rgb(snake_case__ ) else: A : List[Any] = get_black_and_white_rgb(snake_case__ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure lowercase : Optional[Any] = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
311
1
'''simple docstring''' import argparse import copy def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : List[Any] = {} with open(snake_case__ ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: A : List[str] = [] _list.append([line.split()[1], line.split()[2]] ) A : Any = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: A : Optional[int] = [] _list.append([line.split()[0], line.split()[2]] ) A : int = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' with open(snake_case__ ) as f: A : Tuple = f.read(1 ) A : Any = start_node A : List[Any] = [] A : List[str] = start_node A : Union[str, Any] = 0 while visiting not in first_solution: A : Optional[Any] = 1_0000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(snake_case__ ) and k[0] not in first_solution: A : List[str] = k[1] A : int = k[0] first_solution.append(snake_case__ ) A : List[str] = distance_of_first_solution + int(snake_case__ ) A : Any = best_node first_solution.append(snake_case__ ) A : Optional[int] = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 A : Tuple = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 1_0000 ) return first_solution, distance_of_first_solution def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : Optional[Any] = [] for n in solution[1:-1]: A : Union[str, Any] = solution.index(snake_case__ ) for kn in solution[1:-1]: A : str = solution.index(snake_case__ ) if n == kn: continue A : Tuple = copy.deepcopy(snake_case__ ) A : str = kn A : Union[str, Any] = n A : Optional[int] = 0 for k in _tmp[:-1]: A : List[str] = _tmp[_tmp.index(snake_case__ ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: A : List[str] = distance + int(i[1] ) _tmp.append(snake_case__ ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) A : Dict = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda snake_case__ : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : str = 1 A : str = first_solution A : Any = [] A : Optional[Any] = distance_of_first_solution A : Optional[int] = solution while count <= iters: A : List[Any] = find_neighborhood(snake_case__ , snake_case__ ) A : Any = 0 A : str = neighborhood[index_of_best_solution] A : List[Any] = len(snake_case__ ) - 1 A : List[Any] = False while not found: A : Dict = 0 while i < len(snake_case__ ): if best_solution[i] != solution[i]: A : List[str] = best_solution[i] A : Optional[Any] = solution[i] break A : str = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) A : List[str] = True A : Optional[int] = best_solution[:-1] A : Optional[int] = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: A : Optional[Any] = cost A : int = solution else: A : str = index_of_best_solution + 1 A : Optional[Any] = neighborhood[index_of_best_solution] if len(snake_case__ ) >= size: tabu_list.pop(0 ) A : List[Any] = count + 1 return best_solution_ever, best_cost def lowerCAmelCase_ ( snake_case__=None ): '''simple docstring''' A : Union[str, Any] = generate_neighbours(args.File ) A, A : List[Any] = generate_first_solution( args.File , snake_case__ ) A, A : List[str] = tabu_search( snake_case__ , snake_case__ , snake_case__ , args.Iterations , args.Size , ) print(F'Best solution: {best_sol}, with total distance: {best_cost}.' ) if __name__ == "__main__": lowercase : Tuple = argparse.ArgumentParser(description='Tabu Search') parser.add_argument( '-f', '--File', type=str, help='Path to the file containing the data', required=True, ) parser.add_argument( '-i', '--Iterations', type=int, help='How many iterations the algorithm should perform', required=True, ) parser.add_argument( '-s', '--Size', type=int, help='Size of the tabu list', required=True ) # Pass the arguments to main method main(parser.parse_args())
311
'''simple docstring''' import argparse import importlib from pathlib import Path # Test all the extensions added in the setup lowercase : Optional[int] = [ 'kernels/rwkv/wkv_cuda.cu', 'kernels/rwkv/wkv_op.cpp', 'kernels/deformable_detr/ms_deform_attn.h', 'kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh', 'models/graphormer/algos_graphormer.pyx', ] def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for file in FILES_TO_FIND: if not (transformers_path / file).exists(): return False return True if __name__ == "__main__": lowercase : str = argparse.ArgumentParser() parser.add_argument('--check_lib', action='store_true', help='Whether to check the build or the actual package.') lowercase : Optional[Any] = parser.parse_args() if args.check_lib: lowercase : List[Any] = importlib.import_module('transformers') lowercase : str = Path(transformers_module.__file__).parent else: lowercase : List[Any] = Path.cwd() / 'build/lib/transformers' if not test_custom_files_are_present(transformers_path): raise ValueError('The built release does not contain the custom files. Fix this before going further!')
311
1
'''simple docstring''' from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import DistributedType, is_torch_version, set_seed def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' for param, grad_param in zip(model_a.parameters() , model_b.parameters() ): if not param.requires_grad: continue if not did_step: # Grads should not be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is False ), F'Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})' else: # Grads should be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is True ), F'Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})' def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__=True ): '''simple docstring''' model.train() A : Union[str, Any] = model(snake_case__ ) A : List[str] = F.mse_loss(snake_case__ , target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(snake_case__ ) def lowerCAmelCase_ ( snake_case__ , snake_case__=False ): '''simple docstring''' set_seed(42 ) A : Optional[Any] = RegressionModel() A : Union[str, Any] = deepcopy(snake_case__ ) A : Optional[Any] = RegressionDataset(length=80 ) A : Any = DataLoader(snake_case__ , batch_size=16 ) model.to(accelerator.device ) if sched: A : int = AdamW(params=model.parameters() , lr=1E-3 ) A : Union[str, Any] = AdamW(params=ddp_model.parameters() , lr=1E-3 ) A : Optional[Any] = LambdaLR(snake_case__ , lr_lambda=lambda snake_case__ : epoch**0.65 ) A : Tuple = LambdaLR(snake_case__ , lr_lambda=lambda snake_case__ : epoch**0.65 ) # Make a copy of `model` if sched: A, A, A, A : Tuple = accelerator.prepare(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) else: A, A : Optional[Any] = accelerator.prepare(snake_case__ , snake_case__ ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A, A, A : Dict = get_training_setup(snake_case__ ) # Use a single batch A, A : List[str] = next(iter(snake_case__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model A, A : Tuple = accelerator.gather((ddp_input, ddp_target) ) A, A : List[str] = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(snake_case__ ): step_model(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) else: # Sync grads step_model(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue assert torch.allclose( param.grad , ddp_param.grad ), F'Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})' # Shuffle ddp_input on each iteration torch.manual_seed(1337 + iteration ) A : List[Any] = ddp_input[torch.randperm(len(snake_case__ ) )] def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A, A, A : Optional[Any] = get_training_setup(snake_case__ ) # Use a single batch A, A : Tuple = next(iter(snake_case__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model A, A : Tuple = accelerator.gather((ddp_input, ddp_target) ) A, A : Dict = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(snake_case__ ): step_model(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) else: # Sync grads step_model(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if iteration % 2 == 0: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), F'Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})' else: # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), F'Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})' # Shuffle ddp_input on each iteration torch.manual_seed(1337 + iteration ) A : Union[str, Any] = ddp_input[torch.randperm(len(snake_case__ ) )] def lowerCAmelCase_ ( snake_case__=False , snake_case__=False ): '''simple docstring''' A : int = Accelerator( split_batches=snake_case__ , dispatch_batches=snake_case__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly A, A, A : Optional[int] = get_training_setup(snake_case__ ) for iteration, batch in enumerate(snake_case__ ): A, A : str = batch.values() # Gather the distributed inputs and targs for the base model A, A : Tuple = accelerator.gather((ddp_input, ddp_target) ) A, A : str = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # Do "gradient accumulation" (noop) with accelerator.accumulate(snake_case__ ): step_model(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if ((iteration + 1) % 2 == 0) or (iteration == len(snake_case__ ) - 1): # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), F'Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})' else: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), F'Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})' # Shuffle ddp_input on each iteration torch.manual_seed(1337 + iteration ) A : Any = ddp_input[torch.randperm(len(snake_case__ ) )] GradientState._reset_state() def lowerCAmelCase_ ( snake_case__=False , snake_case__=False ): '''simple docstring''' A : Any = Accelerator( split_batches=snake_case__ , dispatch_batches=snake_case__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly A, A, A, A, A, A, A : Tuple = get_training_setup(snake_case__ , snake_case__ ) for iteration, batch in enumerate(snake_case__ ): A, A : List[Any] = batch.values() # Gather the distributed inputs and targs for the base model A, A : Union[str, Any] = accelerator.gather((ddp_input, ddp_target) ) A, A : Any = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" model.train() ddp_model.train() step_model(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(snake_case__ )): if split_batches: sched.step() else: for _ in range(accelerator.num_processes ): sched.step() opt.zero_grad() # Perform gradient accumulation under wrapper with accelerator.accumulate(snake_case__ ): step_model(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) ddp_opt.step() ddp_sched.step() ddp_opt.zero_grad() # Learning rates should be the same assert ( opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] ), F'Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]["lr"]}\nDDP opt: {ddp_opt.param_groups[0]["lr"]}\n' A : Union[str, Any] = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(snake_case__ )) if accelerator.num_processes > 1: check_model_parameters(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # Shuffle ddp_input on each iteration torch.manual_seed(1337 + iteration ) GradientState._reset_state() def lowerCAmelCase_ ( ): '''simple docstring''' A : Any = Accelerator() A : Any = RegressionDataset(length=80 ) A : Union[str, Any] = DataLoader(snake_case__ , batch_size=16 ) A : Optional[int] = RegressionDataset(length=96 ) A : Optional[Any] = DataLoader(snake_case__ , batch_size=16 ) A, A : List[Any] = accelerator.prepare(snake_case__ , snake_case__ ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(snake_case__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(snake_case__ ) if iteration < len(snake_case__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(snake_case__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(snake_case__ ) if batch_num < len(snake_case__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader assert accelerator.gradient_state.active_dataloader is None def lowerCAmelCase_ ( ): '''simple docstring''' A : Tuple = Accelerator() A : int = accelerator.state if state.local_process_index == 0: print('''**Test `accumulate` gradient accumulation with dataloader break**''' ) test_dataloader_break() if state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print('''**Test NOOP `no_sync` context manager**''' ) test_noop_sync(snake_case__ ) if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU): if state.local_process_index == 0: print('''**Test Distributed `no_sync` context manager**''' ) test_distributed_sync(snake_case__ ) if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if state.local_process_index == 0: print( '''**Test `accumulate` gradient accumulation, ''' , F'`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**' , ) test_gradient_accumulation(snake_case__ , snake_case__ ) # Currently will break on torch 2.0 +, need to investigate why if is_torch_version('''<''' , '''2.0''' ) or state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print( '''**Test `accumulate` gradient accumulation with optimizer and scheduler, ''' , '''`split_batches=False`, `dispatch_batches=False`**''' , ) test_gradient_accumulation_with_opt_and_scheduler() if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if not split_batch and not dispatch_batches: continue if state.local_process_index == 0: print( '''**Test `accumulate` gradient accumulation with optimizer and scheduler, ''' , F'`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**' , ) test_gradient_accumulation_with_opt_and_scheduler(snake_case__ , snake_case__ ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' main() if __name__ == "__main__": main()
311
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig 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 ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=30 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=2 , ) -> List[str]: """simple docstring""" A : List[str] = parent A : Optional[Any] = batch_size A : Tuple = image_size A : int = patch_size A : Optional[int] = num_channels A : str = is_training A : List[Any] = use_labels A : Any = hidden_size A : Any = num_hidden_layers A : Optional[int] = num_attention_heads A : Any = intermediate_size A : List[str] = hidden_act A : str = hidden_dropout_prob A : Tuple = attention_probs_dropout_prob A : Any = type_sequence_label_size A : Optional[int] = initializer_range A : Dict = scope A : Tuple = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) A : List[Any] = (image_size // patch_size) ** 2 A : Tuple = num_patches + 2 def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A : Tuple = None if self.use_labels: A : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Tuple = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" return DeiTConfig( 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=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : Any = TFDeiTModel(config=SCREAMING_SNAKE_CASE ) A : str = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" A : Tuple = TFDeiTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE ) A : List[Any] = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A : Optional[int] = 1 A : str = TFDeiTForMaskedImageModeling(SCREAMING_SNAKE_CASE ) A : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Tuple = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" A : str = self.type_sequence_label_size A : Optional[Any] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE ) A : Optional[Any] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images A : Optional[Any] = 1 A : List[str] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE ) A : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Optional[int] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Optional[int] = self.prepare_config_and_inputs() A, A, A : Tuple = config_and_inputs A : Any = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class A ( __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) __magic_name__ = ( { '''feature-extraction''': TFDeiTModel, '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) __magic_name__ = False __magic_name__ = False __magic_name__ = False __magic_name__ = False def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = TFDeiTModelTester(self ) A : Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''DeiT does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" pass def __lowerCAmelCase ( self ) -> str: """simple docstring""" A, A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) A : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE , tf.keras.layers.Dense ) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A, A : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) A : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A : Union[str, Any] = [*signature.parameters.keys()] A : List[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ) -> Tuple: """simple docstring""" A : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def __lowerCAmelCase ( self ) -> str: """simple docstring""" for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A : List[str] = TFDeiTModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_ ( ): '''simple docstring''' A : str = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class A ( unittest.TestCase ): @cached_property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) if is_vision_available() else None ) @slow def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Union[str, Any] = TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) A : Dict = self.default_image_processor A : List[str] = prepare_img() A : Any = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='''tf''' ) # forward pass A : Optional[int] = model(**SCREAMING_SNAKE_CASE ) # verify the logits A : List[Any] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE ) A : str = tf.constant([-1.0_266, 0.1_912, -1.2_861] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
1
'''simple docstring''' import math from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : List[Any] = logging.get_logger(__name__) lowercase : Optional[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 A ( __snake_case ): __magic_name__ = '''data2vec-audio''' def __init__( self , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-5 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=(512, 512, 512, 512, 512, 512, 512) , SCREAMING_SNAKE_CASE=(5, 2, 2, 2, 2, 2, 2) , SCREAMING_SNAKE_CASE=(10, 3, 3, 3, 3, 2, 2) , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=19 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=0.05 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE="sum" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=256 , SCREAMING_SNAKE_CASE=(512, 512, 512, 512, 1500) , SCREAMING_SNAKE_CASE=(5, 3, 3, 1, 1) , SCREAMING_SNAKE_CASE=(1, 2, 3, 1, 1) , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE , pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE ) A : Optional[Any] = hidden_size A : Any = feat_extract_activation A : str = list(SCREAMING_SNAKE_CASE ) A : List[str] = list(SCREAMING_SNAKE_CASE ) A : List[Any] = list(SCREAMING_SNAKE_CASE ) A : str = conv_bias A : Any = num_conv_pos_embeddings A : Tuple = num_conv_pos_embedding_groups A : Union[str, Any] = conv_pos_kernel_size A : Optional[int] = len(self.conv_dim ) A : str = num_hidden_layers A : int = intermediate_size A : Optional[int] = hidden_act A : Dict = num_attention_heads A : str = hidden_dropout A : List[Any] = attention_dropout A : int = activation_dropout A : Any = feat_proj_dropout A : Optional[int] = final_dropout A : List[str] = layerdrop A : int = layer_norm_eps A : int = initializer_range A : int = vocab_size A : List[Any] = 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 A : List[Any] = mask_time_prob A : Tuple = mask_time_length A : Dict = mask_time_min_masks A : List[str] = mask_feature_prob A : Tuple = mask_feature_length A : Optional[int] = mask_feature_min_masks # ctc loss A : Tuple = ctc_loss_reduction A : int = ctc_zero_infinity # adapter A : Optional[Any] = add_adapter A : List[Any] = adapter_kernel_size A : Optional[Any] = adapter_stride A : List[str] = num_adapter_layers A : Optional[Any] = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. A : Optional[int] = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. A : Dict = list(SCREAMING_SNAKE_CASE ) A : Union[str, Any] = list(SCREAMING_SNAKE_CASE ) A : Union[str, Any] = list(SCREAMING_SNAKE_CASE ) A : Union[str, Any] = xvector_output_dim @property def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" return math.prod(self.conv_stride )
311
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase : List[str] = { 'configuration_cpmant': ['CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CpmAntConfig'], 'tokenization_cpmant': ['CpmAntTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[Any] = [ 'CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST', 'CpmAntForCausalLM', 'CpmAntModel', 'CpmAntPreTrainedModel', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys lowercase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
311
1
'''simple docstring''' import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class A ( __snake_case ): __magic_name__ = (DDIMParallelScheduler,) __magic_name__ = (('''eta''', 0.0), ('''num_inference_steps''', 50)) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" A : Optional[Any] = { '''num_train_timesteps''': 1000, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''clip_sample''': True, } config.update(**SCREAMING_SNAKE_CASE ) return config def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" A : int = self.scheduler_classes[0] A : str = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : int = scheduler_class(**SCREAMING_SNAKE_CASE ) A, A : str = 10, 0.0 A : Dict = self.dummy_model() A : List[str] = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for t in scheduler.timesteps: A : Optional[int] = model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : List[str] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample return sample def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" for steps_offset in [0, 1]: self.check_over_configs(steps_offset=SCREAMING_SNAKE_CASE ) A : str = self.scheduler_classes[0] A : Union[str, Any] = self.get_scheduler_config(steps_offset=1 ) A : List[Any] = scheduler_class(**SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE , beta_end=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE , prediction_type=SCREAMING_SNAKE_CASE , sample_max_value=SCREAMING_SNAKE_CASE , ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" for t in [1, 10, 49]: self.check_over_forward(time_step=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE , num_inference_steps=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE , eta=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Optional[int] = self.scheduler_classes[0] A : Any = self.get_scheduler_config() A : Any = scheduler_class(**SCREAMING_SNAKE_CASE ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.14_771 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.32_460 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.00_979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1e-5 def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Tuple = self.scheduler_classes[0] A : str = self.get_scheduler_config() A : Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE ) A, A : int = 10, 0.0 scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) A : List[Any] = self.dummy_model() A : List[str] = self.dummy_sample_deter A : Dict = self.dummy_sample_deter + 0.1 A : Optional[Any] = self.dummy_sample_deter - 0.1 A : Optional[int] = samplea.shape[0] A : Optional[int] = torch.stack([samplea, samplea, samplea] , dim=0 ) A : Tuple = torch.arange(SCREAMING_SNAKE_CASE )[0:3, None].repeat(1 , SCREAMING_SNAKE_CASE ) A : Tuple = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) A : List[Any] = scheduler.batch_step_no_noise(SCREAMING_SNAKE_CASE , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , SCREAMING_SNAKE_CASE ) A : int = torch.sum(torch.abs(SCREAMING_SNAKE_CASE ) ) A : Optional[int] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 1_147.7_904 ) < 1e-2 assert abs(result_mean.item() - 0.4_982 ) < 1e-3 def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Optional[Any] = self.full_loop() A : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE ) ) A : Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 172.0_067 ) < 1e-2 assert abs(result_mean.item() - 0.223_967 ) < 1e-3 def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Union[str, Any] = self.full_loop(prediction_type='''v_prediction''' ) A : Any = torch.sum(torch.abs(SCREAMING_SNAKE_CASE ) ) A : Optional[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 52.5_302 ) < 1e-2 assert abs(result_mean.item() - 0.0_684 ) < 1e-3 def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Tuple = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE , beta_start=0.01 ) A : Any = torch.sum(torch.abs(SCREAMING_SNAKE_CASE ) ) A : Any = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 149.8_295 ) < 1e-2 assert abs(result_mean.item() - 0.1_951 ) < 1e-3 def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Any = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE , beta_start=0.01 ) A : Optional[Any] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE ) ) A : Any = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 149.0_784 ) < 1e-2 assert abs(result_mean.item() - 0.1_941 ) < 1e-3
311
'''simple docstring''' from __future__ import annotations lowercase : Union[str, Any] = list[tuple[int, int]] lowercase : Optional[Any] = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] lowercase : Any = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" A : int = pos_x A : Optional[Any] = pos_y A : Optional[Any] = (pos_y, pos_x) A : str = goal_x A : Optional[int] = goal_y A : List[Any] = g_cost A : str = parent A : str = self.calculate_heuristic() def __lowerCAmelCase ( self ) -> float: """simple docstring""" A : Optional[int] = abs(self.pos_x - self.goal_x ) A : Optional[Any] = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self , SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" return self.f_cost < other.f_cost class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , SCREAMING_SNAKE_CASE ) A : Tuple = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , SCREAMING_SNAKE_CASE ) A : Optional[Any] = [self.start] A : list[Node] = [] A : Tuple = False def __lowerCAmelCase ( self ) -> Path | None: """simple docstring""" while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() A : Optional[int] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: A : Optional[int] = True return self.retrace_path(SCREAMING_SNAKE_CASE ) self.closed_nodes.append(SCREAMING_SNAKE_CASE ) A : Any = self.get_successors(SCREAMING_SNAKE_CASE ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(SCREAMING_SNAKE_CASE ) else: # retrieve the best current path A : str = self.open_nodes.pop(self.open_nodes.index(SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(SCREAMING_SNAKE_CASE ) else: self.open_nodes.append(SCREAMING_SNAKE_CASE ) if not self.reached: return [self.start.pos] return None def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> list[Node]: """simple docstring""" A : List[Any] = [] for action in delta: A : List[str] = parent.pos_x + action[1] A : Dict = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , SCREAMING_SNAKE_CASE , ) ) return successors def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Path: """simple docstring""" A : int = node A : Union[str, Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) A : int = current_node.parent path.reverse() return path if __name__ == "__main__": lowercase : Tuple = (0, 0) lowercase : List[str] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print('------') lowercase : int = GreedyBestFirst(init, goal) lowercase : Union[str, Any] = greedy_bf.search() if path: for pos_x, pos_y in path: lowercase : Dict = 2 for elem in grid: print(elem)
311
1
'''simple docstring''' import math def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if initial_intensity < 0: raise ValueError('''The value of intensity cannot be negative''' ) # handling of negative values of initial intensity if angle < 0 or angle > 360: raise ValueError('''In Malus Law, the angle is in the range 0-360 degrees''' ) # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(snake_case__ ) ) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name='malus_law')
311
'''simple docstring''' import argparse import os from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_task_guides.py lowercase : Any = 'src/transformers' lowercase : str = 'docs/source/en/tasks' def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' with open(snake_case__ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: A : Union[str, Any] = f.readlines() # Find the start prompt. A : List[Any] = 0 while not lines[start_index].startswith(snake_case__ ): start_index += 1 start_index += 1 A : List[str] = start_index while not lines[end_index].startswith(snake_case__ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. lowercase : int = direct_transformers_import(TRANSFORMERS_PATH) lowercase : str = { 'asr.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, 'audio_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, 'language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, 'image_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, 'masked_language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, 'multiple_choice.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, 'object_detection.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, 'question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, 'semantic_segmentation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, 'sequence_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, 'summarization.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'token_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, 'translation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'video_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, 'document_question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, 'monocular_depth_estimation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). lowercase : Optional[int] = { 'summarization.md': ('nllb',), 'translation.md': ('nllb',), } def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : int = TASK_GUIDE_TO_MODELS[task_guide] A : List[str] = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(snake_case__ , set() ) A : Union[str, Any] = { code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([F'[{name}](../model_doc/{code})' for code, name in model_names.items()] ) + "\n" def lowerCAmelCase_ ( snake_case__ , snake_case__=False ): '''simple docstring''' A, A, A, A : Optional[int] = _find_text_in_file( filename=os.path.join(snake_case__ , snake_case__ ) , start_prompt='''<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->''' , end_prompt='''<!--End of the generated tip-->''' , ) A : Optional[int] = get_model_list_for_task(snake_case__ ) if current_list != new_list: if overwrite: with open(os.path.join(snake_case__ , snake_case__ ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:] ) else: raise ValueError( F'The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`' ''' to fix this.''' ) if __name__ == "__main__": lowercase : Dict = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') lowercase : List[Any] = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
311
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor lowercase : Tuple = logging.get_logger(__name__) class A ( __snake_case ): def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" warnings.warn( '''The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DonutImageProcessor instead.''' , SCREAMING_SNAKE_CASE , ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
311
'''simple docstring''' def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if len(snake_case__ ) <= 1: return [tuple(snake_case__ )] A : Tuple = [] def generate(snake_case__ , snake_case__ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , snake_case__ ) for i in range(k - 1 ): if k % 2 == 0: # k is even A, A : Optional[Any] = arr[k - 1], arr[i] else: # k is odd A, A : Optional[Any] = arr[k - 1], arr[0] generate(k - 1 , snake_case__ ) generate(len(snake_case__ ) , snake_case__ ) return res if __name__ == "__main__": lowercase : List[str] = input('Enter numbers separated by a comma:\n').strip() lowercase : int = [int(item) for item in user_input.split(',')] print(heaps(arr))
311
1
'''simple docstring''' import os from pathlib import Path def lowerCAmelCase_ ( ): '''simple docstring''' from torch.utils.cpp_extension import load A : List[Any] = Path(snake_case__ ).resolve().parent.parent.parent / '''kernels''' / '''deformable_detr''' A : Tuple = [ root / filename for filename in [ '''vision.cpp''', os.path.join('''cpu''' , '''ms_deform_attn_cpu.cpp''' ), os.path.join('''cuda''' , '''ms_deform_attn_cuda.cu''' ), ] ] load( '''MultiScaleDeformableAttention''' , snake_case__ , with_cuda=snake_case__ , extra_include_paths=[str(snake_case__ )] , extra_cflags=['''-DWITH_CUDA=1'''] , extra_cuda_cflags=[ '''-DCUDA_HAS_FP16=1''', '''-D__CUDA_NO_HALF_OPERATORS__''', '''-D__CUDA_NO_HALF_CONVERSIONS__''', '''-D__CUDA_NO_HALF2_OPERATORS__''', ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
311
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class A ( __snake_case ): __magic_name__ = (UniPCMultistepScheduler,) __magic_name__ = (('''num_inference_steps''', 25),) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" A : str = { '''num_train_timesteps''': 1000, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''solver_order''': 2, '''solver_type''': '''bh2''', } config.update(**SCREAMING_SNAKE_CASE ) return config def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=0 , **SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : List[Any] = dict(self.forward_default_kwargs ) A : Union[str, Any] = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE ) A : Optional[Any] = self.dummy_sample A : int = 0.1 * sample A : Union[str, Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A : Optional[Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals A : List[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE ) A : List[Any] = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE ) new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals A : Dict = dummy_past_residuals[: new_scheduler.config.solver_order] A, A : Tuple = sample, sample for t in range(SCREAMING_SNAKE_CASE , time_step + scheduler.config.solver_order + 1 ): A : Any = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample A : Optional[Any] = new_scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=0 , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : Optional[Any] = dict(self.forward_default_kwargs ) A : Tuple = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE ) A : List[Any] = self.dummy_sample A : int = 0.1 * sample A : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A : Optional[int] = self.get_scheduler_config() A : Any = scheduler_class(**SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals (must be after setting timesteps) A : int = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE ) A : int = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residual (must be after setting timesteps) A : Optional[Any] = dummy_past_residuals[: new_scheduler.config.solver_order] A : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample A : List[Any] = new_scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" if scheduler is None: A : Dict = self.scheduler_classes[0] A : Union[str, Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : List[Any] = scheduler_class(**SCREAMING_SNAKE_CASE ) A : Tuple = self.scheduler_classes[0] A : Union[str, Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE ) A : int = 10 A : Tuple = self.dummy_model() A : Any = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): A : int = model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Optional[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample return sample def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Tuple = dict(self.forward_default_kwargs ) A : List[Any] = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE ) for scheduler_class in self.scheduler_classes: A : Dict = self.get_scheduler_config() A : Dict = scheduler_class(**SCREAMING_SNAKE_CASE ) A : Optional[Any] = self.dummy_sample A : Optional[int] = 0.1 * sample if num_inference_steps is not None and hasattr(SCREAMING_SNAKE_CASE , '''set_timesteps''' ): scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) elif num_inference_steps is not None and not hasattr(SCREAMING_SNAKE_CASE , '''set_timesteps''' ): A : Tuple = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) A : Dict = [residual + 0.2, residual + 0.15, residual + 0.10] A : List[str] = dummy_past_residuals[: scheduler.config.solver_order] A : List[Any] = scheduler.timesteps[5] A : Dict = scheduler.timesteps[6] A : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample A : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Union[str, Any] = UniPCMultistepScheduler(**self.get_scheduler_config() ) A : List[Any] = self.full_loop(scheduler=SCREAMING_SNAKE_CASE ) A : List[str] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.2_464 ) < 1e-3 A : Dict = DPMSolverSinglestepScheduler.from_config(scheduler.config ) A : Optional[int] = DEISMultistepScheduler.from_config(scheduler.config ) A : List[Any] = DPMSolverMultistepScheduler.from_config(scheduler.config ) A : List[Any] = UniPCMultistepScheduler.from_config(scheduler.config ) A : Optional[Any] = self.full_loop(scheduler=SCREAMING_SNAKE_CASE ) A : Optional[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.2_464 ) < 1e-3 def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE ) 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=SCREAMING_SNAKE_CASE , prediction_type=SCREAMING_SNAKE_CASE , sample_max_value=SCREAMING_SNAKE_CASE , solver_order=SCREAMING_SNAKE_CASE , solver_type=SCREAMING_SNAKE_CASE , ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" for solver_type in ["bh1", "bh2"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=SCREAMING_SNAKE_CASE , solver_type=SCREAMING_SNAKE_CASE , prediction_type=SCREAMING_SNAKE_CASE , ) A : Dict = self.full_loop( solver_order=SCREAMING_SNAKE_CASE , solver_type=SCREAMING_SNAKE_CASE , prediction_type=SCREAMING_SNAKE_CASE , ) assert not torch.isnan(SCREAMING_SNAKE_CASE ).any(), "Samples have nan numbers" def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE ) self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=SCREAMING_SNAKE_CASE , time_step=0 ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : int = self.full_loop() A : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.2_464 ) < 1e-3 def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : List[Any] = self.full_loop(prediction_type='''v_prediction''' ) A : Any = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.1_014 ) < 1e-3 def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Dict = self.scheduler_classes[0] A : List[Any] = self.get_scheduler_config(thresholding=SCREAMING_SNAKE_CASE , dynamic_thresholding_ratio=0 ) A : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE ) A : Tuple = 10 A : Union[str, Any] = self.dummy_model() A : Dict = self.dummy_sample_deter.half() scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): A : Dict = model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Optional[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample assert sample.dtype == torch.floataa def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" for scheduler_class in self.scheduler_classes: A : Dict = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : Tuple = scheduler_class(**SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(scheduler.config.num_train_timesteps ) assert len(scheduler.timesteps.unique() ) == scheduler.num_inference_steps
311
1
'''simple docstring''' lowercase : Dict = 2_56 # Modulus to hash a string lowercase : Optional[int] = 1_00_00_03 def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : Optional[Any] = len(snake_case__ ) A : Union[str, Any] = len(snake_case__ ) if p_len > t_len: return False A : str = 0 A : Optional[Any] = 0 A : Optional[Any] = 1 # Calculating the hash of pattern and substring of text for i in range(snake_case__ ): A : Optional[Any] = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus A : Dict = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue A : Union[str, Any] = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash A : int = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def lowerCAmelCase_ ( ): '''simple docstring''' A : str = '''abc1abc12''' A : List[str] = '''alskfjaldsabc1abc1abc12k23adsfabcabc''' A : Optional[Any] = '''alskfjaldsk23adsfabcabc''' assert rabin_karp(snake_case__ , snake_case__ ) and not rabin_karp(snake_case__ , snake_case__ ) # Test 2) A : Dict = '''ABABX''' A : int = '''ABABZABABYABABX''' assert rabin_karp(snake_case__ , snake_case__ ) # Test 3) A : List[str] = '''AAAB''' A : List[str] = '''ABAAAAAB''' assert rabin_karp(snake_case__ , snake_case__ ) # Test 4) A : Optional[Any] = '''abcdabcy''' A : Optional[Any] = '''abcxabcdabxabcdabcdabcy''' assert rabin_karp(snake_case__ , snake_case__ ) # Test 5) A : Optional[Any] = '''Lü''' A : int = '''Lüsai''' assert rabin_karp(snake_case__ , snake_case__ ) A : str = '''Lue''' assert not rabin_karp(snake_case__ , snake_case__ ) print('''Success.''' ) if __name__ == "__main__": test_rabin_karp()
311
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM A : Dict = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 0.0 , SCREAMING_SNAKE_CASE = 50 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = "pil" , SCREAMING_SNAKE_CASE = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" if isinstance(self.unet.config.sample_size , SCREAMING_SNAKE_CASE ): A : List[Any] = ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size, ) else: A : Optional[int] = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size) if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and len(SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( F'You have passed a list of generators of length {len(SCREAMING_SNAKE_CASE )}, but requested an effective batch' F' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) A : str = randn_tensor(SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output A : Any = self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 A : int = self.scheduler.step( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , eta=SCREAMING_SNAKE_CASE , use_clipped_model_output=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE ).prev_sample A : Dict = (image / 2 + 0.5).clamp(0 , 1 ) A : Optional[int] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": A : int = self.numpy_to_pil(SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE )
311
1
'''simple docstring''' import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class A ( __snake_case ): # to overwrite at feature extractactor specific tests __magic_name__ = None __magic_name__ = None @property def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" return self.feat_extract_tester.prepare_feat_extract_dict() def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''feature_size''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''sampling_rate''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''padding_value''' ) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() A : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) A : Any = feat_extract.model_input_names[0] A : Tuple = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(SCREAMING_SNAKE_CASE ) == len(SCREAMING_SNAKE_CASE ) for x, y in zip(SCREAMING_SNAKE_CASE , processed_features[input_name] ) ) ) A : List[Any] = self.feat_extract_tester.prepare_inputs_for_common(equal_length=SCREAMING_SNAKE_CASE ) A : int = BatchFeature({input_name: speech_inputs} , tensor_type='''np''' ) A : Optional[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: A : Any = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Optional[int] = self.feat_extract_tester.prepare_inputs_for_common(equal_length=SCREAMING_SNAKE_CASE ) A : int = self.feature_extraction_class(**self.feat_extract_dict ) A : Tuple = feat_extract.model_input_names[0] A : Any = BatchFeature({input_name: speech_inputs} , tensor_type='''pt''' ) A : Dict = processed_features[input_name] if len(batch_features_input.shape ) < 3: A : str = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Any = self.feat_extract_tester.prepare_inputs_for_common(equal_length=SCREAMING_SNAKE_CASE ) A : str = self.feature_extraction_class(**self.feat_extract_dict ) A : Union[str, Any] = feat_extract.model_input_names[0] A : List[Any] = BatchFeature({input_name: speech_inputs} , tensor_type='''tf''' ) A : Optional[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: A : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=False ) -> Optional[int]: """simple docstring""" def _inputs_have_equal_length(SCREAMING_SNAKE_CASE ): A : Optional[Any] = len(input[0] ) for input_slice in input[1:]: if len(SCREAMING_SNAKE_CASE ) != length: return False return True def _inputs_are_equal(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): if len(SCREAMING_SNAKE_CASE ) != len(SCREAMING_SNAKE_CASE ): return False for input_slice_a, input_slice_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): if not np.allclose(np.asarray(SCREAMING_SNAKE_CASE ) , np.asarray(SCREAMING_SNAKE_CASE ) , atol=1e-3 ): return False return True A : int = self.feature_extraction_class(**self.feat_extract_dict ) A : Tuple = self.feat_extract_tester.prepare_inputs_for_common(numpify=SCREAMING_SNAKE_CASE ) A : Any = feat_extract.model_input_names[0] A : List[Any] = BatchFeature({input_name: speech_inputs} ) A : Tuple = self.feat_extract_tester.seq_length_diff A : Any = self.feat_extract_tester.max_seq_length + pad_diff A : List[Any] = self.feat_extract_tester.min_seq_length A : Any = self.feat_extract_tester.batch_size A : Union[str, Any] = self.feat_extract_tester.feature_size # test padding for List[int] + numpy A : Tuple = feat_extract.pad(SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE ) A : Union[str, Any] = input_a[input_name] A : Union[str, Any] = feat_extract.pad(SCREAMING_SNAKE_CASE , padding='''longest''' ) A : Dict = input_a[input_name] A : Optional[Any] = feat_extract.pad(SCREAMING_SNAKE_CASE , padding='''max_length''' , max_length=len(speech_inputs[-1] ) ) A : Optional[Any] = input_a[input_name] A : List[str] = feat_extract.pad(SCREAMING_SNAKE_CASE , padding='''longest''' , return_tensors='''np''' ) A : List[str] = input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(SCREAMING_SNAKE_CASE ): feat_extract.pad(SCREAMING_SNAKE_CASE , padding='''max_length''' )[input_name] A : int = feat_extract.pad( SCREAMING_SNAKE_CASE , padding='''max_length''' , max_length=SCREAMING_SNAKE_CASE , return_tensors='''np''' ) A : Any = input_a[input_name] self.assertFalse(_inputs_have_equal_length(SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_are_equal(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy A : str = feat_extract.pad(SCREAMING_SNAKE_CASE , pad_to_multiple_of=10 ) A : Tuple = input_a[input_name] A : str = feat_extract.pad(SCREAMING_SNAKE_CASE , padding='''longest''' , pad_to_multiple_of=10 ) A : Dict = input_a[input_name] A : Union[str, Any] = feat_extract.pad( SCREAMING_SNAKE_CASE , padding='''max_length''' , pad_to_multiple_of=10 , max_length=SCREAMING_SNAKE_CASE ) A : List[str] = input_a[input_name] A : Optional[int] = feat_extract.pad( SCREAMING_SNAKE_CASE , padding='''max_length''' , pad_to_multiple_of=10 , max_length=SCREAMING_SNAKE_CASE , return_tensors='''np''' , ) A : int = input_a[input_name] self.assertTrue(all(len(SCREAMING_SNAKE_CASE ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) A : Optional[int] = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(SCREAMING_SNAKE_CASE ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] , (batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct A : Any = (np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1e-3 ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=False ) -> Optional[Any]: """simple docstring""" def _inputs_have_equal_length(SCREAMING_SNAKE_CASE ): A : str = len(input[0] ) for input_slice in input[1:]: if len(SCREAMING_SNAKE_CASE ) != length: return False return True def _inputs_are_equal(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): if len(SCREAMING_SNAKE_CASE ) != len(SCREAMING_SNAKE_CASE ): return False for input_slice_a, input_slice_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): if not np.allclose(np.asarray(SCREAMING_SNAKE_CASE ) , np.asarray(SCREAMING_SNAKE_CASE ) , atol=1e-3 ): return False return True A : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) A : List[Any] = self.feat_extract_tester.prepare_inputs_for_common(numpify=SCREAMING_SNAKE_CASE ) A : Tuple = feat_extract.model_input_names[0] A : int = BatchFeature({input_name: speech_inputs} ) # truncate to smallest A : str = feat_extract.pad( SCREAMING_SNAKE_CASE , padding='''max_length''' , max_length=len(speech_inputs[0] ) , truncation=SCREAMING_SNAKE_CASE ) A : int = input_a[input_name] A : str = feat_extract.pad(SCREAMING_SNAKE_CASE , padding='''max_length''' , max_length=len(speech_inputs[0] ) ) A : List[Any] = input_a[input_name] self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE ) ) self.assertFalse(_inputs_have_equal_length(SCREAMING_SNAKE_CASE ) ) # truncate to smallest with np A : int = feat_extract.pad( SCREAMING_SNAKE_CASE , padding='''max_length''' , max_length=len(speech_inputs[0] ) , return_tensors='''np''' , truncation=SCREAMING_SNAKE_CASE , ) A : Any = input_a[input_name] A : Any = feat_extract.pad( SCREAMING_SNAKE_CASE , padding='''max_length''' , max_length=len(speech_inputs[0] ) , return_tensors='''np''' ) A : Tuple = input_a[input_name] self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(SCREAMING_SNAKE_CASE ) ) # truncate to middle A : Optional[int] = feat_extract.pad( SCREAMING_SNAKE_CASE , padding='''max_length''' , max_length=len(speech_inputs[1] ) , truncation=SCREAMING_SNAKE_CASE , return_tensors='''np''' , ) A : Any = input_a[input_name] A : Tuple = feat_extract.pad( SCREAMING_SNAKE_CASE , padding='''max_length''' , max_length=len(speech_inputs[1] ) , truncation=SCREAMING_SNAKE_CASE ) A : int = input_a[input_name] A : List[str] = feat_extract.pad( SCREAMING_SNAKE_CASE , padding='''max_length''' , max_length=len(speech_inputs[1] ) , return_tensors='''np''' ) A : List[Any] = input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_are_equal(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(SCREAMING_SNAKE_CASE ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(SCREAMING_SNAKE_CASE ): feat_extract.pad(SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(SCREAMING_SNAKE_CASE ): feat_extract.pad(SCREAMING_SNAKE_CASE , padding='''longest''' , truncation=SCREAMING_SNAKE_CASE )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(SCREAMING_SNAKE_CASE ): feat_extract.pad(SCREAMING_SNAKE_CASE , padding='''longest''' , truncation=SCREAMING_SNAKE_CASE )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(SCREAMING_SNAKE_CASE ): feat_extract.pad(SCREAMING_SNAKE_CASE , padding='''max_length''' , truncation=SCREAMING_SNAKE_CASE )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy A : str = 12 A : List[str] = feat_extract.pad( SCREAMING_SNAKE_CASE , padding='''max_length''' , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , ) A : List[Any] = input_a[input_name] A : str = feat_extract.pad( SCREAMING_SNAKE_CASE , padding='''max_length''' , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=SCREAMING_SNAKE_CASE , ) A : Dict = input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of A : Tuple = len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: A : int = ((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE ) ) self.assertFalse(_inputs_have_equal_length(SCREAMING_SNAKE_CASE ) ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" self._check_padding(numpify=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" self._check_padding(numpify=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" self._check_truncation(numpify=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" self._check_truncation(numpify=SCREAMING_SNAKE_CASE ) @require_torch def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : str = self.feature_extraction_class(**self.feat_extract_dict ) A : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() A : Tuple = feat_extract.model_input_names[0] A : int = BatchFeature({input_name: speech_inputs} ) A : Union[str, Any] = feat_extract.pad(SCREAMING_SNAKE_CASE , padding='''longest''' , return_tensors='''np''' )[input_name] A : List[Any] = feat_extract.pad(SCREAMING_SNAKE_CASE , padding='''longest''' , return_tensors='''pt''' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) @require_tf def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : str = self.feature_extraction_class(**self.feat_extract_dict ) A : Tuple = self.feat_extract_tester.prepare_inputs_for_common() A : List[Any] = feat_extract.model_input_names[0] A : str = BatchFeature({input_name: speech_inputs} ) A : Dict = feat_extract.pad(SCREAMING_SNAKE_CASE , padding='''longest''' , return_tensors='''np''' )[input_name] A : Optional[int] = feat_extract.pad(SCREAMING_SNAKE_CASE , padding='''longest''' , return_tensors='''tf''' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Any = self.feat_extract_dict A : Tuple = True A : List[str] = self.feature_extraction_class(**SCREAMING_SNAKE_CASE ) A : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() A : Any = [len(SCREAMING_SNAKE_CASE ) for x in speech_inputs] A : Dict = feat_extract.model_input_names[0] A : Dict = BatchFeature({input_name: speech_inputs} ) A : Dict = feat_extract.pad(SCREAMING_SNAKE_CASE , padding='''longest''' , return_tensors='''np''' ) self.assertIn('''attention_mask''' , SCREAMING_SNAKE_CASE ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[Any] = self.feat_extract_dict A : Optional[int] = True A : List[Any] = self.feature_extraction_class(**SCREAMING_SNAKE_CASE ) A : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() A : Tuple = [len(SCREAMING_SNAKE_CASE ) for x in speech_inputs] A : Union[str, Any] = feat_extract.model_input_names[0] A : int = BatchFeature({input_name: speech_inputs} ) A : List[str] = min(SCREAMING_SNAKE_CASE ) A : List[str] = feat_extract.pad( SCREAMING_SNAKE_CASE , padding='''max_length''' , max_length=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , return_tensors='''np''' ) self.assertIn('''attention_mask''' , SCREAMING_SNAKE_CASE ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] )
311
'''simple docstring''' from __future__ import annotations from random import random class A : def __init__( self , SCREAMING_SNAKE_CASE = None ) -> Tuple: """simple docstring""" A : Optional[Any] = value A : Any = random() A : Node | None = None A : Node | None = None def __repr__( self ) -> str: """simple docstring""" from pprint import pformat if self.left is None and self.right is None: return F'\'{self.value}: {self.prior:.5}\'' else: return pformat( {F'{self.value}: {self.prior:.5}': (self.left, self.right)} , indent=1 ) def __str__( self ) -> str: """simple docstring""" A : Optional[Any] = str(self.value ) + ''' ''' A : Union[str, Any] = str(self.left or '''''' ) A : Any = str(self.right or '''''' ) return value + left + right def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: A, A : Any = split(root.left , snake_case__ ) return left, root else: A, A : Optional[int] = split(root.right , snake_case__ ) return root, right def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: A : List[str] = merge(left.right , snake_case__ ) return left else: A : Tuple = merge(snake_case__ , right.left ) return right def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : List[Any] = Node(snake_case__ ) A, A : Tuple = split(snake_case__ , snake_case__ ) return merge(merge(snake_case__ , snake_case__ ) , snake_case__ ) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A, A : Dict = split(snake_case__ , value - 1 ) A, A : Any = split(snake_case__ , snake_case__ ) return merge(snake_case__ , snake_case__ ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if not root: # None return else: inorder(root.left ) print(root.value , end=''',''' ) inorder(root.right ) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' for arg in args.split(): if arg[0] == "+": A : int = insert(snake_case__ , int(arg[1:] ) ) elif arg[0] == "-": A : int = erase(snake_case__ , int(arg[1:] ) ) else: print('''Unknown command''' ) return root def lowerCAmelCase_ ( ): '''simple docstring''' A : Union[str, Any] = None print( '''enter numbers to create a tree, + value to add value into treap, ''' '''- value to erase all nodes with value. \'q\' to quit. ''' ) A : Optional[int] = input() while args != "q": A : str = interact_treap(snake_case__ , snake_case__ ) print(snake_case__ ) A : Union[str, Any] = input() print('''good by!''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
311
1
'''simple docstring''' from __future__ import annotations lowercase : int = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" A : Tuple = graph # mapping node to its parent in resulting breadth first tree A : dict[str, str | None] = {} A : List[str] = source_vertex def __lowerCAmelCase ( self ) -> None: """simple docstring""" A : Union[str, Any] = {self.source_vertex} A : Optional[int] = None A : Union[str, Any] = [self.source_vertex] # first in first out queue while queue: A : Tuple = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(SCREAMING_SNAKE_CASE ) A : List[Any] = vertex queue.append(SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" if target_vertex == self.source_vertex: return self.source_vertex A : Any = self.parent.get(SCREAMING_SNAKE_CASE ) if target_vertex_parent is None: A : Tuple = ( F'No path from vertex: {self.source_vertex} to vertex: {target_vertex}' ) raise ValueError(SCREAMING_SNAKE_CASE ) return self.shortest_path(SCREAMING_SNAKE_CASE ) + F'->{target_vertex}' if __name__ == "__main__": lowercase : List[str] = Graph(graph, 'G') g.breath_first_search() print(g.shortest_path('D')) print(g.shortest_path('G')) print(g.shortest_path('Foo'))
311
'''simple docstring''' import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=sys.maxsize ) -> Union[str, Any]: """simple docstring""" A : Tuple = '''bilinear''' A : Optional[int] = max_size A : Dict = short_edge_length def __call__( self , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : Tuple = [] for img in imgs: A, A : str = img.shape[:2] # later: provide list and randomly choose index for resize A : Union[str, Any] = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img A : int = size * 1.0 / min(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if h < w: A, A : Tuple = size, scale * w else: A, A : str = scale * h, size if max(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) > self.max_size: A : List[str] = self.max_size * 1.0 / max(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Tuple = newh * scale A : int = neww * scale A : List[str] = int(neww + 0.5 ) A : int = int(newh + 0.5 ) if img.dtype == np.uinta: A : Dict = Image.fromarray(SCREAMING_SNAKE_CASE ) A : Optional[Any] = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) A : str = np.asarray(SCREAMING_SNAKE_CASE ) else: A : Dict = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw A : List[Any] = nn.functional.interpolate( SCREAMING_SNAKE_CASE , (newh, neww) , mode=self.interp_method , align_corners=SCREAMING_SNAKE_CASE ).squeeze(0 ) img_augs.append(SCREAMING_SNAKE_CASE ) return img_augs class A : def __init__( self , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" A : Any = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) A : str = cfg.INPUT.FORMAT A : int = cfg.SIZE_DIVISIBILITY A : Optional[int] = cfg.PAD_VALUE A : Dict = cfg.INPUT.MAX_SIZE_TEST A : Optional[Any] = cfg.MODEL.DEVICE A : Dict = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) A : Tuple = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) A : str = lambda SCREAMING_SNAKE_CASE : (x - self.pixel_mean) / self.pixel_std def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" A : Union[str, Any] = tuple(max(SCREAMING_SNAKE_CASE ) for s in zip(*[img.shape for img in images] ) ) A : List[str] = [im.shape[-2:] for im in images] A : Optional[Any] = [ nn.functional.pad( SCREAMING_SNAKE_CASE , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ] return torch.stack(SCREAMING_SNAKE_CASE ), torch.tensor(SCREAMING_SNAKE_CASE ) def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ) -> Union[str, Any]: """simple docstring""" with torch.no_grad(): if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : str = [images] if single_image: assert len(SCREAMING_SNAKE_CASE ) == 1 for i in range(len(SCREAMING_SNAKE_CASE ) ): if isinstance(images[i] , torch.Tensor ): images.insert(SCREAMING_SNAKE_CASE , images.pop(SCREAMING_SNAKE_CASE ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( SCREAMING_SNAKE_CASE , torch.as_tensor(img_tensorize(images.pop(SCREAMING_SNAKE_CASE ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge A : Tuple = torch.tensor([im.shape[:2] for im in images] ) A : Dict = self.aug(SCREAMING_SNAKE_CASE ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic A : Tuple = [self.normalizer(SCREAMING_SNAKE_CASE ) for x in images] # now pad them to do the following operations A, A : Optional[int] = self.pad(SCREAMING_SNAKE_CASE ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad A : Tuple = torch.true_divide(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' assert torch.isfinite(snake_case__ ).all(), "Box tensor contains infinite or NaN!" A, A : str = box_size tensor[:, 0].clamp_(min=0 , max=snake_case__ ) tensor[:, 1].clamp_(min=0 , max=snake_case__ ) tensor[:, 2].clamp_(min=0 , max=snake_case__ ) tensor[:, 3].clamp_(min=0 , max=snake_case__ )
311
1
'''simple docstring''' import re def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' return [char.split() for char in re.split(R'''[^ a-z A-Z 0-9 \s]''' , str_ )] def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : List[Any] = split_input(str_ ) return "".join( [''''''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' try: A : Union[str, Any] = split_input(snake_case__ ) if upper: A : Dict = ''''''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: A : Any = ''''''.join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' return to_simple_case(snake_case__ ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' try: A : Tuple = to_simple_case(snake_case__ ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' return to_complex_case(snake_case__ , snake_case__ , '''_''' ) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' return to_complex_case(snake_case__ , snake_case__ , '''-''' ) if __name__ == "__main__": __import__('doctest').testmod()
311
'''simple docstring''' import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": lowercase : Tuple = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml parser.add_argument( '--original_config_file', default=None, type=str, 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( '--scheduler_type', default='pndm', type=str, help='Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']', ) parser.add_argument( '--pipeline_type', default=None, type=str, help=( 'The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\'' '. If `None` pipeline will be automatically inferred.' ), ) parser.add_argument( '--image_size', default=None, 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( '--prediction_type', default=None, type=str, help=( 'The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable' ' Diffusion v2 Base. Use \'v_prediction\' 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.)') parser.add_argument( '--stable_unclip', type=str, default=None, required=False, help='Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.', ) parser.add_argument( '--stable_unclip_prior', type=str, default=None, required=False, help='Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.', ) parser.add_argument( '--clip_stats_path', type=str, help='Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.', required=False, ) parser.add_argument( '--controlnet', action='store_true', default=None, help='Set flag if this is a controlnet checkpoint.' ) parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--vae_path', type=str, default=None, required=False, help='Set to a path, hub id to an already converted vae to not convert it again.', ) lowercase : Tuple = parser.parse_args() lowercase : Union[str, Any] = download_from_original_stable_diffusion_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, prediction_type=args.prediction_type, model_type=args.pipeline_type, extract_ema=args.extract_ema, scheduler_type=args.scheduler_type, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, stable_unclip=args.stable_unclip, stable_unclip_prior=args.stable_unclip_prior, clip_stats_path=args.clip_stats_path, controlnet=args.controlnet, vae_path=args.vae_path, ) if args.half: pipe.to(torch_dtype=torch.floataa) if args.controlnet: # only save the controlnet model pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) else: pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
311
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) if is_sentencepiece_available(): from ..ta.tokenization_ta import TaTokenizer else: from ...utils.dummy_sentencepiece_objects import TaTokenizer lowercase : Optional[int] = TaTokenizer if is_tokenizers_available(): from ..ta.tokenization_ta_fast import TaTokenizerFast else: from ...utils.dummy_tokenizers_objects import TaTokenizerFast lowercase : Dict = TaTokenizerFast lowercase : Optional[int] = {'configuration_mt5': ['MT5Config', 'MT5OnnxConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[Any] = [ 'MT5EncoderModel', 'MT5ForConditionalGeneration', 'MT5ForQuestionAnswering', 'MT5Model', 'MT5PreTrainedModel', 'MT5Stack', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Union[str, Any] = ['TFMT5EncoderModel', 'TFMT5ForConditionalGeneration', 'TFMT5Model'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Dict = ['FlaxMT5EncoderModel', 'FlaxMT5ForConditionalGeneration', 'FlaxMT5Model'] if TYPE_CHECKING: from .configuration_mta import MTaConfig, MTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mta import ( MTaEncoderModel, MTaForConditionalGeneration, MTaForQuestionAnswering, MTaModel, MTaPreTrainedModel, MTaStack, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel else: import sys lowercase : Any = _LazyModule( __name__, globals()['__file__'], _import_structure, extra_objects={'MT5Tokenizer': MTaTokenizer, 'MT5TokenizerFast': MTaTokenizerFast}, module_spec=__spec__, )
311
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal lowercase : str = datasets.utils.logging.get_logger(__name__) lowercase : Union[str, Any] = ['names', 'prefix'] lowercase : Union[str, Any] = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] lowercase : List[Any] = ['encoding_errors', 'on_bad_lines'] lowercase : Any = ['date_format'] @dataclass class A ( datasets.BuilderConfig ): __magic_name__ = "," __magic_name__ = None __magic_name__ = "infer" __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = False __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = True __magic_name__ = False __magic_name__ = True __magic_name__ = None __magic_name__ = "." __magic_name__ = None __magic_name__ = '"' __magic_name__ = 0 __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = True __magic_name__ = 0 __magic_name__ = True __magic_name__ = False __magic_name__ = None __magic_name__ = 10000 __magic_name__ = None __magic_name__ = "strict" __magic_name__ = "error" __magic_name__ = None def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" if self.delimiter is not None: A : Optional[Any] = self.delimiter if self.column_names is not None: A : Optional[Any] = self.column_names @property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : str = { '''sep''': self.sep, '''header''': self.header, '''names''': self.names, '''index_col''': self.index_col, '''usecols''': self.usecols, '''prefix''': self.prefix, '''mangle_dupe_cols''': self.mangle_dupe_cols, '''engine''': self.engine, '''converters''': self.converters, '''true_values''': self.true_values, '''false_values''': self.false_values, '''skipinitialspace''': self.skipinitialspace, '''skiprows''': self.skiprows, '''nrows''': self.nrows, '''na_values''': self.na_values, '''keep_default_na''': self.keep_default_na, '''na_filter''': self.na_filter, '''verbose''': self.verbose, '''skip_blank_lines''': self.skip_blank_lines, '''thousands''': self.thousands, '''decimal''': self.decimal, '''lineterminator''': self.lineterminator, '''quotechar''': self.quotechar, '''quoting''': self.quoting, '''escapechar''': self.escapechar, '''comment''': self.comment, '''encoding''': self.encoding, '''dialect''': self.dialect, '''error_bad_lines''': self.error_bad_lines, '''warn_bad_lines''': self.warn_bad_lines, '''skipfooter''': self.skipfooter, '''doublequote''': self.doublequote, '''memory_map''': self.memory_map, '''float_precision''': self.float_precision, '''chunksize''': self.chunksize, '''encoding_errors''': self.encoding_errors, '''on_bad_lines''': self.on_bad_lines, '''date_format''': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , SCREAMING_SNAKE_CASE ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class A ( datasets.ArrowBasedBuilder ): __magic_name__ = CsvConfig def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) A : int = dl_manager.download_and_extract(self.config.data_files ) if isinstance(SCREAMING_SNAKE_CASE , (str, list, tuple) ): A : str = data_files if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : int = [files] A : Optional[int] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] A : Tuple = [] for split_name, files in data_files.items(): if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : List[str] = [files] A : List[str] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE ) for file in files] splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE , gen_kwargs={'''files''': files} ) ) return splits def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> pa.Table: """simple docstring""" if self.config.features is not None: A : Optional[int] = self.config.features.arrow_schema if all(not require_storage_cast(SCREAMING_SNAKE_CASE ) for feature in self.config.features.values() ): # cheaper cast A : List[Any] = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=SCREAMING_SNAKE_CASE ) else: # more expensive cast; allows str <-> int/float or str to Audio for example A : int = table_cast(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return pa_table def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" A : Union[str, Any] = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str A : int = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(SCREAMING_SNAKE_CASE ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE ) ): A : Union[str, Any] = pd.read_csv(SCREAMING_SNAKE_CASE , iterator=SCREAMING_SNAKE_CASE , dtype=SCREAMING_SNAKE_CASE , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(SCREAMING_SNAKE_CASE ): A : Dict = pa.Table.from_pandas(SCREAMING_SNAKE_CASE ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE ) except ValueError as e: logger.error(F'Failed to read file \'{file}\' with error {type(SCREAMING_SNAKE_CASE )}: {e}' ) raise
311
1
'''simple docstring''' import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO, ) lowercase : Dict = logging.getLogger(__name__) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : int = git.Repo(search_parent_directories=snake_case__ ) A : Any = { '''repo_id''': str(snake_case__ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), } with open(os.path.join(snake_case__ , '''git_log.json''' ) , '''w''' ) as f: json.dump(snake_case__ , snake_case__ , indent=4 ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if params.n_gpu <= 0: A : List[str] = 0 A : Tuple = -1 A : str = True A : List[Any] = False return assert torch.cuda.is_available() logger.info('''Initializing GPUs''' ) if params.n_gpu > 1: assert params.local_rank != -1 A : List[Any] = int(os.environ['''WORLD_SIZE'''] ) A : Union[str, Any] = int(os.environ['''N_GPU_NODE'''] ) A : Dict = int(os.environ['''RANK'''] ) # number of nodes / node ID A : int = params.world_size // params.n_gpu_per_node A : Optional[Any] = params.global_rank // params.n_gpu_per_node A : Union[str, Any] = True assert params.n_nodes == int(os.environ['''N_NODES'''] ) assert params.node_id == int(os.environ['''NODE_RANK'''] ) # local job (single GPU) else: assert params.local_rank == -1 A : Dict = 1 A : Dict = 0 A : Tuple = 0 A : str = 0 A : List[Any] = 1 A : int = 1 A : Tuple = False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode A : str = params.node_id == 0 and params.local_rank == 0 A : Optional[Any] = params.n_nodes > 1 # summary A : List[str] = F'--- Global rank: {params.global_rank} - ' logger.info(PREFIX + '''Number of nodes: %i''' % params.n_nodes ) logger.info(PREFIX + '''Node ID : %i''' % params.node_id ) logger.info(PREFIX + '''Local rank : %i''' % params.local_rank ) logger.info(PREFIX + '''World size : %i''' % params.world_size ) logger.info(PREFIX + '''GPUs per node : %i''' % params.n_gpu_per_node ) logger.info(PREFIX + '''Master : %s''' % str(params.is_master ) ) logger.info(PREFIX + '''Multi-node : %s''' % str(params.multi_node ) ) logger.info(PREFIX + '''Multi-GPU : %s''' % str(params.multi_gpu ) ) logger.info(PREFIX + '''Hostname : %s''' % socket.gethostname() ) # set GPU device torch.cuda.set_device(params.local_rank ) # initialize multi-GPU if params.multi_gpu: logger.info('''Initializing PyTorch distributed''' ) torch.distributed.init_process_group( init_method='''env://''' , backend='''nccl''' , ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
311
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : int = logging.get_logger(__name__) lowercase : int = { 'asapp/sew-tiny-100k': 'https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json', # See all SEW models at https://huggingface.co/models?filter=sew } class A ( __snake_case ): __magic_name__ = '''sew''' def __init__( self , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-5 , SCREAMING_SNAKE_CASE="group" , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , SCREAMING_SNAKE_CASE=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=0.05 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE="mean" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=256 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=2 , **SCREAMING_SNAKE_CASE , ) -> Tuple: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE , pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE ) A : Optional[Any] = hidden_size A : Any = feat_extract_norm A : Optional[int] = feat_extract_activation A : Tuple = list(SCREAMING_SNAKE_CASE ) A : List[str] = list(SCREAMING_SNAKE_CASE ) A : List[str] = list(SCREAMING_SNAKE_CASE ) A : int = conv_bias A : List[Any] = num_conv_pos_embeddings A : Tuple = num_conv_pos_embedding_groups A : int = len(self.conv_dim ) A : Dict = num_hidden_layers A : Optional[int] = intermediate_size A : Any = squeeze_factor A : int = hidden_act A : str = num_attention_heads A : Dict = hidden_dropout A : Optional[Any] = attention_dropout A : List[str] = activation_dropout A : Union[str, Any] = feat_proj_dropout A : Union[str, Any] = final_dropout A : int = layerdrop A : Optional[Any] = layer_norm_eps A : Any = initializer_range A : Tuple = vocab_size 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)`,''' F'but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)' F'= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 A : Optional[Any] = apply_spec_augment A : Optional[Any] = mask_time_prob A : Union[str, Any] = mask_time_length A : Optional[Any] = mask_time_min_masks A : str = mask_feature_prob A : Tuple = mask_feature_length A : Any = mask_feature_min_masks # ctc loss A : List[Any] = ctc_loss_reduction A : Dict = ctc_zero_infinity # sequence classification A : int = use_weighted_layer_sum A : Optional[int] = classifier_proj_size @property def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
311
1
'''simple docstring''' def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if number < 0: raise ValueError('''number must not be negative''' ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
311
'''simple docstring''' import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Dict = SwinConfig() A : List[Any] = swin_name.split('''_''' ) A : Tuple = name_split[1] A : Union[str, Any] = int(name_split[4] ) A : str = int(name_split[3][-1] ) if model_size == "tiny": A : Optional[int] = 96 A : Optional[Any] = (2, 2, 6, 2) A : Any = (3, 6, 12, 24) elif model_size == "small": A : Optional[int] = 96 A : str = (2, 2, 18, 2) A : Tuple = (3, 6, 12, 24) elif model_size == "base": A : int = 128 A : Optional[Any] = (2, 2, 18, 2) A : List[str] = (4, 8, 16, 32) else: A : Dict = 192 A : Optional[Any] = (2, 2, 18, 2) A : Optional[Any] = (6, 12, 24, 48) if "in22k" in swin_name: A : Dict = 2_1841 else: A : str = 1000 A : List[str] = '''huggingface/label-files''' A : Any = '''imagenet-1k-id2label.json''' A : Any = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='''dataset''' ) , '''r''' ) ) A : str = {int(snake_case__ ): v for k, v in idalabel.items()} A : Tuple = idalabel A : Tuple = {v: k for k, v in idalabel.items()} A : Tuple = img_size A : Dict = num_classes A : Optional[Any] = embed_dim A : str = depths A : str = num_heads A : Optional[int] = window_size return config def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if "patch_embed.proj" in name: A : Any = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: A : Tuple = name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: A : Optional[int] = '''encoder.''' + name if "attn.proj" in name: A : List[str] = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: A : List[str] = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: A : Any = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: A : Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: A : Dict = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: A : str = name.replace('''mlp.fc2''' , '''output.dense''' ) if name == "norm.weight": A : Tuple = '''layernorm.weight''' if name == "norm.bias": A : Tuple = '''layernorm.bias''' if "head" in name: A : Any = name.replace('''head''' , '''classifier''' ) else: A : List[Any] = '''swin.''' + name return name def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' for key in orig_state_dict.copy().keys(): A : Dict = orig_state_dict.pop(snake_case__ ) if "mask" in key: continue elif "qkv" in key: A : Dict = key.split('''.''' ) A : Optional[int] = int(key_split[1] ) A : List[str] = int(key_split[3] ) A : Optional[int] = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: A : Any = val[:dim, :] A : Dict = val[ dim : dim * 2, : ] A : List[str] = val[-dim:, :] else: A : Any = val[ :dim ] A : Optional[int] = val[ dim : dim * 2 ] A : Any = val[ -dim: ] else: A : str = val return orig_state_dict def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : Tuple = timm.create_model(snake_case__ , pretrained=snake_case__ ) timm_model.eval() A : Optional[Any] = get_swin_config(snake_case__ ) A : Optional[int] = SwinForImageClassification(snake_case__ ) model.eval() A : List[str] = convert_state_dict(timm_model.state_dict() , snake_case__ ) model.load_state_dict(snake_case__ ) A : Optional[int] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' A : Any = AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swin_name.replace('''_''' , '''-''' ) ) ) A : List[Any] = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) A : List[Any] = image_processor(images=snake_case__ , return_tensors='''pt''' ) A : Any = timm_model(inputs['''pixel_values'''] ) A : Optional[Any] = model(**snake_case__ ).logits assert torch.allclose(snake_case__ , snake_case__ , atol=1E-3 ) print(F'Saving model {swin_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case__ ) if __name__ == "__main__": lowercase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swin_name', default='swin_tiny_patch4_window7_224', type=str, help='Name of the Swin timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) lowercase : int = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
311
1
'''simple docstring''' from __future__ import annotations import math def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(snake_case__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True lowercase : Any = [num for num in range(3, 10_00_01, 2) if not is_prime(num)] def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if not isinstance(snake_case__ , snake_case__ ): raise ValueError('''n must be an integer''' ) if n <= 0: raise ValueError('''n must be >= 0''' ) A : Optional[int] = [] for num in range(len(snake_case__ ) ): A : Dict = 0 while 2 * i * i <= odd_composites[num]: A : Optional[Any] = odd_composites[num] - 2 * i * i if is_prime(snake_case__ ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(snake_case__ ) == n: return list_nums return [] def lowerCAmelCase_ ( ): '''simple docstring''' return compute_nums(1 )[0] if __name__ == "__main__": print(f'''{solution() = }''')
311
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : Optional[int] = logging.get_logger(__name__) lowercase : Tuple = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class A ( __snake_case ): __magic_name__ = '''pix2struct_text_model''' __magic_name__ = ['''past_key_values'''] __magic_name__ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , SCREAMING_SNAKE_CASE=50244 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Optional[Any]: """simple docstring""" A : str = vocab_size A : List[str] = hidden_size A : List[Any] = d_kv A : Optional[Any] = d_ff A : Dict = num_layers A : Dict = num_heads A : Optional[int] = relative_attention_num_buckets A : Optional[Any] = relative_attention_max_distance A : Dict = dropout_rate A : Dict = layer_norm_epsilon A : Tuple = initializer_factor A : Union[str, Any] = use_cache A : int = eos_token_id A : List[str] = decoder_start_token_id # for backwards compatibility A : int = dense_act_fn super().__init__( pad_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , decoder_start_token_id=SCREAMING_SNAKE_CASE , tie_word_embeddings=SCREAMING_SNAKE_CASE , is_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) A, A : Optional[Any] = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": A : Union[str, Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A ( __snake_case ): __magic_name__ = '''pix2struct_vision_model''' def __init__( self , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=1e-10 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=4096 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=128 , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) A : List[str] = hidden_size A : Optional[Any] = patch_embed_hidden_size A : Union[str, Any] = d_ff A : Dict = dropout_rate A : str = num_hidden_layers A : Dict = num_attention_heads A : Tuple = initializer_range A : List[str] = initializer_factor A : Union[str, Any] = attention_dropout A : Tuple = layer_norm_eps A : int = dense_act_fn A : Optional[int] = seq_len A : Tuple = relative_attention_num_buckets A : str = relative_attention_max_distance A : Optional[Any] = d_kv @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) A, A : int = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": A : Optional[Any] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A ( __snake_case ): __magic_name__ = '''pix2struct''' __magic_name__ = True def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(tie_word_embeddings=SCREAMING_SNAKE_CASE , is_encoder_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) if text_config is None: A : Dict = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: A : str = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) A : Dict = PixaStructTextConfig(**SCREAMING_SNAKE_CASE ) A : Any = PixaStructVisionConfig(**SCREAMING_SNAKE_CASE ) A : Any = self.text_config.decoder_start_token_id A : Any = self.text_config.pad_token_id A : Dict = self.text_config.eos_token_id A : Union[str, Any] = initializer_factor A : Tuple = initializer_range A : Optional[Any] = self.initializer_range A : int = self.initializer_range A : Tuple = is_vqa @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Tuple = copy.deepcopy(self.__dict__ ) A : Dict = self.text_config.to_dict() A : int = self.vision_config.to_dict() A : Any = self.__class__.model_type return output
311
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase : Optional[int] = { 'configuration_time_series_transformer': [ 'TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimeSeriesTransformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : int = [ 'TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TimeSeriesTransformerForPrediction', 'TimeSeriesTransformerModel', 'TimeSeriesTransformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys lowercase : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
311
'''simple docstring''' from __future__ import annotations def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : List[str] = 2 A : Dict = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(snake_case__ ) if n > 1: factors.append(snake_case__ ) return factors if __name__ == "__main__": import doctest doctest.testmod()
311
1
'''simple docstring''' def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if not nums: # Makes sure that the list is not empty raise ValueError('''List is empty''' ) A : Optional[Any] = sum(snake_case__ ) / len(snake_case__ ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(snake_case__ ) if __name__ == "__main__": import doctest doctest.testmod()
311
'''simple docstring''' # Function to print upper half of diamond (pyramid) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for i in range(0 , snake_case__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(''' ''' , end='''''' ) for _ in range(0 , i + 1 ): # printing stars print('''* ''' , end='''''' ) print() def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for i in range(snake_case__ , 0 , -1 ): for _ in range(snake_case__ , 0 , -1 ): # printing stars print('''* ''' , end='''''' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(''' ''' , end='''''' ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if n <= 0: print(''' ... .... nothing printing :(''' ) return floyd(snake_case__ ) # upper half reverse_floyd(snake_case__ ) # lower half if __name__ == "__main__": print(R'| /\ | |- | |- |--| |\ /| |-') print(R'|/ \| |- |_ |_ |__| | \/ | |_') lowercase : List[str] = 1 while K: lowercase : List[Any] = int(input('enter the number and , and see the magic : ')) print() pretty_print(user_number) lowercase : Any = int(input('press 0 to exit... and 1 to continue...')) print('Good Bye...')
311
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowercase : int = { 'configuration_transfo_xl': ['TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TransfoXLConfig'], 'tokenization_transfo_xl': ['TransfoXLCorpus', 'TransfoXLTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[Any] = [ 'TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST', 'AdaptiveEmbedding', 'TransfoXLForSequenceClassification', 'TransfoXLLMHeadModel', 'TransfoXLModel', 'TransfoXLPreTrainedModel', 'load_tf_weights_in_transfo_xl', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : str = [ 'TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFAdaptiveEmbedding', 'TFTransfoXLForSequenceClassification', 'TFTransfoXLLMHeadModel', 'TFTransfoXLMainLayer', 'TFTransfoXLModel', 'TFTransfoXLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_transfo_xl import ( TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, AdaptiveEmbedding, TransfoXLForSequenceClassification, TransfoXLLMHeadModel, TransfoXLModel, TransfoXLPreTrainedModel, load_tf_weights_in_transfo_xl, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_transfo_xl import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFAdaptiveEmbedding, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLMainLayer, TFTransfoXLModel, TFTransfoXLPreTrainedModel, ) else: import sys lowercase : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
311
'''simple docstring''' # limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 50 , SCREAMING_SNAKE_CASE = "pil" , SCREAMING_SNAKE_CASE = True , **SCREAMING_SNAKE_CASE , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" A : List[Any] = torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=SCREAMING_SNAKE_CASE , ) A : Optional[Any] = image.to(self.device ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output A : Tuple = self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 A : List[Any] = self.scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample A : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) A : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": A : List[Any] = self.numpy_to_pil(SCREAMING_SNAKE_CASE ) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE ), "This is a local test"
311
1
'''simple docstring''' import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version('>=', FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType lowercase : Optional[Any] = get_logger(__name__) def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__=0 ): '''simple docstring''' os.makedirs(snake_case__ , exist_ok=snake_case__ ) with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): A : str = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: A : List[str] = F'{MODEL_NAME}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}.bin' A : Any = os.path.join(snake_case__ , snake_case__ ) if accelerator.process_index == 0: logger.info(F'Saving model to {output_model_file}' ) torch.save(snake_case__ , snake_case__ ) logger.info(F'Model saved to {output_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: A : List[str] = ( F'{MODEL_NAME}_rank{accelerator.process_index}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin' ) A : List[Any] = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Saving model to {output_model_file}' ) torch.save(snake_case__ , snake_case__ ) logger.info(F'Model saved to {output_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: A : int = os.path.join(snake_case__ , F'{MODEL_NAME}_{model_index}' ) os.makedirs(snake_case__ , exist_ok=snake_case__ ) logger.info(F'Saving model to {ckpt_dir}' ) A : Optional[int] = {'''model''': state_dict} dist_cp.save_state_dict( state_dict=snake_case__ , storage_writer=dist_cp.FileSystemWriter(snake_case__ ) , planner=DefaultSavePlanner() , ) logger.info(F'Model saved to {ckpt_dir}' ) def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__=0 ): '''simple docstring''' accelerator.wait_for_everyone() with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(snake_case__ ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( '''Set the `sync_module_states` flag to `True` so that model states are synced across processes when ''' '''initializing FSDP object''' ) return A : str = F'{MODEL_NAME}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}.bin' A : List[str] = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Loading model from {input_model_file}' ) A : List[Any] = torch.load(snake_case__ ) logger.info(F'Model loaded from {input_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: A : Any = ( F'{MODEL_NAME}_rank{accelerator.process_index}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin' ) A : int = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Loading model from {input_model_file}' ) A : Optional[int] = torch.load(snake_case__ ) logger.info(F'Model loaded from {input_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: A : Optional[int] = ( os.path.join(snake_case__ , F'{MODEL_NAME}_{model_index}' ) if F'{MODEL_NAME}' not in input_dir else input_dir ) logger.info(F'Loading model from {ckpt_dir}' ) A : Optional[int] = {'''model''': model.state_dict()} dist_cp.load_state_dict( state_dict=snake_case__ , storage_reader=dist_cp.FileSystemReader(snake_case__ ) , planner=DefaultLoadPlanner() , ) A : Union[str, Any] = state_dict['''model'''] logger.info(F'Model loaded from {ckpt_dir}' ) model.load_state_dict(snake_case__ ) def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__=0 ): '''simple docstring''' os.makedirs(snake_case__ , exist_ok=snake_case__ ) with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): A : Any = FSDP.optim_state_dict(snake_case__ , snake_case__ ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: A : Optional[Any] = ( F'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else F'{OPTIMIZER_NAME}_{optimizer_index}.bin' ) A : Dict = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Saving Optimizer state to {output_optimizer_file}' ) torch.save(snake_case__ , snake_case__ ) logger.info(F'Optimizer state saved in {output_optimizer_file}' ) else: A : Any = os.path.join(snake_case__ , F'{OPTIMIZER_NAME}_{optimizer_index}' ) os.makedirs(snake_case__ , exist_ok=snake_case__ ) logger.info(F'Saving Optimizer state to {ckpt_dir}' ) dist_cp.save_state_dict( state_dict={'''optimizer''': optim_state} , storage_writer=dist_cp.FileSystemWriter(snake_case__ ) , planner=DefaultSavePlanner() , ) logger.info(F'Optimizer state saved in {ckpt_dir}' ) def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__=0 ): '''simple docstring''' accelerator.wait_for_everyone() with FSDP.state_dict_type( snake_case__ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: A : Tuple = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: A : Optional[Any] = ( F'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else F'{OPTIMIZER_NAME}_{optimizer_index}.bin' ) A : Optional[int] = os.path.join(snake_case__ , snake_case__ ) logger.info(F'Loading Optimizer state from {input_optimizer_file}' ) A : List[Any] = torch.load(snake_case__ ) logger.info(F'Optimizer state loaded from {input_optimizer_file}' ) else: A : Dict = ( os.path.join(snake_case__ , F'{OPTIMIZER_NAME}_{optimizer_index}' ) if F'{OPTIMIZER_NAME}' not in input_dir else input_dir ) logger.info(F'Loading Optimizer from {ckpt_dir}' ) A : str = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() , optimizer_key='''optimizer''' , storage_reader=dist_cp.FileSystemReader(snake_case__ ) , ) A : Optional[int] = optim_state['''optimizer'''] logger.info(F'Optimizer loaded from {ckpt_dir}' ) A : List[Any] = FSDP.optim_state_dict_to_load(snake_case__ , snake_case__ , snake_case__ ) optimizer.load_state_dict(snake_case__ )
311
'''simple docstring''' import unittest from transformers import BertGenerationConfig, 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 BertGenerationDecoder, BertGenerationEncoder class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=50 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=None , ) -> str: """simple docstring""" A : Any = parent A : List[Any] = batch_size A : Union[str, Any] = seq_length A : Any = is_training A : int = use_input_mask A : Union[str, Any] = vocab_size A : List[Any] = hidden_size A : List[Any] = num_hidden_layers A : Optional[int] = num_attention_heads A : str = intermediate_size A : Tuple = hidden_act A : Union[str, Any] = hidden_dropout_prob A : Union[str, Any] = attention_probs_dropout_prob A : int = max_position_embeddings A : Optional[int] = initializer_range A : Any = use_labels A : Optional[int] = scope def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Optional[int] = None if self.use_input_mask: A : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: A : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Dict = self.get_config() return config, input_ids, input_mask, token_labels def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" return BertGenerationConfig( 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 , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" ( ( A ), ( A ), ( A ), ( A ), ) : Any = self.prepare_config_and_inputs() A : Tuple = True A : int = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A : str = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" A : List[str] = BertGenerationEncoder(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) A : int = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> Union[str, Any]: """simple docstring""" A : List[str] = True A : Union[str, Any] = BertGenerationEncoder(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , ) A : List[Any] = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" A : Optional[Any] = True A : Tuple = True A : Optional[int] = BertGenerationDecoder(config=SCREAMING_SNAKE_CASE ).to(SCREAMING_SNAKE_CASE ).eval() # first forward pass A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , use_cache=SCREAMING_SNAKE_CASE , ) A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A : List[str] = ids_tensor((self.batch_size, 3) , config.vocab_size ) A : Tuple = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and A : Dict = torch.cat([input_ids, next_tokens] , dim=-1 ) A : List[str] = torch.cat([input_mask, next_mask] , dim=-1 ) A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE , )['''hidden_states'''][0] A : Any = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , past_key_values=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE , )['''hidden_states'''][0] # select random slice A : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() A : List[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() A : str = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" A : Optional[Any] = BertGenerationDecoder(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Optional[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A, A, A, A : Optional[int] = self.prepare_config_and_inputs() A : str = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class A ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () __magic_name__ = (BertGenerationDecoder,) if is_torch_available() else () __magic_name__ = ( {'''feature-extraction''': BertGenerationEncoder, '''text-generation''': BertGenerationDecoder} if is_torch_available() else {} ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : List[str] = BertGenerationEncoderTester(self ) A : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A, A, A, A : Tuple = self.model_tester.prepare_config_and_inputs() A : str = '''bert''' self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : int = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" ( ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ) : Tuple = self.model_tester.prepare_config_and_inputs_for_decoder() A : Union[str, Any] = None self.model_tester.create_and_check_model_as_decoder( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*SCREAMING_SNAKE_CASE ) @slow def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Optional[Any] = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) A : Optional[Any] = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]] ) with torch.no_grad(): A : Dict = model(SCREAMING_SNAKE_CASE )[0] A : Optional[Any] = torch.Size([1, 8, 1024] ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : Dict = torch.tensor( [[[0.1_775, 0.0_083, -0.0_321], [1.6_002, 0.1_287, 0.3_912], [2.1_473, 0.5_791, 0.6_066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[Any] = BertGenerationDecoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) A : Dict = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]] ) with torch.no_grad(): A : Optional[Any] = model(SCREAMING_SNAKE_CASE )[0] A : Optional[Any] = torch.Size([1, 8, 50358] ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : Any = torch.tensor( [[[-0.5_788, -2.5_994, -3.7_054], [0.0_438, 4.7_997, 1.8_795], [1.5_862, 6.6_409, 4.4_638]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
1
'''simple docstring''' def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(snake_case__ , snake_case__ ): raise TypeError('''Input value must be a \'int\' type''' ) return bin(snake_case__ ).count('''1''' ) if __name__ == "__main__": import doctest doctest.testmod()
311
'''simple docstring''' import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' return 1.0 / (1.0 + np.exp(-_outputs )) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Optional[int] = np.max(_outputs , axis=-1 , keepdims=snake_case__ ) A : Any = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=snake_case__ ) class A ( __snake_case ): __magic_name__ = '''sigmoid''' __magic_name__ = '''softmax''' __magic_name__ = '''none''' @add_end_docstrings( __snake_case , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class A ( __snake_case ): __magic_name__ = False __magic_name__ = ClassificationFunction.NONE def __init__( self , **SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE="" , **SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" A : Optional[Any] = tokenizer_kwargs A : int = {} if hasattr(self.model.config , '''return_all_scores''' ) and return_all_scores is None: A : int = self.model.config.return_all_scores if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) or top_k is None: A : Union[str, Any] = top_k A : Dict = False elif return_all_scores is not None: warnings.warn( '''`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of''' ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.''' , SCREAMING_SNAKE_CASE , ) if return_all_scores: A : Optional[int] = None else: A : Dict = 1 if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : Dict = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: A : int = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : str = super().__call__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. A : Any = '''top_k''' not in kwargs if isinstance(args[0] , SCREAMING_SNAKE_CASE ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Dict[str, GenericTensor]: """simple docstring""" A : List[Any] = self.framework if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): return self.tokenizer(**SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and len(SCREAMING_SNAKE_CASE ) == 1 and isinstance(inputs[0] , SCREAMING_SNAKE_CASE ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a''' ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.''' ) return self.tokenizer(SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" return self.model(**SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=True ) -> List[str]: """simple docstring""" if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: A : Optional[int] = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: A : Any = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , '''function_to_apply''' ) and function_to_apply is None: A : Optional[int] = self.model.config.function_to_apply else: A : Optional[int] = ClassificationFunction.NONE A : Any = model_outputs['''logits'''][0] A : List[Any] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: A : int = sigmoid(SCREAMING_SNAKE_CASE ) elif function_to_apply == ClassificationFunction.SOFTMAX: A : Any = softmax(SCREAMING_SNAKE_CASE ) elif function_to_apply == ClassificationFunction.NONE: A : int = outputs else: raise ValueError(F'Unrecognized `function_to_apply` argument: {function_to_apply}' ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} A : int = [ {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(SCREAMING_SNAKE_CASE ) ] if not _legacy: dict_scores.sort(key=lambda SCREAMING_SNAKE_CASE : x["score"] , reverse=SCREAMING_SNAKE_CASE ) if top_k is not None: A : Union[str, Any] = dict_scores[:top_k] return dict_scores
311
1
'''simple docstring''' import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Dict = SwinConfig() A : List[Any] = swin_name.split('''_''' ) A : Tuple = name_split[1] A : Union[str, Any] = int(name_split[4] ) A : str = int(name_split[3][-1] ) if model_size == "tiny": A : Optional[int] = 96 A : Optional[Any] = (2, 2, 6, 2) A : Any = (3, 6, 12, 24) elif model_size == "small": A : Optional[int] = 96 A : str = (2, 2, 18, 2) A : Tuple = (3, 6, 12, 24) elif model_size == "base": A : int = 128 A : Optional[Any] = (2, 2, 18, 2) A : List[str] = (4, 8, 16, 32) else: A : Dict = 192 A : Optional[Any] = (2, 2, 18, 2) A : Optional[Any] = (6, 12, 24, 48) if "in22k" in swin_name: A : Dict = 2_1841 else: A : str = 1000 A : List[str] = '''huggingface/label-files''' A : Any = '''imagenet-1k-id2label.json''' A : Any = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='''dataset''' ) , '''r''' ) ) A : str = {int(snake_case__ ): v for k, v in idalabel.items()} A : Tuple = idalabel A : Tuple = {v: k for k, v in idalabel.items()} A : Tuple = img_size A : Dict = num_classes A : Optional[Any] = embed_dim A : str = depths A : str = num_heads A : Optional[int] = window_size return config def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if "patch_embed.proj" in name: A : Any = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: A : Tuple = name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: A : Optional[int] = '''encoder.''' + name if "attn.proj" in name: A : List[str] = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: A : List[str] = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: A : Any = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: A : Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: A : Dict = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: A : str = name.replace('''mlp.fc2''' , '''output.dense''' ) if name == "norm.weight": A : Tuple = '''layernorm.weight''' if name == "norm.bias": A : Tuple = '''layernorm.bias''' if "head" in name: A : Any = name.replace('''head''' , '''classifier''' ) else: A : List[Any] = '''swin.''' + name return name def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' for key in orig_state_dict.copy().keys(): A : Dict = orig_state_dict.pop(snake_case__ ) if "mask" in key: continue elif "qkv" in key: A : Dict = key.split('''.''' ) A : Optional[int] = int(key_split[1] ) A : List[str] = int(key_split[3] ) A : Optional[int] = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: A : Any = val[:dim, :] A : Dict = val[ dim : dim * 2, : ] A : List[str] = val[-dim:, :] else: A : Any = val[ :dim ] A : Optional[int] = val[ dim : dim * 2 ] A : Any = val[ -dim: ] else: A : str = val return orig_state_dict def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : Tuple = timm.create_model(snake_case__ , pretrained=snake_case__ ) timm_model.eval() A : Optional[Any] = get_swin_config(snake_case__ ) A : Optional[int] = SwinForImageClassification(snake_case__ ) model.eval() A : List[str] = convert_state_dict(timm_model.state_dict() , snake_case__ ) model.load_state_dict(snake_case__ ) A : Optional[int] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' A : Any = AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swin_name.replace('''_''' , '''-''' ) ) ) A : List[Any] = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) A : List[Any] = image_processor(images=snake_case__ , return_tensors='''pt''' ) A : Any = timm_model(inputs['''pixel_values'''] ) A : Optional[Any] = model(**snake_case__ ).logits assert torch.allclose(snake_case__ , snake_case__ , atol=1E-3 ) print(F'Saving model {swin_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case__ ) if __name__ == "__main__": lowercase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swin_name', default='swin_tiny_patch4_window7_224', type=str, help='Name of the Swin timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) lowercase : int = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
311
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCAmelCase_ ( snake_case__ = "laptop" ): '''simple docstring''' A : Tuple = F'https://www.amazon.in/laptop/s?k={product}' A : Optional[int] = { '''User-Agent''': '''Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36''', '''Accept-Language''': '''en-US, en;q=0.5''', } A : Any = BeautifulSoup(requests.get(snake_case__ , headers=snake_case__ ).text ) # Initialize a Pandas dataframe with the column titles A : List[str] = DataFrame( columns=[ '''Product Title''', '''Product Link''', '''Current Price of the product''', '''Product Rating''', '''MRP of the product''', '''Discount''', ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( '''div''' , attrs={'''class''': '''s-result-item''', '''data-component-type''': '''s-search-result'''} , ) , soup.find_all('''div''' , attrs={'''class''': '''a-row a-size-base a-color-base'''} ) , ): try: A : Optional[Any] = item.ha.text A : Union[str, Any] = '''https://www.amazon.in/''' + item.ha.a['''href'''] A : Tuple = item.find('''span''' , attrs={'''class''': '''a-offscreen'''} ).text try: A : int = item.find('''span''' , attrs={'''class''': '''a-icon-alt'''} ).text except AttributeError: A : Optional[int] = '''Not available''' try: A : str = ( '''₹''' + item.find( '''span''' , attrs={'''class''': '''a-price a-text-price'''} ).text.split('''₹''' )[1] ) except AttributeError: A : List[Any] = '''''' try: A : Dict = float( ( ( float(product_mrp.strip('''₹''' ).replace(''',''' , '''''' ) ) - float(product_price.strip('''₹''' ).replace(''',''' , '''''' ) ) ) / float(product_mrp.strip('''₹''' ).replace(''',''' , '''''' ) ) ) * 100 ) except ValueError: A : str = float('''nan''' ) except AttributeError: pass A : Union[str, Any] = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] A : List[str] = ''' ''' A : Optional[Any] = ''' ''' data_frame.index += 1 return data_frame if __name__ == "__main__": lowercase : Union[str, Any] = 'headphones' get_amazon_product_data(product).to_csv(f'''Amazon Product Data for {product}.csv''')
311
1
'''simple docstring''' import argparse import importlib from pathlib import Path # Test all the extensions added in the setup lowercase : Optional[int] = [ 'kernels/rwkv/wkv_cuda.cu', 'kernels/rwkv/wkv_op.cpp', 'kernels/deformable_detr/ms_deform_attn.h', 'kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh', 'models/graphormer/algos_graphormer.pyx', ] def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for file in FILES_TO_FIND: if not (transformers_path / file).exists(): return False return True if __name__ == "__main__": lowercase : str = argparse.ArgumentParser() parser.add_argument('--check_lib', action='store_true', help='Whether to check the build or the actual package.') lowercase : Optional[Any] = parser.parse_args() if args.check_lib: lowercase : List[Any] = importlib.import_module('transformers') lowercase : str = Path(transformers_module.__file__).parent else: lowercase : List[Any] = Path.cwd() / 'build/lib/transformers' if not test_custom_files_are_present(transformers_path): raise ValueError('The built release does not contain the custom files. Fix this before going further!')
311
'''simple docstring''' import colorsys from PIL import Image # type: ignore def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : Optional[int] = x A : str = y for step in range(snake_case__ ): # noqa: B007 A : str = a * a - b * b + x A : List[str] = 2 * a * b + y A : str = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255 ) for i in colorsys.hsv_to_rgb(snake_case__ , 1 , 1 ) ) def lowerCAmelCase_ ( snake_case__ = 800 , snake_case__ = 600 , snake_case__ = -0.6 , snake_case__ = 0 , snake_case__ = 3.2 , snake_case__ = 50 , snake_case__ = True , ): '''simple docstring''' A : List[Any] = Image.new('''RGB''' , (image_width, image_height) ) A : Tuple = img.load() # loop through the image-coordinates for image_x in range(snake_case__ ): for image_y in range(snake_case__ ): # determine the figure-coordinates based on the image-coordinates A : Optional[int] = figure_width / image_width * image_height A : Tuple = figure_center_x + (image_x / image_width - 0.5) * figure_width A : List[str] = figure_center_y + (image_y / image_height - 0.5) * figure_height A : str = get_distance(snake_case__ , snake_case__ , snake_case__ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: A : str = get_color_coded_rgb(snake_case__ ) else: A : List[Any] = get_black_and_white_rgb(snake_case__ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure lowercase : Optional[Any] = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
311
1
'''simple docstring''' import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class A ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : List[Any] = inspect.getfile(accelerate.test_utils ) A : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) A : Optional[Any] = os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] ) @require_tpu def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Union[str, Any] = F'\n {self.test_dir}/xla_spawn.py\n --num_cores 8\n {self.test_file_path}\n '.split() A : Dict = [sys.executable] + distributed_args execute_subprocess_async(SCREAMING_SNAKE_CASE , env=os.environ.copy() )
311
'''simple docstring''' import argparse import importlib from pathlib import Path # Test all the extensions added in the setup lowercase : Optional[int] = [ 'kernels/rwkv/wkv_cuda.cu', 'kernels/rwkv/wkv_op.cpp', 'kernels/deformable_detr/ms_deform_attn.h', 'kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh', 'models/graphormer/algos_graphormer.pyx', ] def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for file in FILES_TO_FIND: if not (transformers_path / file).exists(): return False return True if __name__ == "__main__": lowercase : str = argparse.ArgumentParser() parser.add_argument('--check_lib', action='store_true', help='Whether to check the build or the actual package.') lowercase : Optional[Any] = parser.parse_args() if args.check_lib: lowercase : List[Any] = importlib.import_module('transformers') lowercase : str = Path(transformers_module.__file__).parent else: lowercase : List[Any] = Path.cwd() / 'build/lib/transformers' if not test_custom_files_are_present(transformers_path): raise ValueError('The built release does not contain the custom files. Fix this before going further!')
311
1
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class A ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Any = tempfile.mkdtemp() # fmt: off A : Optional[Any] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on A : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) A : Tuple = { '''do_resize''': True, '''size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } A : Optional[Any] = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" return ViTImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] A : int = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : int = self.get_tokenizer() A : Union[str, Any] = self.get_image_processor() A : List[str] = VisionTextDualEncoderProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE ) processor.save_pretrained(self.tmpdirname ) A : Any = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Any = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Dict = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) A : Optional[int] = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE , padding_value=1.0 ) A : Union[str, Any] = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Dict = self.get_image_processor() A : List[Any] = self.get_tokenizer() A : str = VisionTextDualEncoderProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE ) A : List[str] = self.prepare_image_inputs() A : int = image_processor(SCREAMING_SNAKE_CASE , return_tensors='''np''' ) A : List[Any] = processor(images=SCREAMING_SNAKE_CASE , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Optional[Any] = self.get_image_processor() A : int = self.get_tokenizer() A : Tuple = VisionTextDualEncoderProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE ) A : Dict = '''lower newer''' A : Tuple = processor(text=SCREAMING_SNAKE_CASE ) A : List[Any] = tokenizer(SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Optional[Any] = self.get_image_processor() A : int = self.get_tokenizer() A : Any = VisionTextDualEncoderProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE ) A : Dict = '''lower newer''' A : Any = self.prepare_image_inputs() A : str = processor(text=SCREAMING_SNAKE_CASE , images=SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(SCREAMING_SNAKE_CASE ): processor() def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : List[str] = self.get_image_processor() A : Optional[Any] = self.get_tokenizer() A : Tuple = VisionTextDualEncoderProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE ) A : Dict = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] A : List[Any] = processor.batch_decode(SCREAMING_SNAKE_CASE ) A : str = tokenizer.batch_decode(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Optional[Any] = self.get_image_processor() A : Union[str, Any] = self.get_tokenizer() A : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE ) A : Tuple = '''lower newer''' A : Optional[Any] = self.prepare_image_inputs() A : Tuple = processor(text=SCREAMING_SNAKE_CASE , images=SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
311
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig 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 ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=30 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=2 , ) -> List[str]: """simple docstring""" A : List[str] = parent A : Optional[Any] = batch_size A : Tuple = image_size A : int = patch_size A : Optional[int] = num_channels A : str = is_training A : List[Any] = use_labels A : Any = hidden_size A : Any = num_hidden_layers A : Optional[int] = num_attention_heads A : Any = intermediate_size A : List[str] = hidden_act A : str = hidden_dropout_prob A : Tuple = attention_probs_dropout_prob A : Any = type_sequence_label_size A : Optional[int] = initializer_range A : Dict = scope A : Tuple = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) A : List[Any] = (image_size // patch_size) ** 2 A : Tuple = num_patches + 2 def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A : Tuple = None if self.use_labels: A : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Tuple = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" return DeiTConfig( 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=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : Any = TFDeiTModel(config=SCREAMING_SNAKE_CASE ) A : str = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" A : Tuple = TFDeiTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE ) A : List[Any] = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A : Optional[int] = 1 A : str = TFDeiTForMaskedImageModeling(SCREAMING_SNAKE_CASE ) A : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Tuple = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" A : str = self.type_sequence_label_size A : Optional[Any] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE ) A : Optional[Any] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images A : Optional[Any] = 1 A : List[str] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE ) A : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Optional[int] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Optional[int] = self.prepare_config_and_inputs() A, A, A : Tuple = config_and_inputs A : Any = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class A ( __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) __magic_name__ = ( { '''feature-extraction''': TFDeiTModel, '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) __magic_name__ = False __magic_name__ = False __magic_name__ = False __magic_name__ = False def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = TFDeiTModelTester(self ) A : Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''DeiT does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" pass def __lowerCAmelCase ( self ) -> str: """simple docstring""" A, A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) A : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE , tf.keras.layers.Dense ) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A, A : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) A : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A : Union[str, Any] = [*signature.parameters.keys()] A : List[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ) -> Tuple: """simple docstring""" A : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def __lowerCAmelCase ( self ) -> str: """simple docstring""" for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A : List[str] = TFDeiTModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_ ( ): '''simple docstring''' A : str = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class A ( unittest.TestCase ): @cached_property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) if is_vision_available() else None ) @slow def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Union[str, Any] = TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) A : Dict = self.default_image_processor A : List[str] = prepare_img() A : Any = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='''tf''' ) # forward pass A : Optional[int] = model(**SCREAMING_SNAKE_CASE ) # verify the logits A : List[Any] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE ) A : str = tf.constant([-1.0_266, 0.1_912, -1.2_861] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
1
'''simple docstring''' lowercase : int = '\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' lowercase : Union[str, Any] = [{'type': 'code', 'content': INSTALL_CONTENT}] lowercase : Optional[int] = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
311
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase : List[str] = { 'configuration_cpmant': ['CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CpmAntConfig'], 'tokenization_cpmant': ['CpmAntTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[Any] = [ 'CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST', 'CpmAntForCausalLM', 'CpmAntModel', 'CpmAntPreTrainedModel', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys lowercase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
311
1
'''simple docstring''' import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, 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 ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE="last" , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , ) -> Tuple: """simple docstring""" A : Union[str, Any] = parent A : Tuple = batch_size A : Any = seq_length A : str = is_training A : Any = use_input_lengths A : Optional[Any] = use_token_type_ids A : str = use_labels A : Optional[Any] = gelu_activation A : Dict = sinusoidal_embeddings A : Any = causal A : List[str] = asm A : Union[str, Any] = n_langs A : int = vocab_size A : str = n_special A : Dict = hidden_size A : Optional[Any] = num_hidden_layers A : int = num_attention_heads A : Any = hidden_dropout_prob A : str = attention_probs_dropout_prob A : int = max_position_embeddings A : List[str] = type_vocab_size A : Optional[int] = type_sequence_label_size A : Any = initializer_range A : Optional[Any] = num_labels A : Dict = num_choices A : Optional[int] = summary_type A : Tuple = use_proj A : int = scope def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) A : Any = None if self.use_input_lengths: A : List[str] = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length A : int = None if self.use_token_type_ids: A : str = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) A : str = None A : int = None A : Optional[Any] = None if self.use_labels: A : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A : str = ids_tensor([self.batch_size] , 2 ).float() A : str = ids_tensor([self.batch_size] , self.num_choices ) A : List[Any] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" return FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" A : List[Any] = FlaubertModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Optional[Any] = model(SCREAMING_SNAKE_CASE , lengths=SCREAMING_SNAKE_CASE , langs=SCREAMING_SNAKE_CASE ) A : Dict = model(SCREAMING_SNAKE_CASE , langs=SCREAMING_SNAKE_CASE ) A : Optional[Any] = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> Dict: """simple docstring""" A : Optional[Any] = FlaubertWithLMHeadModel(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : str = model(SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" A : int = FlaubertForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Any = model(SCREAMING_SNAKE_CASE ) A : List[Any] = model(SCREAMING_SNAKE_CASE , start_positions=SCREAMING_SNAKE_CASE , end_positions=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" A : int = FlaubertForQuestionAnswering(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[Any] = model(SCREAMING_SNAKE_CASE ) A : int = model( SCREAMING_SNAKE_CASE , start_positions=SCREAMING_SNAKE_CASE , end_positions=SCREAMING_SNAKE_CASE , cls_index=SCREAMING_SNAKE_CASE , is_impossible=SCREAMING_SNAKE_CASE , p_mask=SCREAMING_SNAKE_CASE , ) A : Any = model( SCREAMING_SNAKE_CASE , start_positions=SCREAMING_SNAKE_CASE , end_positions=SCREAMING_SNAKE_CASE , cls_index=SCREAMING_SNAKE_CASE , is_impossible=SCREAMING_SNAKE_CASE , ) ((A), ) : str = result_with_labels.to_tuple() A : int = model(SCREAMING_SNAKE_CASE , start_positions=SCREAMING_SNAKE_CASE , end_positions=SCREAMING_SNAKE_CASE ) ((A), ) : Dict = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" A : Tuple = FlaubertForSequenceClassification(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : int = model(SCREAMING_SNAKE_CASE ) A : Tuple = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> Dict: """simple docstring""" A : Tuple = self.num_labels A : Dict = FlaubertForTokenClassification(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[str] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> int: """simple docstring""" A : Optional[Any] = self.num_choices A : Dict = FlaubertForMultipleChoice(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : Dict = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : Optional[Any] = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Optional[int] = self.prepare_config_and_inputs() ( ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ) : Optional[Any] = config_and_inputs A : Dict = { '''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''lengths''': input_lengths, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class A ( __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) __magic_name__ = ( { '''feature-extraction''': FlaubertModel, '''fill-mask''': FlaubertWithLMHeadModel, '''question-answering''': FlaubertForQuestionAnsweringSimple, '''text-classification''': FlaubertForSequenceClassification, '''token-classification''': FlaubertForTokenClassification, '''zero-shot''': FlaubertForSequenceClassification, } if is_torch_available() else {} ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('''Fast''' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ) -> Tuple: """simple docstring""" A : List[str] = super()._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": A : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE ) A : str = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE ) return inputs_dict def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : List[Any] = FlaubertModelTester(self ) A : str = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , emb_dim=37 ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*SCREAMING_SNAKE_CASE ) @slow def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A : str = FlaubertModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) @slow @require_torch_gpu def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A, A : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return A : Tuple = True A : List[Any] = model_class(config=SCREAMING_SNAKE_CASE ) A : Dict = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Optional[int] = torch.jit.trace( SCREAMING_SNAKE_CASE , (inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(SCREAMING_SNAKE_CASE , os.path.join(SCREAMING_SNAKE_CASE , '''traced_model.pt''' ) ) A : int = torch.jit.load(os.path.join(SCREAMING_SNAKE_CASE , '''traced_model.pt''' ) , map_location=SCREAMING_SNAKE_CASE ) loaded(inputs_dict['''input_ids'''].to(SCREAMING_SNAKE_CASE ) , inputs_dict['''attention_mask'''].to(SCREAMING_SNAKE_CASE ) ) @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Optional[int] = FlaubertModel.from_pretrained('''flaubert/flaubert_base_cased''' ) A : Optional[Any] = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) with torch.no_grad(): A : List[str] = model(SCREAMING_SNAKE_CASE )[0] A : Any = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : str = torch.tensor( [[[-2.6_251, -1.4_298, -0.0_227], [-2.8_510, -1.6_387, 0.2_258], [-2.8_114, -1.1_832, -0.3_066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
'''simple docstring''' from __future__ import annotations lowercase : Union[str, Any] = list[tuple[int, int]] lowercase : Optional[Any] = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] lowercase : Any = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" A : int = pos_x A : Optional[Any] = pos_y A : Optional[Any] = (pos_y, pos_x) A : str = goal_x A : Optional[int] = goal_y A : List[Any] = g_cost A : str = parent A : str = self.calculate_heuristic() def __lowerCAmelCase ( self ) -> float: """simple docstring""" A : Optional[int] = abs(self.pos_x - self.goal_x ) A : Optional[Any] = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self , SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" return self.f_cost < other.f_cost class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , SCREAMING_SNAKE_CASE ) A : Tuple = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , SCREAMING_SNAKE_CASE ) A : Optional[Any] = [self.start] A : list[Node] = [] A : Tuple = False def __lowerCAmelCase ( self ) -> Path | None: """simple docstring""" while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() A : Optional[int] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: A : Optional[int] = True return self.retrace_path(SCREAMING_SNAKE_CASE ) self.closed_nodes.append(SCREAMING_SNAKE_CASE ) A : Any = self.get_successors(SCREAMING_SNAKE_CASE ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(SCREAMING_SNAKE_CASE ) else: # retrieve the best current path A : str = self.open_nodes.pop(self.open_nodes.index(SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(SCREAMING_SNAKE_CASE ) else: self.open_nodes.append(SCREAMING_SNAKE_CASE ) if not self.reached: return [self.start.pos] return None def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> list[Node]: """simple docstring""" A : List[Any] = [] for action in delta: A : List[str] = parent.pos_x + action[1] A : Dict = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , SCREAMING_SNAKE_CASE , ) ) return successors def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Path: """simple docstring""" A : int = node A : Union[str, Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) A : int = current_node.parent path.reverse() return path if __name__ == "__main__": lowercase : Tuple = (0, 0) lowercase : List[str] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print('------') lowercase : int = GreedyBestFirst(init, goal) lowercase : Union[str, Any] = greedy_bf.search() if path: for pos_x, pos_y in path: lowercase : Dict = 2 for elem in grid: print(elem)
311
1
'''simple docstring''' import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class A ( __snake_case ): def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : List[Any] = tempfile.mkdtemp() A : Dict = 8 # DPR tok A : Any = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] A : Optional[Any] = os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE ) A : List[Any] = os.path.join(SCREAMING_SNAKE_CASE , DPR_VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) # BART tok A : Optional[Any] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] A : Optional[Any] = dict(zip(SCREAMING_SNAKE_CASE , range(len(SCREAMING_SNAKE_CASE ) ) ) ) A : Optional[int] = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] A : Any = {'''unk_token''': '''<unk>'''} A : List[str] = os.path.join(self.tmpdirname , '''bart_tokenizer''' ) os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE ) A : Tuple = os.path.join(SCREAMING_SNAKE_CASE , BART_VOCAB_FILES_NAMES['''vocab_file'''] ) A : List[str] = os.path.join(SCREAMING_SNAKE_CASE , BART_VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE ) ) def __lowerCAmelCase ( self ) -> DPRQuestionEncoderTokenizer: """simple docstring""" return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) ) def __lowerCAmelCase ( self ) -> DPRContextEncoderTokenizer: """simple docstring""" return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) ) def __lowerCAmelCase ( self ) -> BartTokenizer: """simple docstring""" return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''bart_tokenizer''' ) ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Optional[Any] = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''text''': ['''foo''', '''bar'''], '''title''': ['''Foo''', '''Bar'''], '''embeddings''': [np.ones(self.retrieval_vector_size ), 2 * np.ones(self.retrieval_vector_size )], } ) dataset.add_faiss_index('''embeddings''' , string_factory='''Flat''' , metric_type=faiss.METRIC_INNER_PRODUCT ) return dataset def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : List[str] = self.get_dummy_dataset() A : int = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , ) with patch('''transformers.models.rag.retrieval_rag.load_dataset''' ) as mock_load_dataset: A : Dict = dataset A : Optional[Any] = RagRetriever( SCREAMING_SNAKE_CASE , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" A : List[str] = self.get_dummy_dataset() A : Tuple = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='''custom''' , ) if from_disk: A : Dict = os.path.join(self.tmpdirname , '''dataset''' ) A : List[Any] = os.path.join(self.tmpdirname , '''index.faiss''' ) dataset.get_index('''embeddings''' ).save(os.path.join(self.tmpdirname , '''index.faiss''' ) ) dataset.drop_index('''embeddings''' ) dataset.save_to_disk(os.path.join(self.tmpdirname , '''dataset''' ) ) del dataset A : Any = RagRetriever( SCREAMING_SNAKE_CASE , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: A : Tuple = RagRetriever( SCREAMING_SNAKE_CASE , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , SCREAMING_SNAKE_CASE ) , ) return retriever def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : List[Any] = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''text''': ['''foo''', '''bar'''], '''title''': ['''Foo''', '''Bar'''], '''embeddings''': [np.ones(self.retrieval_vector_size + 1 ), 2 * np.ones(self.retrieval_vector_size + 1 )], } ) dataset.add_faiss_index('''embeddings''' , string_factory='''Flat''' , metric_type=faiss.METRIC_INNER_PRODUCT ) A : str = os.path.join(self.tmpdirname , '''hf_bert_base.hnswSQ8_correct_phi_128.c_index''' ) dataset.save_faiss_index('''embeddings''' , index_file_name + '''.index.dpr''' ) pickle.dump(dataset['''id'''] , open(index_file_name + '''.index_meta.dpr''' , '''wb''' ) ) A : Optional[Any] = os.path.join(self.tmpdirname , '''psgs_w100.tsv.pkl''' ) A : Dict = {sample['''id''']: [sample['''text'''], sample['''title''']] for sample in dataset} pickle.dump(SCREAMING_SNAKE_CASE , open(SCREAMING_SNAKE_CASE , '''wb''' ) ) A : str = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='''legacy''' , index_path=self.tmpdirname , ) A : Tuple = RagRetriever( SCREAMING_SNAKE_CASE , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() ) return retriever def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = 1 A : Dict = self.get_dummy_canonical_hf_index_retriever() A : Union[str, Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) A, A, A : List[Any] = retriever.retrieve(SCREAMING_SNAKE_CASE , n_docs=SCREAMING_SNAKE_CASE ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , SCREAMING_SNAKE_CASE ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : str = self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch('''transformers.models.rag.retrieval_rag.load_dataset''' ) as mock_load_dataset: A : List[str] = self.get_dummy_dataset() retriever.save_pretrained(SCREAMING_SNAKE_CASE ) A : List[str] = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Optional[Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) A : int = retriever.retrieve(SCREAMING_SNAKE_CASE , n_docs=1 ) self.assertTrue(out is not None ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : str = 1 A : int = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE ) A : Union[str, Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) A, A, A : List[Any] = retriever.retrieve(SCREAMING_SNAKE_CASE , n_docs=SCREAMING_SNAKE_CASE ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , SCREAMING_SNAKE_CASE ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Optional[int] = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE ) A : Union[str, Any] = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Optional[Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) A : Union[str, Any] = retriever.retrieve(SCREAMING_SNAKE_CASE , n_docs=1 ) self.assertTrue(out is not None ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : int = 1 A : Dict = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE ) A : Union[str, Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) A, A, A : Any = retriever.retrieve(SCREAMING_SNAKE_CASE , n_docs=SCREAMING_SNAKE_CASE ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , SCREAMING_SNAKE_CASE ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : List[str] = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE ) A : Any = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Union[str, Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) A : Any = retriever.retrieve(SCREAMING_SNAKE_CASE , n_docs=1 ) self.assertTrue(out is not None ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : int = 1 A : Dict = self.get_dummy_legacy_index_retriever() A : Any = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) A, A, A : Tuple = retriever.retrieve(SCREAMING_SNAKE_CASE , n_docs=SCREAMING_SNAKE_CASE ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''text'''] ) , SCREAMING_SNAKE_CASE ) self.assertEqual(doc_dicts[0]['''text'''][0] , '''bar''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''text'''][0] , '''foo''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Union[str, Any] = self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE ) A : Union[str, Any] = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : List[str] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) A : str = retriever.retrieve(SCREAMING_SNAKE_CASE , n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def __lowerCAmelCase ( self ) -> Any: """simple docstring""" import torch A : Any = 1 A : Dict = self.get_dummy_canonical_hf_index_retriever() A : Tuple = [[5, 7], [10, 11]] A : Optional[Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) A : Tuple = retriever(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE ) A, A, A : Union[str, Any] = ( out['''context_input_ids'''], out['''context_attention_mask'''], out['''retrieved_doc_embeds'''], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , np.ndarray ) A : Optional[Any] = retriever( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE , return_tensors='''pt''' , ) A, A, A, A : int = ( # noqa: F841 out['''context_input_ids'''], out['''context_attention_mask'''], out['''retrieved_doc_embeds'''], out['''doc_ids'''], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(SCREAMING_SNAKE_CASE , torch.Tensor ) self.assertIsInstance(SCREAMING_SNAKE_CASE , torch.Tensor ) self.assertIsInstance(SCREAMING_SNAKE_CASE , torch.Tensor ) @require_torch @require_tokenizers @require_sentencepiece def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Optional[int] = self.get_dpr_ctx_encoder_tokenizer() A : Union[str, Any] = 1 A : Tuple = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE ) retriever.set_ctx_encoder_tokenizer(SCREAMING_SNAKE_CASE ) A : Tuple = [[5, 7], [10, 11]] A : Any = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) A : Union[str, Any] = retriever(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE ) self.assertEqual( len(SCREAMING_SNAKE_CASE ) , 6 ) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ('''tokenized_doc_ids''', '''tokenized_doc_attention_mask''') ) , SCREAMING_SNAKE_CASE ) # check for doc token related keys in dictionary.
311
'''simple docstring''' import argparse import os from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_task_guides.py lowercase : Any = 'src/transformers' lowercase : str = 'docs/source/en/tasks' def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' with open(snake_case__ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: A : Union[str, Any] = f.readlines() # Find the start prompt. A : List[Any] = 0 while not lines[start_index].startswith(snake_case__ ): start_index += 1 start_index += 1 A : List[str] = start_index while not lines[end_index].startswith(snake_case__ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. lowercase : int = direct_transformers_import(TRANSFORMERS_PATH) lowercase : str = { 'asr.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, 'audio_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, 'language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, 'image_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, 'masked_language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, 'multiple_choice.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, 'object_detection.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, 'question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, 'semantic_segmentation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, 'sequence_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, 'summarization.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'token_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, 'translation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'video_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, 'document_question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, 'monocular_depth_estimation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). lowercase : Optional[int] = { 'summarization.md': ('nllb',), 'translation.md': ('nllb',), } def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : int = TASK_GUIDE_TO_MODELS[task_guide] A : List[str] = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(snake_case__ , set() ) A : Union[str, Any] = { code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([F'[{name}](../model_doc/{code})' for code, name in model_names.items()] ) + "\n" def lowerCAmelCase_ ( snake_case__ , snake_case__=False ): '''simple docstring''' A, A, A, A : Optional[int] = _find_text_in_file( filename=os.path.join(snake_case__ , snake_case__ ) , start_prompt='''<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->''' , end_prompt='''<!--End of the generated tip-->''' , ) A : Optional[int] = get_model_list_for_task(snake_case__ ) if current_list != new_list: if overwrite: with open(os.path.join(snake_case__ , snake_case__ ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:] ) else: raise ValueError( F'The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`' ''' to fix this.''' ) if __name__ == "__main__": lowercase : Dict = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') lowercase : List[Any] = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
311
1
'''simple docstring''' from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def lowerCAmelCase_ ( snake_case__ = True , *snake_case__ , **snake_case__ ): '''simple docstring''' if not is_tqdm_available(): raise ImportError('''Accelerate\'s `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.''' ) A : List[Any] = False if main_process_only: A : str = PartialState().local_process_index == 0 return _tqdm(*snake_case__ , **snake_case__ , disable=snake_case__ )
311
'''simple docstring''' def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if len(snake_case__ ) <= 1: return [tuple(snake_case__ )] A : Tuple = [] def generate(snake_case__ , snake_case__ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , snake_case__ ) for i in range(k - 1 ): if k % 2 == 0: # k is even A, A : Optional[Any] = arr[k - 1], arr[i] else: # k is odd A, A : Optional[Any] = arr[k - 1], arr[0] generate(k - 1 , snake_case__ ) generate(len(snake_case__ ) , snake_case__ ) return res if __name__ == "__main__": lowercase : List[str] = input('Enter numbers separated by a comma:\n').strip() lowercase : int = [int(item) for item in user_input.split(',')] print(heaps(arr))
311
1
'''simple docstring''' from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder # @@protoc_insertion_point(imports) lowercase : Any = _symbol_database.Default() lowercase : int = _descriptor_pool.Default().AddSerializedFile( B'\n\x19sentencepiece_model.proto\x12\rsentencepiece"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03' ) lowercase : Optional[int] = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sentencepiece_model_pb2', _globals) if _descriptor._USE_C_DESCRIPTORS is False: lowercase : List[Any] = None lowercase : Tuple = B'H\003' # (generated by protobuf compiler, but `_TRAINERSPEC` is not defined) # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001" # _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001" lowercase : List[str] = 45 lowercase : List[Any] = 15_81 lowercase : List[str] = 15_17 lowercase : List[Any] = 15_70 lowercase : Optional[int] = 15_84 lowercase : Any = 17_93 lowercase : Any = 17_95 lowercase : Tuple = 19_16 lowercase : Any = 18_64 lowercase : List[Any] = 19_05 lowercase : str = 19_19 lowercase : Any = 24_29 lowercase : Optional[int] = 22_08 lowercase : Dict = 24_18 lowercase : Tuple = 23_23 lowercase : Tuple = 24_07 # @@protoc_insertion_point(module_scope)
311
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class A ( __snake_case ): __magic_name__ = (UniPCMultistepScheduler,) __magic_name__ = (('''num_inference_steps''', 25),) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" A : str = { '''num_train_timesteps''': 1000, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''solver_order''': 2, '''solver_type''': '''bh2''', } config.update(**SCREAMING_SNAKE_CASE ) return config def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=0 , **SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : List[Any] = dict(self.forward_default_kwargs ) A : Union[str, Any] = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE ) A : Optional[Any] = self.dummy_sample A : int = 0.1 * sample A : Union[str, Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A : Optional[Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals A : List[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE ) A : List[Any] = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE ) new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals A : Dict = dummy_past_residuals[: new_scheduler.config.solver_order] A, A : Tuple = sample, sample for t in range(SCREAMING_SNAKE_CASE , time_step + scheduler.config.solver_order + 1 ): A : Any = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample A : Optional[Any] = new_scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=0 , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : Optional[Any] = dict(self.forward_default_kwargs ) A : Tuple = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE ) A : List[Any] = self.dummy_sample A : int = 0.1 * sample A : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A : Optional[int] = self.get_scheduler_config() A : Any = scheduler_class(**SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals (must be after setting timesteps) A : int = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE ) A : int = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residual (must be after setting timesteps) A : Optional[Any] = dummy_past_residuals[: new_scheduler.config.solver_order] A : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample A : List[Any] = new_scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" if scheduler is None: A : Dict = self.scheduler_classes[0] A : Union[str, Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : List[Any] = scheduler_class(**SCREAMING_SNAKE_CASE ) A : Tuple = self.scheduler_classes[0] A : Union[str, Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE ) A : int = 10 A : Tuple = self.dummy_model() A : Any = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): A : int = model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Optional[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample return sample def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Tuple = dict(self.forward_default_kwargs ) A : List[Any] = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE ) for scheduler_class in self.scheduler_classes: A : Dict = self.get_scheduler_config() A : Dict = scheduler_class(**SCREAMING_SNAKE_CASE ) A : Optional[Any] = self.dummy_sample A : Optional[int] = 0.1 * sample if num_inference_steps is not None and hasattr(SCREAMING_SNAKE_CASE , '''set_timesteps''' ): scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) elif num_inference_steps is not None and not hasattr(SCREAMING_SNAKE_CASE , '''set_timesteps''' ): A : Tuple = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) A : Dict = [residual + 0.2, residual + 0.15, residual + 0.10] A : List[str] = dummy_past_residuals[: scheduler.config.solver_order] A : List[Any] = scheduler.timesteps[5] A : Dict = scheduler.timesteps[6] A : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample A : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Union[str, Any] = UniPCMultistepScheduler(**self.get_scheduler_config() ) A : List[Any] = self.full_loop(scheduler=SCREAMING_SNAKE_CASE ) A : List[str] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.2_464 ) < 1e-3 A : Dict = DPMSolverSinglestepScheduler.from_config(scheduler.config ) A : Optional[int] = DEISMultistepScheduler.from_config(scheduler.config ) A : List[Any] = DPMSolverMultistepScheduler.from_config(scheduler.config ) A : List[Any] = UniPCMultistepScheduler.from_config(scheduler.config ) A : Optional[Any] = self.full_loop(scheduler=SCREAMING_SNAKE_CASE ) A : Optional[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.2_464 ) < 1e-3 def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE ) 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=SCREAMING_SNAKE_CASE , prediction_type=SCREAMING_SNAKE_CASE , sample_max_value=SCREAMING_SNAKE_CASE , solver_order=SCREAMING_SNAKE_CASE , solver_type=SCREAMING_SNAKE_CASE , ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" for solver_type in ["bh1", "bh2"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=SCREAMING_SNAKE_CASE , solver_type=SCREAMING_SNAKE_CASE , prediction_type=SCREAMING_SNAKE_CASE , ) A : Dict = self.full_loop( solver_order=SCREAMING_SNAKE_CASE , solver_type=SCREAMING_SNAKE_CASE , prediction_type=SCREAMING_SNAKE_CASE , ) assert not torch.isnan(SCREAMING_SNAKE_CASE ).any(), "Samples have nan numbers" def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE ) self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=SCREAMING_SNAKE_CASE , time_step=0 ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : int = self.full_loop() A : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.2_464 ) < 1e-3 def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : List[Any] = self.full_loop(prediction_type='''v_prediction''' ) A : Any = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.1_014 ) < 1e-3 def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Dict = self.scheduler_classes[0] A : List[Any] = self.get_scheduler_config(thresholding=SCREAMING_SNAKE_CASE , dynamic_thresholding_ratio=0 ) A : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE ) A : Tuple = 10 A : Union[str, Any] = self.dummy_model() A : Dict = self.dummy_sample_deter.half() scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): A : Dict = model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Optional[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample assert sample.dtype == torch.floataa def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" for scheduler_class in self.scheduler_classes: A : Dict = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : Tuple = scheduler_class(**SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(scheduler.config.num_train_timesteps ) assert len(scheduler.timesteps.unique() ) == scheduler.num_inference_steps
311
1
'''simple docstring''' lowercase : Union[str, Any] = 0 # The first color of the flag. lowercase : Union[str, Any] = 1 # The second color of the flag. lowercase : Optional[int] = 2 # The third color of the flag. lowercase : Tuple = (red, white, blue) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if not sequence: return [] if len(snake_case__ ) == 1: return list(snake_case__ ) A : Dict = 0 A : Optional[int] = len(snake_case__ ) - 1 A : Tuple = 0 while mid <= high: if sequence[mid] == colors[0]: A, A : List[Any] = sequence[mid], sequence[low] low += 1 mid += 1 elif sequence[mid] == colors[1]: mid += 1 elif sequence[mid] == colors[2]: A, A : int = sequence[high], sequence[mid] high -= 1 else: A : Optional[Any] = F'The elements inside the sequence must contains only {colors} values' raise ValueError(snake_case__ ) return sequence if __name__ == "__main__": import doctest doctest.testmod() lowercase : List[str] = input('Enter numbers separated by commas:\n').strip() lowercase : Dict = [int(item.strip()) for item in user_input.split(',')] print(f'''{dutch_national_flag_sort(unsorted)}''')
311
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM A : Dict = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 0.0 , SCREAMING_SNAKE_CASE = 50 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = "pil" , SCREAMING_SNAKE_CASE = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" if isinstance(self.unet.config.sample_size , SCREAMING_SNAKE_CASE ): A : List[Any] = ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size, ) else: A : Optional[int] = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size) if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and len(SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( F'You have passed a list of generators of length {len(SCREAMING_SNAKE_CASE )}, but requested an effective batch' F' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) A : str = randn_tensor(SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output A : Any = self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 A : int = self.scheduler.step( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , eta=SCREAMING_SNAKE_CASE , use_clipped_model_output=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE ).prev_sample A : Dict = (image / 2 + 0.5).clamp(0 , 1 ) A : Optional[int] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": A : int = self.numpy_to_pil(SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE )
311
1
'''simple docstring''' from __future__ import annotations def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A, A : Optional[int] = set(snake_case__ ), [start] while stack: A : Any = stack.pop() explored.add(snake_case__ ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(snake_case__ ) return explored lowercase : Optional[Any] = { 'A': ['B', 'C', 'D'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B', 'D'], 'E': ['B', 'F'], 'F': ['C', 'E', 'G'], 'G': ['F'], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, 'A'))
311
'''simple docstring''' from __future__ import annotations from random import random class A : def __init__( self , SCREAMING_SNAKE_CASE = None ) -> Tuple: """simple docstring""" A : Optional[Any] = value A : Any = random() A : Node | None = None A : Node | None = None def __repr__( self ) -> str: """simple docstring""" from pprint import pformat if self.left is None and self.right is None: return F'\'{self.value}: {self.prior:.5}\'' else: return pformat( {F'{self.value}: {self.prior:.5}': (self.left, self.right)} , indent=1 ) def __str__( self ) -> str: """simple docstring""" A : Optional[Any] = str(self.value ) + ''' ''' A : Union[str, Any] = str(self.left or '''''' ) A : Any = str(self.right or '''''' ) return value + left + right def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: A, A : Any = split(root.left , snake_case__ ) return left, root else: A, A : Optional[int] = split(root.right , snake_case__ ) return root, right def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: A : List[str] = merge(left.right , snake_case__ ) return left else: A : Tuple = merge(snake_case__ , right.left ) return right def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : List[Any] = Node(snake_case__ ) A, A : Tuple = split(snake_case__ , snake_case__ ) return merge(merge(snake_case__ , snake_case__ ) , snake_case__ ) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A, A : Dict = split(snake_case__ , value - 1 ) A, A : Any = split(snake_case__ , snake_case__ ) return merge(snake_case__ , snake_case__ ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if not root: # None return else: inorder(root.left ) print(root.value , end=''',''' ) inorder(root.right ) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' for arg in args.split(): if arg[0] == "+": A : int = insert(snake_case__ , int(arg[1:] ) ) elif arg[0] == "-": A : int = erase(snake_case__ , int(arg[1:] ) ) else: print('''Unknown command''' ) return root def lowerCAmelCase_ ( ): '''simple docstring''' A : Union[str, Any] = None print( '''enter numbers to create a tree, + value to add value into treap, ''' '''- value to erase all nodes with value. \'q\' to quit. ''' ) A : Optional[int] = input() while args != "q": A : str = interact_treap(snake_case__ , snake_case__ ) print(snake_case__ ) A : Union[str, Any] = input() print('''good by!''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
311
1
'''simple docstring''' import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCriteria, MaxNewTokensCriteria, MaxTimeCriteria, StoppingCriteriaList, validate_stopping_criteria, ) @require_torch class A ( unittest.TestCase ): def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : Optional[Any] = 3 A : List[Any] = 250 A : Tuple = ids_tensor((batch_size, length) , SCREAMING_SNAKE_CASE ) A : Tuple = torch.ones((batch_size, length) , device=SCREAMING_SNAKE_CASE , dtype=torch.float ) / length return input_ids, scores def __lowerCAmelCase ( self ) -> str: """simple docstring""" A, A : Any = self._get_tensors(5 ) A : Optional[Any] = StoppingCriteriaList( [ MaxLengthCriteria(max_length=10 ), MaxTimeCriteria(max_time=0.1 ), ] ) self.assertFalse(criteria(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) A, A : Optional[int] = self._get_tensors(9 ) self.assertFalse(criteria(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) A, A : List[Any] = self._get_tensors(10 ) self.assertTrue(criteria(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : str = MaxLengthCriteria(max_length=10 ) A, A : int = self._get_tensors(5 ) self.assertFalse(criteria(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) A, A : List[Any] = self._get_tensors(9 ) self.assertFalse(criteria(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) A, A : Any = self._get_tensors(10 ) self.assertTrue(criteria(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : int = MaxNewTokensCriteria(start_length=5 , max_new_tokens=5 ) A, A : List[str] = self._get_tensors(5 ) self.assertFalse(criteria(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) A, A : Any = self._get_tensors(9 ) self.assertFalse(criteria(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) A, A : int = self._get_tensors(10 ) self.assertTrue(criteria(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) A : Optional[Any] = StoppingCriteriaList([criteria] ) self.assertEqual(criteria_list.max_length , 10 ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A, A : Union[str, Any] = self._get_tensors(5 ) A : List[Any] = MaxTimeCriteria(max_time=0.1 ) self.assertFalse(criteria(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) A : str = MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2 ) self.assertTrue(criteria(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 10 ) with self.assertWarns(SCREAMING_SNAKE_CASE ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 11 ) A : int = validate_stopping_criteria(StoppingCriteriaList() , 11 ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , 1 )
311
'''simple docstring''' import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=sys.maxsize ) -> Union[str, Any]: """simple docstring""" A : Tuple = '''bilinear''' A : Optional[int] = max_size A : Dict = short_edge_length def __call__( self , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : Tuple = [] for img in imgs: A, A : str = img.shape[:2] # later: provide list and randomly choose index for resize A : Union[str, Any] = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img A : int = size * 1.0 / min(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if h < w: A, A : Tuple = size, scale * w else: A, A : str = scale * h, size if max(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) > self.max_size: A : List[str] = self.max_size * 1.0 / max(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Tuple = newh * scale A : int = neww * scale A : List[str] = int(neww + 0.5 ) A : int = int(newh + 0.5 ) if img.dtype == np.uinta: A : Dict = Image.fromarray(SCREAMING_SNAKE_CASE ) A : Optional[Any] = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) A : str = np.asarray(SCREAMING_SNAKE_CASE ) else: A : Dict = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw A : List[Any] = nn.functional.interpolate( SCREAMING_SNAKE_CASE , (newh, neww) , mode=self.interp_method , align_corners=SCREAMING_SNAKE_CASE ).squeeze(0 ) img_augs.append(SCREAMING_SNAKE_CASE ) return img_augs class A : def __init__( self , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" A : Any = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) A : str = cfg.INPUT.FORMAT A : int = cfg.SIZE_DIVISIBILITY A : Optional[int] = cfg.PAD_VALUE A : Dict = cfg.INPUT.MAX_SIZE_TEST A : Optional[Any] = cfg.MODEL.DEVICE A : Dict = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) A : Tuple = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) A : str = lambda SCREAMING_SNAKE_CASE : (x - self.pixel_mean) / self.pixel_std def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" A : Union[str, Any] = tuple(max(SCREAMING_SNAKE_CASE ) for s in zip(*[img.shape for img in images] ) ) A : List[str] = [im.shape[-2:] for im in images] A : Optional[Any] = [ nn.functional.pad( SCREAMING_SNAKE_CASE , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ] return torch.stack(SCREAMING_SNAKE_CASE ), torch.tensor(SCREAMING_SNAKE_CASE ) def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ) -> Union[str, Any]: """simple docstring""" with torch.no_grad(): if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : str = [images] if single_image: assert len(SCREAMING_SNAKE_CASE ) == 1 for i in range(len(SCREAMING_SNAKE_CASE ) ): if isinstance(images[i] , torch.Tensor ): images.insert(SCREAMING_SNAKE_CASE , images.pop(SCREAMING_SNAKE_CASE ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( SCREAMING_SNAKE_CASE , torch.as_tensor(img_tensorize(images.pop(SCREAMING_SNAKE_CASE ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge A : Tuple = torch.tensor([im.shape[:2] for im in images] ) A : Dict = self.aug(SCREAMING_SNAKE_CASE ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic A : Tuple = [self.normalizer(SCREAMING_SNAKE_CASE ) for x in images] # now pad them to do the following operations A, A : Optional[int] = self.pad(SCREAMING_SNAKE_CASE ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad A : Tuple = torch.true_divide(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' assert torch.isfinite(snake_case__ ).all(), "Box tensor contains infinite or NaN!" A, A : str = box_size tensor[:, 0].clamp_(min=0 , max=snake_case__ ) tensor[:, 1].clamp_(min=0 , max=snake_case__ ) tensor[:, 2].clamp_(min=0 , max=snake_case__ ) tensor[:, 3].clamp_(min=0 , max=snake_case__ )
311
1
'''simple docstring''' import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=None , ) -> Union[str, Any]: """simple docstring""" A : List[str] = parent A : Optional[Any] = batch_size A : Optional[Any] = seq_length A : List[Any] = is_training A : Optional[Any] = use_input_mask A : Dict = use_token_type_ids A : List[str] = use_labels A : List[Any] = vocab_size A : Optional[Any] = hidden_size A : int = embedding_size A : Union[str, Any] = num_hidden_layers A : Tuple = num_attention_heads A : Optional[int] = intermediate_size A : Union[str, Any] = hidden_act A : List[Any] = hidden_dropout_prob A : Dict = attention_probs_dropout_prob A : str = max_position_embeddings A : str = type_vocab_size A : Dict = type_sequence_label_size A : str = initializer_range A : Optional[int] = num_labels A : Tuple = num_choices A : str = scope def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : int = None if self.use_input_mask: A : str = random_attention_mask([self.batch_size, self.seq_length] ) A : Optional[Any] = None if self.use_token_type_ids: A : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A : Dict = None A : int = None A : Optional[Any] = None if self.use_labels: A : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A : Optional[int] = ids_tensor([self.batch_size] , self.num_choices ) A : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" return MegatronBertConfig( 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 , embedding_size=self.embedding_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" A : List[Any] = MegatronBertModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE ) A : Optional[int] = model(SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE ) A : Union[str, Any] = model(SCREAMING_SNAKE_CASE ) 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 __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" A : Union[str, Any] = MegatronBertForMaskedLM(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : int = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" A : str = MegatronBertForCausalLM(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Optional[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" A : Tuple = MegatronBertForNextSentencePrediction(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" A : Optional[Any] = MegatronBertForPreTraining(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[str] = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE , next_sentence_label=SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" A : Any = MegatronBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[Any] = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , start_positions=SCREAMING_SNAKE_CASE , end_positions=SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" A : Optional[int] = self.num_labels A : List[Any] = MegatronBertForSequenceClassification(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Tuple = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" A : Dict = self.num_labels A : Union[str, Any] = MegatronBertForTokenClassification(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : int = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" A : List[Any] = self.num_choices A : Optional[int] = MegatronBertForMultipleChoice(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : Tuple = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : Tuple = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : str = self.prepare_config_and_inputs() ( ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ) : str = config_and_inputs A : Any = {'''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 ): __magic_name__ = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) __magic_name__ = ( { '''feature-extraction''': MegatronBertModel, '''fill-mask''': MegatronBertForMaskedLM, '''question-answering''': MegatronBertForQuestionAnswering, '''text-classification''': MegatronBertForSequenceClassification, '''text-generation''': MegatronBertForCausalLM, '''token-classification''': MegatronBertForTokenClassification, '''zero-shot''': MegatronBertForSequenceClassification, } if is_torch_available() else {} ) __magic_name__ = True # test_resize_embeddings = False __magic_name__ = False def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ) -> Optional[int]: """simple docstring""" A : str = super()._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE ): A : List[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=SCREAMING_SNAKE_CASE ) A : int = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE ) return inputs_dict def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : int = MegatronBertModelTester(self ) A : List[str] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*SCREAMING_SNAKE_CASE ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' return torch.tensor( snake_case__ , dtype=torch.long , device=snake_case__ , ) lowercase : Optional[Any] = 1e-4 @require_torch @require_sentencepiece @require_tokenizers class A ( unittest.TestCase ): @slow @unittest.skip('''Model is not available.''' ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Tuple = '''nvidia/megatron-bert-uncased-345m''' if "MYDIR" in os.environ: A : List[Any] = os.path.join(os.environ['''MYDIR'''] , SCREAMING_SNAKE_CASE ) A : Optional[Any] = MegatronBertModel.from_pretrained(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.half() A : Tuple = _long_tensor([[101, 7110, 1005, 1056, 2023, 11333, 17413, 1029, 102]] ) with torch.no_grad(): A : List[str] = model(SCREAMING_SNAKE_CASE )[0] A : List[Any] = torch.Size((1, 9, 1024) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : Any = [-0.6_040, -0.2_517, -0.1_025, 0.3_420, -0.6_758, -0.0_017, -0.1_089, -0.1_990, 0.5_728] for ii in range(3 ): for jj in range(3 ): A : Union[str, Any] = output[0, ii, jj] A : str = expected[3 * ii + jj] A : List[str] = '''ii={} jj={} a={} b={}'''.format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertTrue(math.isclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , rel_tol=SCREAMING_SNAKE_CASE , abs_tol=SCREAMING_SNAKE_CASE ) , msg=SCREAMING_SNAKE_CASE )
311
'''simple docstring''' import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": lowercase : Tuple = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml parser.add_argument( '--original_config_file', default=None, type=str, 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( '--scheduler_type', default='pndm', type=str, help='Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']', ) parser.add_argument( '--pipeline_type', default=None, type=str, help=( 'The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\'' '. If `None` pipeline will be automatically inferred.' ), ) parser.add_argument( '--image_size', default=None, 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( '--prediction_type', default=None, type=str, help=( 'The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable' ' Diffusion v2 Base. Use \'v_prediction\' 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.)') parser.add_argument( '--stable_unclip', type=str, default=None, required=False, help='Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.', ) parser.add_argument( '--stable_unclip_prior', type=str, default=None, required=False, help='Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.', ) parser.add_argument( '--clip_stats_path', type=str, help='Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.', required=False, ) parser.add_argument( '--controlnet', action='store_true', default=None, help='Set flag if this is a controlnet checkpoint.' ) parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--vae_path', type=str, default=None, required=False, help='Set to a path, hub id to an already converted vae to not convert it again.', ) lowercase : Tuple = parser.parse_args() lowercase : Union[str, Any] = download_from_original_stable_diffusion_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, prediction_type=args.prediction_type, model_type=args.pipeline_type, extract_ema=args.extract_ema, scheduler_type=args.scheduler_type, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, stable_unclip=args.stable_unclip, stable_unclip_prior=args.stable_unclip_prior, clip_stats_path=args.clip_stats_path, controlnet=args.controlnet, vae_path=args.vae_path, ) if args.half: pipe.to(torch_dtype=torch.floataa) if args.controlnet: # only save the controlnet model pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) else: pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
311
1
'''simple docstring''' import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class A ( __snake_case ): def __init__( self , *SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) A : Optional[int] = eval_examples A : int = post_process_function def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE = "eval" ) -> Any: """simple docstring""" A : Any = self.eval_dataset if eval_dataset is None else eval_dataset A : Union[str, Any] = self.get_eval_dataloader(SCREAMING_SNAKE_CASE ) A : Optional[int] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. A : Optional[int] = self.compute_metrics A : Union[str, Any] = None A : Any = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop A : Optional[int] = time.time() try: A : Tuple = eval_loop( SCREAMING_SNAKE_CASE , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=SCREAMING_SNAKE_CASE , metric_key_prefix=SCREAMING_SNAKE_CASE , ) finally: A : List[Any] = compute_metrics A : Union[str, Any] = self.args.eval_batch_size * self.args.world_size if F'{metric_key_prefix}_jit_compilation_time' in output.metrics: start_time += output.metrics[F'{metric_key_prefix}_jit_compilation_time'] output.metrics.update( speed_metrics( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default A : Optional[Any] = self.post_process_function(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , output.predictions ) A : Any = self.compute_metrics(SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'{metric_key_prefix}_' ): A : Optional[Any] = metrics.pop(SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) else: A : str = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(SCREAMING_SNAKE_CASE ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) A : str = self.callback_handler.on_evaluate(self.args , self.state , self.control , SCREAMING_SNAKE_CASE ) return metrics def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE = "test" ) -> Union[str, Any]: """simple docstring""" A : Optional[int] = self.get_test_dataloader(SCREAMING_SNAKE_CASE ) # Temporarily disable metric computation, we will do it in the loop here. A : Union[str, Any] = self.compute_metrics A : Union[str, Any] = None A : Any = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop A : int = time.time() try: A : int = eval_loop( SCREAMING_SNAKE_CASE , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=SCREAMING_SNAKE_CASE , metric_key_prefix=SCREAMING_SNAKE_CASE , ) finally: A : int = compute_metrics A : List[Any] = self.args.eval_batch_size * self.args.world_size if F'{metric_key_prefix}_jit_compilation_time' in output.metrics: start_time += output.metrics[F'{metric_key_prefix}_jit_compilation_time'] output.metrics.update( speed_metrics( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output A : Optional[int] = self.post_process_function(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , output.predictions , '''predict''' ) A : int = self.compute_metrics(SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'{metric_key_prefix}_' ): A : Tuple = metrics.pop(SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=SCREAMING_SNAKE_CASE )
311
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal lowercase : str = datasets.utils.logging.get_logger(__name__) lowercase : Union[str, Any] = ['names', 'prefix'] lowercase : Union[str, Any] = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] lowercase : List[Any] = ['encoding_errors', 'on_bad_lines'] lowercase : Any = ['date_format'] @dataclass class A ( datasets.BuilderConfig ): __magic_name__ = "," __magic_name__ = None __magic_name__ = "infer" __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = False __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = True __magic_name__ = False __magic_name__ = True __magic_name__ = None __magic_name__ = "." __magic_name__ = None __magic_name__ = '"' __magic_name__ = 0 __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = True __magic_name__ = 0 __magic_name__ = True __magic_name__ = False __magic_name__ = None __magic_name__ = 10000 __magic_name__ = None __magic_name__ = "strict" __magic_name__ = "error" __magic_name__ = None def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" if self.delimiter is not None: A : Optional[Any] = self.delimiter if self.column_names is not None: A : Optional[Any] = self.column_names @property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : str = { '''sep''': self.sep, '''header''': self.header, '''names''': self.names, '''index_col''': self.index_col, '''usecols''': self.usecols, '''prefix''': self.prefix, '''mangle_dupe_cols''': self.mangle_dupe_cols, '''engine''': self.engine, '''converters''': self.converters, '''true_values''': self.true_values, '''false_values''': self.false_values, '''skipinitialspace''': self.skipinitialspace, '''skiprows''': self.skiprows, '''nrows''': self.nrows, '''na_values''': self.na_values, '''keep_default_na''': self.keep_default_na, '''na_filter''': self.na_filter, '''verbose''': self.verbose, '''skip_blank_lines''': self.skip_blank_lines, '''thousands''': self.thousands, '''decimal''': self.decimal, '''lineterminator''': self.lineterminator, '''quotechar''': self.quotechar, '''quoting''': self.quoting, '''escapechar''': self.escapechar, '''comment''': self.comment, '''encoding''': self.encoding, '''dialect''': self.dialect, '''error_bad_lines''': self.error_bad_lines, '''warn_bad_lines''': self.warn_bad_lines, '''skipfooter''': self.skipfooter, '''doublequote''': self.doublequote, '''memory_map''': self.memory_map, '''float_precision''': self.float_precision, '''chunksize''': self.chunksize, '''encoding_errors''': self.encoding_errors, '''on_bad_lines''': self.on_bad_lines, '''date_format''': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , SCREAMING_SNAKE_CASE ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class A ( datasets.ArrowBasedBuilder ): __magic_name__ = CsvConfig def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) A : int = dl_manager.download_and_extract(self.config.data_files ) if isinstance(SCREAMING_SNAKE_CASE , (str, list, tuple) ): A : str = data_files if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : int = [files] A : Optional[int] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] A : Tuple = [] for split_name, files in data_files.items(): if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : List[str] = [files] A : List[str] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE ) for file in files] splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE , gen_kwargs={'''files''': files} ) ) return splits def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> pa.Table: """simple docstring""" if self.config.features is not None: A : Optional[int] = self.config.features.arrow_schema if all(not require_storage_cast(SCREAMING_SNAKE_CASE ) for feature in self.config.features.values() ): # cheaper cast A : List[Any] = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=SCREAMING_SNAKE_CASE ) else: # more expensive cast; allows str <-> int/float or str to Audio for example A : int = table_cast(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return pa_table def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" A : Union[str, Any] = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str A : int = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(SCREAMING_SNAKE_CASE ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE ) ): A : Union[str, Any] = pd.read_csv(SCREAMING_SNAKE_CASE , iterator=SCREAMING_SNAKE_CASE , dtype=SCREAMING_SNAKE_CASE , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(SCREAMING_SNAKE_CASE ): A : Dict = pa.Table.from_pandas(SCREAMING_SNAKE_CASE ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE ) except ValueError as e: logger.error(F'Failed to read file \'{file}\' with error {type(SCREAMING_SNAKE_CASE )}: {e}' ) raise
311
1
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class A ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Dict = tempfile.mkdtemp() # fmt: off A : List[Any] = ['''''', '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>'''] # fmt: on A : Any = dict(zip(SCREAMING_SNAKE_CASE , range(len(SCREAMING_SNAKE_CASE ) ) ) ) A : Dict = ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''', ''''''] A : Dict = {'''unk_token''': '''<unk>'''} A : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) A : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE ) ) A : Any = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.48_145_466, 0.4_578_275, 0.40_821_073], '''image_std''': [0.26_862_954, 0.26_130_258, 0.27_577_711], } A : List[Any] = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='''!''' , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='''!''' , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : List[str] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] A : List[Any] = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Optional[int] = self.get_tokenizer() A : Union[str, Any] = self.get_rust_tokenizer() A : Optional[int] = self.get_image_processor() A : Optional[Any] = OwlViTProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) A : Optional[Any] = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE ) A : Tuple = OwlViTProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) A : Any = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : int = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : int = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) A : Tuple = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE ) A : str = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=SCREAMING_SNAKE_CASE ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Tuple = self.get_image_processor() A : List[str] = self.get_tokenizer() A : Union[str, Any] = OwlViTProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE ) A : Dict = self.prepare_image_inputs() A : Optional[Any] = image_processor(SCREAMING_SNAKE_CASE , return_tensors='''np''' ) A : Optional[int] = processor(images=SCREAMING_SNAKE_CASE , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Union[str, Any] = self.get_image_processor() A : Tuple = self.get_tokenizer() A : List[Any] = OwlViTProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE ) A : Tuple = '''lower newer''' A : List[Any] = processor(text=SCREAMING_SNAKE_CASE , return_tensors='''np''' ) A : int = tokenizer(SCREAMING_SNAKE_CASE , return_tensors='''np''' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : int = self.get_image_processor() A : List[str] = self.get_tokenizer() A : Optional[int] = OwlViTProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE ) A : int = '''lower newer''' A : Optional[int] = self.prepare_image_inputs() A : Union[str, Any] = processor(text=SCREAMING_SNAKE_CASE , images=SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE ): processor() def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Tuple = '''google/owlvit-base-patch32''' A : Optional[int] = OwlViTProcessor.from_pretrained(SCREAMING_SNAKE_CASE ) A : List[str] = ['''cat''', '''nasa badge'''] A : int = processor(text=SCREAMING_SNAKE_CASE ) A : List[Any] = 16 self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask'''] ) self.assertEqual(inputs['''input_ids'''].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE ): processor() def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Any = '''google/owlvit-base-patch32''' A : str = OwlViTProcessor.from_pretrained(SCREAMING_SNAKE_CASE ) A : Optional[int] = [['''cat''', '''nasa badge'''], ['''person''']] A : Any = processor(text=SCREAMING_SNAKE_CASE ) A : Optional[Any] = 16 A : Dict = len(SCREAMING_SNAKE_CASE ) A : List[str] = max([len(SCREAMING_SNAKE_CASE ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask'''] ) self.assertEqual(inputs['''input_ids'''].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE ): processor() def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : int = '''google/owlvit-base-patch32''' A : Optional[Any] = OwlViTProcessor.from_pretrained(SCREAMING_SNAKE_CASE ) A : Optional[Any] = ['''cat''', '''nasa badge'''] A : str = processor(text=SCREAMING_SNAKE_CASE ) A : Optional[int] = 16 A : str = inputs['''input_ids'''] A : Optional[int] = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask'''] ) self.assertEqual(inputs['''input_ids'''].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Optional[int] = self.get_image_processor() A : int = self.get_tokenizer() A : Union[str, Any] = OwlViTProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE ) A : Any = self.prepare_image_inputs() A : Tuple = self.prepare_image_inputs() A : Tuple = processor(images=SCREAMING_SNAKE_CASE , query_images=SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ['''query_pixel_values''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE ): processor() def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = self.get_image_processor() A : Optional[Any] = self.get_tokenizer() A : str = OwlViTProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE ) A : List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] A : Union[str, Any] = processor.batch_decode(SCREAMING_SNAKE_CASE ) A : Union[str, Any] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
311
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : int = logging.get_logger(__name__) lowercase : int = { 'asapp/sew-tiny-100k': 'https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json', # See all SEW models at https://huggingface.co/models?filter=sew } class A ( __snake_case ): __magic_name__ = '''sew''' def __init__( self , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-5 , SCREAMING_SNAKE_CASE="group" , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , SCREAMING_SNAKE_CASE=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=0.05 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE="mean" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=256 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=2 , **SCREAMING_SNAKE_CASE , ) -> Tuple: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE , pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE ) A : Optional[Any] = hidden_size A : Any = feat_extract_norm A : Optional[int] = feat_extract_activation A : Tuple = list(SCREAMING_SNAKE_CASE ) A : List[str] = list(SCREAMING_SNAKE_CASE ) A : List[str] = list(SCREAMING_SNAKE_CASE ) A : int = conv_bias A : List[Any] = num_conv_pos_embeddings A : Tuple = num_conv_pos_embedding_groups A : int = len(self.conv_dim ) A : Dict = num_hidden_layers A : Optional[int] = intermediate_size A : Any = squeeze_factor A : int = hidden_act A : str = num_attention_heads A : Dict = hidden_dropout A : Optional[Any] = attention_dropout A : List[str] = activation_dropout A : Union[str, Any] = feat_proj_dropout A : Union[str, Any] = final_dropout A : int = layerdrop A : Optional[Any] = layer_norm_eps A : Any = initializer_range A : Tuple = vocab_size 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)`,''' F'but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)' F'= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 A : Optional[Any] = apply_spec_augment A : Optional[Any] = mask_time_prob A : Union[str, Any] = mask_time_length A : Optional[Any] = mask_time_min_masks A : str = mask_feature_prob A : Tuple = mask_feature_length A : Any = mask_feature_min_masks # ctc loss A : List[Any] = ctc_loss_reduction A : Dict = ctc_zero_infinity # sequence classification A : int = use_weighted_layer_sum A : Optional[int] = classifier_proj_size @property def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
311
1
'''simple docstring''' import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def lowerCAmelCase_ ( snake_case__ = 3 ): '''simple docstring''' if isinstance(snake_case__ , snake_case__ ): raise TypeError('''number of qubits must be a integer.''' ) if number_of_qubits <= 0: raise ValueError('''number of qubits must be > 0.''' ) if math.floor(snake_case__ ) != number_of_qubits: raise ValueError('''number of qubits must be exact integer.''' ) if number_of_qubits > 10: raise ValueError('''number of qubits too large to simulate(>10).''' ) A : Optional[int] = QuantumRegister(snake_case__ , '''qr''' ) A : Optional[Any] = ClassicalRegister(snake_case__ , '''cr''' ) A : List[str] = QuantumCircuit(snake_case__ , snake_case__ ) A : Optional[int] = number_of_qubits for i in range(snake_case__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(snake_case__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , snake_case__ , snake_case__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(snake_case__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(snake_case__ , snake_case__ ) # simulate with 10000 shots A : List[str] = Aer.get_backend('''qasm_simulator''' ) A : Tuple = execute(snake_case__ , snake_case__ , shots=1_0000 ) return job.result().get_counts(snake_case__ ) if __name__ == "__main__": print( f'''Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}''' )
311
'''simple docstring''' import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Dict = SwinConfig() A : List[Any] = swin_name.split('''_''' ) A : Tuple = name_split[1] A : Union[str, Any] = int(name_split[4] ) A : str = int(name_split[3][-1] ) if model_size == "tiny": A : Optional[int] = 96 A : Optional[Any] = (2, 2, 6, 2) A : Any = (3, 6, 12, 24) elif model_size == "small": A : Optional[int] = 96 A : str = (2, 2, 18, 2) A : Tuple = (3, 6, 12, 24) elif model_size == "base": A : int = 128 A : Optional[Any] = (2, 2, 18, 2) A : List[str] = (4, 8, 16, 32) else: A : Dict = 192 A : Optional[Any] = (2, 2, 18, 2) A : Optional[Any] = (6, 12, 24, 48) if "in22k" in swin_name: A : Dict = 2_1841 else: A : str = 1000 A : List[str] = '''huggingface/label-files''' A : Any = '''imagenet-1k-id2label.json''' A : Any = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='''dataset''' ) , '''r''' ) ) A : str = {int(snake_case__ ): v for k, v in idalabel.items()} A : Tuple = idalabel A : Tuple = {v: k for k, v in idalabel.items()} A : Tuple = img_size A : Dict = num_classes A : Optional[Any] = embed_dim A : str = depths A : str = num_heads A : Optional[int] = window_size return config def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if "patch_embed.proj" in name: A : Any = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: A : Tuple = name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: A : Optional[int] = '''encoder.''' + name if "attn.proj" in name: A : List[str] = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: A : List[str] = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: A : Any = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: A : Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: A : Dict = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: A : str = name.replace('''mlp.fc2''' , '''output.dense''' ) if name == "norm.weight": A : Tuple = '''layernorm.weight''' if name == "norm.bias": A : Tuple = '''layernorm.bias''' if "head" in name: A : Any = name.replace('''head''' , '''classifier''' ) else: A : List[Any] = '''swin.''' + name return name def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' for key in orig_state_dict.copy().keys(): A : Dict = orig_state_dict.pop(snake_case__ ) if "mask" in key: continue elif "qkv" in key: A : Dict = key.split('''.''' ) A : Optional[int] = int(key_split[1] ) A : List[str] = int(key_split[3] ) A : Optional[int] = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: A : Any = val[:dim, :] A : Dict = val[ dim : dim * 2, : ] A : List[str] = val[-dim:, :] else: A : Any = val[ :dim ] A : Optional[int] = val[ dim : dim * 2 ] A : Any = val[ -dim: ] else: A : str = val return orig_state_dict def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : Tuple = timm.create_model(snake_case__ , pretrained=snake_case__ ) timm_model.eval() A : Optional[Any] = get_swin_config(snake_case__ ) A : Optional[int] = SwinForImageClassification(snake_case__ ) model.eval() A : List[str] = convert_state_dict(timm_model.state_dict() , snake_case__ ) model.load_state_dict(snake_case__ ) A : Optional[int] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' A : Any = AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swin_name.replace('''_''' , '''-''' ) ) ) A : List[Any] = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) A : List[Any] = image_processor(images=snake_case__ , return_tensors='''pt''' ) A : Any = timm_model(inputs['''pixel_values'''] ) A : Optional[Any] = model(**snake_case__ ).logits assert torch.allclose(snake_case__ , snake_case__ , atol=1E-3 ) print(F'Saving model {swin_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case__ ) if __name__ == "__main__": lowercase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swin_name', default='swin_tiny_patch4_window7_224', type=str, help='Name of the Swin timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) lowercase : int = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
311
1
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase : List[str] = { 'configuration_cpmant': ['CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CpmAntConfig'], 'tokenization_cpmant': ['CpmAntTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[Any] = [ 'CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST', 'CpmAntForCausalLM', 'CpmAntModel', 'CpmAntPreTrainedModel', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys lowercase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
311
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : Optional[int] = logging.get_logger(__name__) lowercase : Tuple = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class A ( __snake_case ): __magic_name__ = '''pix2struct_text_model''' __magic_name__ = ['''past_key_values'''] __magic_name__ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , SCREAMING_SNAKE_CASE=50244 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Optional[Any]: """simple docstring""" A : str = vocab_size A : List[str] = hidden_size A : List[Any] = d_kv A : Optional[Any] = d_ff A : Dict = num_layers A : Dict = num_heads A : Optional[int] = relative_attention_num_buckets A : Optional[Any] = relative_attention_max_distance A : Dict = dropout_rate A : Dict = layer_norm_epsilon A : Tuple = initializer_factor A : Union[str, Any] = use_cache A : int = eos_token_id A : List[str] = decoder_start_token_id # for backwards compatibility A : int = dense_act_fn super().__init__( pad_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , decoder_start_token_id=SCREAMING_SNAKE_CASE , tie_word_embeddings=SCREAMING_SNAKE_CASE , is_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) A, A : Optional[Any] = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": A : Union[str, Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A ( __snake_case ): __magic_name__ = '''pix2struct_vision_model''' def __init__( self , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=1e-10 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=4096 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=128 , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) A : List[str] = hidden_size A : Optional[Any] = patch_embed_hidden_size A : Union[str, Any] = d_ff A : Dict = dropout_rate A : str = num_hidden_layers A : Dict = num_attention_heads A : Tuple = initializer_range A : List[str] = initializer_factor A : Union[str, Any] = attention_dropout A : Tuple = layer_norm_eps A : int = dense_act_fn A : Optional[int] = seq_len A : Tuple = relative_attention_num_buckets A : str = relative_attention_max_distance A : Optional[Any] = d_kv @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) A, A : int = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": A : Optional[Any] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A ( __snake_case ): __magic_name__ = '''pix2struct''' __magic_name__ = True def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(tie_word_embeddings=SCREAMING_SNAKE_CASE , is_encoder_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) if text_config is None: A : Dict = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: A : str = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) A : Dict = PixaStructTextConfig(**SCREAMING_SNAKE_CASE ) A : Any = PixaStructVisionConfig(**SCREAMING_SNAKE_CASE ) A : Any = self.text_config.decoder_start_token_id A : Any = self.text_config.pad_token_id A : Dict = self.text_config.eos_token_id A : Union[str, Any] = initializer_factor A : Tuple = initializer_range A : Optional[Any] = self.initializer_range A : int = self.initializer_range A : Tuple = is_vqa @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Tuple = copy.deepcopy(self.__dict__ ) A : Dict = self.text_config.to_dict() A : int = self.vision_config.to_dict() A : Any = self.__class__.model_type return output
311
1
'''simple docstring''' import math def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : str = [True] * n A : Union[str, Any] = False A : Optional[Any] = False A : List[str] = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): A : Dict = i * 2 while index < n: A : int = False A : int = index + i A : Union[str, Any] = [2] for i in range(3 , snake_case__ , 2 ): if is_prime[i]: primes.append(snake_case__ ) return primes def lowerCAmelCase_ ( snake_case__ = 9999_6666_3333 ): '''simple docstring''' A : Any = math.floor(math.sqrt(snake_case__ ) ) + 100 A : List[Any] = prime_sieve(snake_case__ ) A : Optional[int] = 0 A : Any = 0 A : str = primes[prime_index] while (last_prime**2) <= limit: A : Any = primes[prime_index + 1] A : Any = last_prime**2 A : Dict = next_prime**2 # Get numbers divisible by lps(current) A : str = 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) A : Dict = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps A : Tuple = 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 A : List[str] = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
311
'''simple docstring''' from __future__ import annotations def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : List[str] = 2 A : Dict = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(snake_case__ ) if n > 1: factors.append(snake_case__ ) return factors if __name__ == "__main__": import doctest doctest.testmod()
311
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowercase : Dict = logging.get_logger(__name__) lowercase : Tuple = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class A ( __snake_case , __snake_case ): __magic_name__ = '''convnextv2''' def __init__( self , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-12 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=224 , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE , ) -> Optional[int]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) A : Union[str, Any] = num_channels A : List[str] = patch_size A : str = num_stages A : Optional[Any] = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes A : Dict = [3, 3, 9, 3] if depths is None else depths A : Union[str, Any] = hidden_act A : List[Any] = initializer_range A : Optional[int] = layer_norm_eps A : List[Any] = drop_path_rate A : List[Any] = image_size A : Any = ['''stem'''] + [F'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] A, A : Optional[Any] = get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE , out_indices=SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
311
'''simple docstring''' # Function to print upper half of diamond (pyramid) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for i in range(0 , snake_case__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(''' ''' , end='''''' ) for _ in range(0 , i + 1 ): # printing stars print('''* ''' , end='''''' ) print() def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for i in range(snake_case__ , 0 , -1 ): for _ in range(snake_case__ , 0 , -1 ): # printing stars print('''* ''' , end='''''' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(''' ''' , end='''''' ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if n <= 0: print(''' ... .... nothing printing :(''' ) return floyd(snake_case__ ) # upper half reverse_floyd(snake_case__ ) # lower half if __name__ == "__main__": print(R'| /\ | |- | |- |--| |\ /| |-') print(R'|/ \| |- |_ |_ |__| | \/ | |_') lowercase : List[str] = 1 while K: lowercase : List[Any] = int(input('enter the number and , and see the magic : ')) print() pretty_print(user_number) lowercase : Any = int(input('press 0 to exit... and 1 to continue...')) print('Good Bye...')
311
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 lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer A : str = flax_key_tuple[:-1] + ('''weight''',) A : Any = torch.permute(snake_case__ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(snake_case__ ): # linear layer A : Optional[Any] = flax_key_tuple[:-1] + ('''weight''',) A : Optional[Any] = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: A : Union[str, Any] = flax_key_tuple[:-1] + ('''weight''',) return flax_key_tuple, flax_tensor def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' if "metadata" in layer: A : List[str] = layer.split('''metadata''' ) A : Union[str, Any] = ''''''.join(split_layer[0] )[:-1] A : Dict = [tuple(('''metadata''' + split_layer[1]).split('''/''' ) )] elif "kvstore" in layer: A : Tuple = layer.split('''kvstore''' ) A : List[Any] = ''''''.join(split_layer[0] )[:-1] A : str = [tuple(('''kvstore''' + split_layer[1]).split('''/''' ) )] else: A : str = layer.split('''/''' ) A : Tuple = '''/'''.join(split_layer[:-1] ) A : str = (split_layer[-1],) if "kvstore/path" in layer: A : Any = F'{switch_checkpoint_path}/{checkpoint_info[layer]}' elif "kvstore/driver" in layer: A : Tuple = '''file''' else: A : Dict = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : Optional[int] = rename_keys(snake_case__ ) A : Optional[Any] = {} for k, v in current_block.items(): A : Dict = v A : Tuple = new_current_block torch.save(snake_case__ , snake_case__ ) def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ = WEIGHTS_NAME ): '''simple docstring''' A : Optional[Any] = convert_file_size_to_int(snake_case__ ) A : List[Any] = [] A : List[Any] = {} A : Dict = 0 A : Tuple = 0 os.makedirs(snake_case__ , exist_ok=snake_case__ ) with gfile.GFile(switch_checkpoint_path + '''/checkpoint''' , '''rb''' ) as fp: A : str = serialization.msgpack_restore(fp.read() )['''optimizer''']['''target'''] A : int = flatten_dict(snake_case__ , sep='''/''' ) A : Optional[Any] = {} for layer in checkpoint_info.keys(): A, A, A : Dict = get_key_and_tensorstore_dict( snake_case__ , snake_case__ , snake_case__ ) if curr_real_layer_name in all_layers: A : Tuple = content else: A : int = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file A : List[Any] = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() A : Dict = torch.tensor(snake_case__ ) A : List[Any] = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts A, A : Union[str, Any] = rename_base_flax_keys(tuple(key.split('''/''' ) ) , snake_case__ ) A : Any = '''/'''.join(snake_case__ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: A : List[Any] = os.path.join( snake_case__ , weights_name.replace('''.bin''' , F'-{len(snake_case__ )+1:05d}-of-???.bin' ) ) rename_and_save_block(snake_case__ , snake_case__ ) sharded_state_dicts.append(current_block.keys() ) del current_block A : Dict = {} A : Optional[int] = 0 A : str = raw_weights.to(getattr(snake_case__ , snake_case__ ) ) current_block_size += weight_size total_size += weight_size # Add the last block A : Optional[Any] = os.path.join(snake_case__ , weights_name.replace('''.bin''' , F'-{len(snake_case__ )+1:05d}-of-???.bin' ) ) rename_and_save_block(snake_case__ , snake_case__ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(snake_case__ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index A : int = {} A : str = {} for idx, shard in enumerate(snake_case__ ): A : Optional[int] = weights_name.replace( '''.bin''' , F'-{idx+1:05d}-of-{len(snake_case__ ):05d}.bin' ) # len(sharded_state_dicts):05d} A : Optional[Any] = os.path.join(snake_case__ , weights_name.replace('''.bin''' , F'-{idx+1:05d}-of-???.bin' ) ) os.rename(snake_case__ , os.path.join(snake_case__ , snake_case__ ) ) A : Optional[Any] = shard for key in shard: A : Optional[int] = shard_file # Add the metadata A : Optional[Any] = {'''total_size''': total_size} A : Dict = {'''metadata''': metadata, '''weight_map''': weight_map} with open(os.path.join(snake_case__ , snake_case__ ) , '''w''' , encoding='''utf-8''' ) as f: A : List[str] = json.dumps(snake_case__ , indent=2 , sort_keys=snake_case__ ) + '''\n''' f.write(snake_case__ ) return metadata, index if __name__ == "__main__": lowercase : str = 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.', ) lowercase : List[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 lowerCAmelCase_ ( ): '''simple docstring''' from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer A : Dict = SwitchTransformersConfig.from_pretrained('''google/switch-base-8''' ) config.save_pretrained('''/home/arthur_huggingface_co/transformers/switch_converted''' ) A : List[str] = SwitchTransformersForConditionalGeneration.from_pretrained( '''/home/arthur_huggingface_co/transformers/switch_converted''' , device_map='''auto''' ) A : Optional[int] = TaTokenizer.from_pretrained('''t5-small''' ) A : str = '''A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''' A : List[Any] = tokenizer(snake_case__ , return_tensors='''pt''' ).input_ids A : List[Any] = model.generate(snake_case__ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
311
'''simple docstring''' # limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 50 , SCREAMING_SNAKE_CASE = "pil" , SCREAMING_SNAKE_CASE = True , **SCREAMING_SNAKE_CASE , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" A : List[Any] = torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=SCREAMING_SNAKE_CASE , ) A : Optional[Any] = image.to(self.device ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output A : Tuple = self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 A : List[Any] = self.scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample A : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) A : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": A : List[Any] = self.numpy_to_pil(SCREAMING_SNAKE_CASE ) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE ), "This is a local test"
311
1
'''simple docstring''' import colorsys from PIL import Image # type: ignore def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : Optional[int] = x A : str = y for step in range(snake_case__ ): # noqa: B007 A : str = a * a - b * b + x A : List[str] = 2 * a * b + y A : str = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255 ) for i in colorsys.hsv_to_rgb(snake_case__ , 1 , 1 ) ) def lowerCAmelCase_ ( snake_case__ = 800 , snake_case__ = 600 , snake_case__ = -0.6 , snake_case__ = 0 , snake_case__ = 3.2 , snake_case__ = 50 , snake_case__ = True , ): '''simple docstring''' A : List[Any] = Image.new('''RGB''' , (image_width, image_height) ) A : Tuple = img.load() # loop through the image-coordinates for image_x in range(snake_case__ ): for image_y in range(snake_case__ ): # determine the figure-coordinates based on the image-coordinates A : Optional[int] = figure_width / image_width * image_height A : Tuple = figure_center_x + (image_x / image_width - 0.5) * figure_width A : List[str] = figure_center_y + (image_y / image_height - 0.5) * figure_height A : str = get_distance(snake_case__ , snake_case__ , snake_case__ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: A : str = get_color_coded_rgb(snake_case__ ) else: A : List[Any] = get_black_and_white_rgb(snake_case__ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure lowercase : Optional[Any] = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
311
'''simple docstring''' import unittest from transformers import BertGenerationConfig, 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 BertGenerationDecoder, BertGenerationEncoder class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=50 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=None , ) -> str: """simple docstring""" A : Any = parent A : List[Any] = batch_size A : Union[str, Any] = seq_length A : Any = is_training A : int = use_input_mask A : Union[str, Any] = vocab_size A : List[Any] = hidden_size A : List[Any] = num_hidden_layers A : Optional[int] = num_attention_heads A : str = intermediate_size A : Tuple = hidden_act A : Union[str, Any] = hidden_dropout_prob A : Union[str, Any] = attention_probs_dropout_prob A : int = max_position_embeddings A : Optional[int] = initializer_range A : Any = use_labels A : Optional[int] = scope def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Optional[int] = None if self.use_input_mask: A : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: A : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Dict = self.get_config() return config, input_ids, input_mask, token_labels def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" return BertGenerationConfig( 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 , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" ( ( A ), ( A ), ( A ), ( A ), ) : Any = self.prepare_config_and_inputs() A : Tuple = True A : int = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A : str = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" A : List[str] = BertGenerationEncoder(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) A : int = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> Union[str, Any]: """simple docstring""" A : List[str] = True A : Union[str, Any] = BertGenerationEncoder(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , ) A : List[Any] = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" A : Optional[Any] = True A : Tuple = True A : Optional[int] = BertGenerationDecoder(config=SCREAMING_SNAKE_CASE ).to(SCREAMING_SNAKE_CASE ).eval() # first forward pass A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , use_cache=SCREAMING_SNAKE_CASE , ) A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A : List[str] = ids_tensor((self.batch_size, 3) , config.vocab_size ) A : Tuple = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and A : Dict = torch.cat([input_ids, next_tokens] , dim=-1 ) A : List[str] = torch.cat([input_mask, next_mask] , dim=-1 ) A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE , )['''hidden_states'''][0] A : Any = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , past_key_values=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE , )['''hidden_states'''][0] # select random slice A : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() A : List[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() A : str = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" A : Optional[Any] = BertGenerationDecoder(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Optional[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A, A, A, A : Optional[int] = self.prepare_config_and_inputs() A : str = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class A ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () __magic_name__ = (BertGenerationDecoder,) if is_torch_available() else () __magic_name__ = ( {'''feature-extraction''': BertGenerationEncoder, '''text-generation''': BertGenerationDecoder} if is_torch_available() else {} ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : List[str] = BertGenerationEncoderTester(self ) A : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A, A, A, A : Tuple = self.model_tester.prepare_config_and_inputs() A : str = '''bert''' self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : int = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" ( ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ) : Tuple = self.model_tester.prepare_config_and_inputs_for_decoder() A : Union[str, Any] = None self.model_tester.create_and_check_model_as_decoder( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*SCREAMING_SNAKE_CASE ) @slow def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Optional[Any] = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) A : Optional[Any] = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]] ) with torch.no_grad(): A : Dict = model(SCREAMING_SNAKE_CASE )[0] A : Optional[Any] = torch.Size([1, 8, 1024] ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : Dict = torch.tensor( [[[0.1_775, 0.0_083, -0.0_321], [1.6_002, 0.1_287, 0.3_912], [2.1_473, 0.5_791, 0.6_066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[Any] = BertGenerationDecoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) A : Dict = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]] ) with torch.no_grad(): A : Optional[Any] = model(SCREAMING_SNAKE_CASE )[0] A : Optional[Any] = torch.Size([1, 8, 50358] ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : Any = torch.tensor( [[[-0.5_788, -2.5_994, -3.7_054], [0.0_438, 4.7_997, 1.8_795], [1.5_862, 6.6_409, 4.4_638]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
1
'''simple docstring''' import os import sys import unittest lowercase : List[str] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) lowercase : Any = os.path.join('tests', 'models', 'bert', 'test_modeling_bert.py') lowercase : int = os.path.join('tests', 'models', 'blip', 'test_modeling_blip.py') class A ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : List[str] = get_test_to_tester_mapping(SCREAMING_SNAKE_CASE ) A : Optional[Any] = get_test_to_tester_mapping(SCREAMING_SNAKE_CASE ) A : List[str] = {'''BertModelTest''': '''BertModelTester'''} A : List[Any] = { '''BlipModelTest''': '''BlipModelTester''', '''BlipTextImageModelTest''': '''BlipTextImageModelsModelTester''', '''BlipTextModelTest''': '''BlipTextModelTester''', '''BlipTextRetrievalModelTest''': '''BlipTextRetrievalModelTester''', '''BlipVQAModelTest''': '''BlipVQAModelTester''', '''BlipVisionModelTest''': '''BlipVisionModelTester''', } self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Optional[Any] = get_model_to_test_mapping(SCREAMING_SNAKE_CASE ) A : Dict = get_model_to_test_mapping(SCREAMING_SNAKE_CASE ) A : Any = { '''BertForMaskedLM''': ['''BertModelTest'''], '''BertForMultipleChoice''': ['''BertModelTest'''], '''BertForNextSentencePrediction''': ['''BertModelTest'''], '''BertForPreTraining''': ['''BertModelTest'''], '''BertForQuestionAnswering''': ['''BertModelTest'''], '''BertForSequenceClassification''': ['''BertModelTest'''], '''BertForTokenClassification''': ['''BertModelTest'''], '''BertLMHeadModel''': ['''BertModelTest'''], '''BertModel''': ['''BertModelTest'''], } A : Optional[Any] = { '''BlipForConditionalGeneration''': ['''BlipTextImageModelTest'''], '''BlipForImageTextRetrieval''': ['''BlipTextRetrievalModelTest'''], '''BlipForQuestionAnswering''': ['''BlipVQAModelTest'''], '''BlipModel''': ['''BlipModelTest'''], '''BlipTextModel''': ['''BlipTextModelTest'''], '''BlipVisionModel''': ['''BlipVisionModelTest'''], } self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : str = get_model_to_tester_mapping(SCREAMING_SNAKE_CASE ) A : Dict = get_model_to_tester_mapping(SCREAMING_SNAKE_CASE ) A : Optional[Any] = { '''BertForMaskedLM''': ['''BertModelTester'''], '''BertForMultipleChoice''': ['''BertModelTester'''], '''BertForNextSentencePrediction''': ['''BertModelTester'''], '''BertForPreTraining''': ['''BertModelTester'''], '''BertForQuestionAnswering''': ['''BertModelTester'''], '''BertForSequenceClassification''': ['''BertModelTester'''], '''BertForTokenClassification''': ['''BertModelTester'''], '''BertLMHeadModel''': ['''BertModelTester'''], '''BertModel''': ['''BertModelTester'''], } A : Any = { '''BlipForConditionalGeneration''': ['''BlipTextImageModelsModelTester'''], '''BlipForImageTextRetrieval''': ['''BlipTextRetrievalModelTester'''], '''BlipForQuestionAnswering''': ['''BlipVQAModelTester'''], '''BlipModel''': ['''BlipModelTester'''], '''BlipTextModel''': ['''BlipTextModelTester'''], '''BlipVisionModel''': ['''BlipVisionModelTester'''], } self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE )
311
'''simple docstring''' import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' return 1.0 / (1.0 + np.exp(-_outputs )) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Optional[int] = np.max(_outputs , axis=-1 , keepdims=snake_case__ ) A : Any = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=snake_case__ ) class A ( __snake_case ): __magic_name__ = '''sigmoid''' __magic_name__ = '''softmax''' __magic_name__ = '''none''' @add_end_docstrings( __snake_case , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class A ( __snake_case ): __magic_name__ = False __magic_name__ = ClassificationFunction.NONE def __init__( self , **SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE="" , **SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" A : Optional[Any] = tokenizer_kwargs A : int = {} if hasattr(self.model.config , '''return_all_scores''' ) and return_all_scores is None: A : int = self.model.config.return_all_scores if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) or top_k is None: A : Union[str, Any] = top_k A : Dict = False elif return_all_scores is not None: warnings.warn( '''`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of''' ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.''' , SCREAMING_SNAKE_CASE , ) if return_all_scores: A : Optional[int] = None else: A : Dict = 1 if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : Dict = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: A : int = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : str = super().__call__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. A : Any = '''top_k''' not in kwargs if isinstance(args[0] , SCREAMING_SNAKE_CASE ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Dict[str, GenericTensor]: """simple docstring""" A : List[Any] = self.framework if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): return self.tokenizer(**SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and len(SCREAMING_SNAKE_CASE ) == 1 and isinstance(inputs[0] , SCREAMING_SNAKE_CASE ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a''' ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.''' ) return self.tokenizer(SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" return self.model(**SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=True ) -> List[str]: """simple docstring""" if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: A : Optional[int] = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: A : Any = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , '''function_to_apply''' ) and function_to_apply is None: A : Optional[int] = self.model.config.function_to_apply else: A : Optional[int] = ClassificationFunction.NONE A : Any = model_outputs['''logits'''][0] A : List[Any] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: A : int = sigmoid(SCREAMING_SNAKE_CASE ) elif function_to_apply == ClassificationFunction.SOFTMAX: A : Any = softmax(SCREAMING_SNAKE_CASE ) elif function_to_apply == ClassificationFunction.NONE: A : int = outputs else: raise ValueError(F'Unrecognized `function_to_apply` argument: {function_to_apply}' ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} A : int = [ {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(SCREAMING_SNAKE_CASE ) ] if not _legacy: dict_scores.sort(key=lambda SCREAMING_SNAKE_CASE : x["score"] , reverse=SCREAMING_SNAKE_CASE ) if top_k is not None: A : Union[str, Any] = dict_scores[:top_k] return dict_scores
311
1
'''simple docstring''' import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowercase : Any = get_tests_dir('fixtures/spiece.model') @require_sentencepiece @require_tokenizers class A ( __snake_case , unittest.TestCase ): __magic_name__ = DebertaVaTokenizer __magic_name__ = DebertaVaTokenizerFast __magic_name__ = True __magic_name__ = True def __lowerCAmelCase ( self ) -> Any: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing A : str = DebertaVaTokenizer(SCREAMING_SNAKE_CASE , unk_token='''<unk>''' ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" A : Union[str, Any] = '''this is a test''' A : Tuple = '''this is a test''' return input_text, output_text def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Union[str, Any] = '''<pad>''' A : str = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<pad>''' ) self.assertEqual(vocab_keys[1] , '''<unk>''' ) self.assertEqual(vocab_keys[-1] , '''[PAD]''' ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , 30001 ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 30000 ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : int = ''' \tHeLLo!how \n Are yoU? ''' A : int = ['''▁hello''', '''!''', '''how''', '''▁are''', '''▁you''', '''?'''] # fmt: on A : Dict = DebertaVaTokenizer(SCREAMING_SNAKE_CASE , do_lower_case=SCREAMING_SNAKE_CASE ) A : Dict = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : List[str] = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE , do_lower_case=SCREAMING_SNAKE_CASE ) A : Tuple = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @unittest.skip('''There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.''' ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" pass @unittest.skip('''There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.''' ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" pass def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Dict = '''I was born in 92000, and this is falsé.''' A : Optional[int] = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ] # fmt: on A : Dict = DebertaVaTokenizer(SCREAMING_SNAKE_CASE , split_by_punct=SCREAMING_SNAKE_CASE ) A : Tuple = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Union[str, Any] = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE , split_by_punct=SCREAMING_SNAKE_CASE ) A : Tuple = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Tuple = '''I was born in 92000, and this is falsé.''' A : Optional[Any] = ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ] # fmt: on A : Dict = DebertaVaTokenizer(SCREAMING_SNAKE_CASE , do_lower_case=SCREAMING_SNAKE_CASE , split_by_punct=SCREAMING_SNAKE_CASE ) A : Dict = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Tuple = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE , do_lower_case=SCREAMING_SNAKE_CASE , split_by_punct=SCREAMING_SNAKE_CASE ) A : List[str] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : str = '''I was born in 92000, and this is falsé.''' A : int = ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''.''', ] # fmt: on A : List[Any] = DebertaVaTokenizer(SCREAMING_SNAKE_CASE , do_lower_case=SCREAMING_SNAKE_CASE , split_by_punct=SCREAMING_SNAKE_CASE ) A : Dict = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Any = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE , do_lower_case=SCREAMING_SNAKE_CASE , split_by_punct=SCREAMING_SNAKE_CASE ) A : Dict = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Tuple = '''I was born in 92000, and this is falsé.''' A : str = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ] # fmt: on A : Optional[int] = DebertaVaTokenizer(SCREAMING_SNAKE_CASE , do_lower_case=SCREAMING_SNAKE_CASE , split_by_punct=SCREAMING_SNAKE_CASE ) A : Dict = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : int = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE , do_lower_case=SCREAMING_SNAKE_CASE , split_by_punct=SCREAMING_SNAKE_CASE ) A : Dict = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Union[str, Any] = ''' \tHeLLo!how \n Are yoU? ''' A : Any = ['''▁''', '''<unk>''', '''e''', '''<unk>''', '''o''', '''!''', '''how''', '''▁''', '''<unk>''', '''re''', '''▁yo''', '''<unk>''', '''?'''] # fmt: on A : Tuple = DebertaVaTokenizer(SCREAMING_SNAKE_CASE , do_lower_case=SCREAMING_SNAKE_CASE , split_by_punct=SCREAMING_SNAKE_CASE ) A : Union[str, Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : List[str] = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE , do_lower_case=SCREAMING_SNAKE_CASE , split_by_punct=SCREAMING_SNAKE_CASE ) A : List[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Any = self.get_tokenizer() A : Tuple = self.get_rust_tokenizer() A : int = '''I was born in 92000, and this is falsé.''' A : Dict = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) ) A : Tuple = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Any = tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) A : str = rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : int = self.get_rust_tokenizer() A : Dict = tokenizer.encode(SCREAMING_SNAKE_CASE ) A : str = rust_tokenizer.encode(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[Any] = '''This is a test''' A : Any = [13, 1, 4398, 25, 21, 1289] A : Union[str, Any] = ['''▁''', '''T''', '''his''', '''▁is''', '''▁a''', '''▁test'''] A : Optional[Any] = ['''▁''', '''<unk>''', '''his''', '''▁is''', '''▁a''', '''▁test'''] A : Optional[int] = DebertaVaTokenizer(SCREAMING_SNAKE_CASE , keep_accents=SCREAMING_SNAKE_CASE ) A : Optional[int] = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE , keep_accents=SCREAMING_SNAKE_CASE ) A : Tuple = tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Optional[int] = tokenizer.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : str = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Optional[Any] = rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : List[Any] = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Tuple = rust_tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # fmt: off A : List[str] = '''I was born in 92000, and this is falsé.''' A : List[Any] = [13, 1, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 9] A : Dict = ['''▁''', '''I''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''é''', '''.''', ] A : Tuple = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''.''', ] # fmt: on A : Any = tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Any = tokenizer.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Tuple = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Union[str, Any] = rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Any = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : int = rust_tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : List[Any] = DebertaVaTokenizer(SCREAMING_SNAKE_CASE ) A : Dict = tokenizer.encode('''sequence builders''' ) A : Tuple = tokenizer.encode('''multi-sequence build''' ) A : Optional[int] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE ) A : str = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , SCREAMING_SNAKE_CASE ) self.assertEqual( [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , SCREAMING_SNAKE_CASE , ) @slow def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Any = {'''input_ids''': [[1, 39867, 36, 19390, 486, 27, 35052, 81436, 18, 60685, 1225, 7, 35052, 81436, 18, 9367, 16899, 18, 15937, 53, 594, 773, 18, 16287, 30465, 36, 15937, 6, 41139, 38, 36979, 60763, 191, 6, 34132, 99, 6, 50538, 390, 43230, 6, 34132, 2779, 20850, 14, 699, 1072, 1194, 36, 382, 10901, 53, 7, 699, 1072, 2084, 36, 20422, 630, 53, 19, 105, 3049, 1896, 1053, 16899, 1506, 11, 37978, 4243, 7, 1237, 31869, 200, 16566, 654, 6, 35052, 81436, 7, 55630, 13593, 4, 2], [1, 26, 15011, 13, 667, 8, 1053, 18, 23611, 1237, 72356, 12820, 34, 104134, 1209, 35, 13313, 6627, 21, 202, 347, 7, 164, 2399, 11, 46, 4485, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 5, 1232, 2864, 15785, 14951, 105, 5, 8581, 1250, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE , model_name='''microsoft/deberta-v2-xlarge''' , revision='''ad6e42c1532ddf3a15c39246b63f5559d558b670''' , )
311
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCAmelCase_ ( snake_case__ = "laptop" ): '''simple docstring''' A : Tuple = F'https://www.amazon.in/laptop/s?k={product}' A : Optional[int] = { '''User-Agent''': '''Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36''', '''Accept-Language''': '''en-US, en;q=0.5''', } A : Any = BeautifulSoup(requests.get(snake_case__ , headers=snake_case__ ).text ) # Initialize a Pandas dataframe with the column titles A : List[str] = DataFrame( columns=[ '''Product Title''', '''Product Link''', '''Current Price of the product''', '''Product Rating''', '''MRP of the product''', '''Discount''', ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( '''div''' , attrs={'''class''': '''s-result-item''', '''data-component-type''': '''s-search-result'''} , ) , soup.find_all('''div''' , attrs={'''class''': '''a-row a-size-base a-color-base'''} ) , ): try: A : Optional[Any] = item.ha.text A : Union[str, Any] = '''https://www.amazon.in/''' + item.ha.a['''href'''] A : Tuple = item.find('''span''' , attrs={'''class''': '''a-offscreen'''} ).text try: A : int = item.find('''span''' , attrs={'''class''': '''a-icon-alt'''} ).text except AttributeError: A : Optional[int] = '''Not available''' try: A : str = ( '''₹''' + item.find( '''span''' , attrs={'''class''': '''a-price a-text-price'''} ).text.split('''₹''' )[1] ) except AttributeError: A : List[Any] = '''''' try: A : Dict = float( ( ( float(product_mrp.strip('''₹''' ).replace(''',''' , '''''' ) ) - float(product_price.strip('''₹''' ).replace(''',''' , '''''' ) ) ) / float(product_mrp.strip('''₹''' ).replace(''',''' , '''''' ) ) ) * 100 ) except ValueError: A : str = float('''nan''' ) except AttributeError: pass A : Union[str, Any] = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] A : List[str] = ''' ''' A : Optional[Any] = ''' ''' data_frame.index += 1 return data_frame if __name__ == "__main__": lowercase : Union[str, Any] = 'headphones' get_amazon_product_data(product).to_csv(f'''Amazon Product Data for {product}.csv''')
311
1
'''simple docstring''' from argparse import ArgumentParser from .add_new_model import AddNewModelCommand from .add_new_model_like import AddNewModelLikeCommand from .convert import ConvertCommand from .download import DownloadCommand from .env import EnvironmentCommand from .lfs import LfsCommands from .pt_to_tf import PTtoTFCommand from .run import RunCommand from .serving import ServeCommand from .user import UserCommands def lowerCAmelCase_ ( ): '''simple docstring''' A : Union[str, Any] = ArgumentParser('''Transformers CLI tool''' , usage='''transformers-cli <command> [<args>]''' ) A : Tuple = parser.add_subparsers(help='''transformers-cli command helpers''' ) # Register commands ConvertCommand.register_subcommand(snake_case__ ) DownloadCommand.register_subcommand(snake_case__ ) EnvironmentCommand.register_subcommand(snake_case__ ) RunCommand.register_subcommand(snake_case__ ) ServeCommand.register_subcommand(snake_case__ ) UserCommands.register_subcommand(snake_case__ ) AddNewModelCommand.register_subcommand(snake_case__ ) AddNewModelLikeCommand.register_subcommand(snake_case__ ) LfsCommands.register_subcommand(snake_case__ ) PTtoTFCommand.register_subcommand(snake_case__ ) # Let's go A : List[Any] = parser.parse_args() if not hasattr(snake_case__ , '''func''' ): parser.print_help() exit(1 ) # Run A : Any = args.func(snake_case__ ) service.run() if __name__ == "__main__": main()
311
'''simple docstring''' import colorsys from PIL import Image # type: ignore def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : Optional[int] = x A : str = y for step in range(snake_case__ ): # noqa: B007 A : str = a * a - b * b + x A : List[str] = 2 * a * b + y A : str = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255 ) for i in colorsys.hsv_to_rgb(snake_case__ , 1 , 1 ) ) def lowerCAmelCase_ ( snake_case__ = 800 , snake_case__ = 600 , snake_case__ = -0.6 , snake_case__ = 0 , snake_case__ = 3.2 , snake_case__ = 50 , snake_case__ = True , ): '''simple docstring''' A : List[Any] = Image.new('''RGB''' , (image_width, image_height) ) A : Tuple = img.load() # loop through the image-coordinates for image_x in range(snake_case__ ): for image_y in range(snake_case__ ): # determine the figure-coordinates based on the image-coordinates A : Optional[int] = figure_width / image_width * image_height A : Tuple = figure_center_x + (image_x / image_width - 0.5) * figure_width A : List[str] = figure_center_y + (image_y / image_height - 0.5) * figure_height A : str = get_distance(snake_case__ , snake_case__ , snake_case__ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: A : str = get_color_coded_rgb(snake_case__ ) else: A : List[Any] = get_black_and_white_rgb(snake_case__ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure lowercase : Optional[Any] = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
311
1
'''simple docstring''' import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''distilbert-base-cased''', '''instance_type''': '''ml.g4dn.xlarge''', '''results''': {'''train_runtime''': 650, '''eval_accuracy''': 0.6, '''eval_loss''': 0.9}, }, { '''framework''': '''tensorflow''', '''script''': '''run_tf.py''', '''model_name_or_path''': '''distilbert-base-cased''', '''instance_type''': '''ml.g4dn.xlarge''', '''results''': {'''train_runtime''': 600, '''eval_accuracy''': 0.3, '''eval_loss''': 0.9}, }, ] ) class A ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> Any: """simple docstring""" if self.framework == "pytorch": subprocess.run( F'cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'.split() , encoding='''utf-8''' , check=SCREAMING_SNAKE_CASE , ) assert hasattr(self , '''env''' ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=1 ) -> Optional[int]: """simple docstring""" return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=F'{self.env.base_job_name}-single' , instance_count=SCREAMING_SNAKE_CASE , instance_type=self.instance_type , debugger_hook_config=SCREAMING_SNAKE_CASE , hyperparameters={**self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , py_version='''py36''' , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" TrainingJobAnalytics(SCREAMING_SNAKE_CASE ).export_csv(F'{self.env.test_path}/{job_name}_metrics.csv' ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Any = self.create_estimator() # run training estimator.fit() # result dataframe A : Optional[Any] = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis A : Any = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) A : Dict = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping A : Optional[int] = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 999999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(F'{estimator.latest_training_job.name}.json' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , SCREAMING_SNAKE_CASE )
311
'''simple docstring''' import argparse import importlib from pathlib import Path # Test all the extensions added in the setup lowercase : Optional[int] = [ 'kernels/rwkv/wkv_cuda.cu', 'kernels/rwkv/wkv_op.cpp', 'kernels/deformable_detr/ms_deform_attn.h', 'kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh', 'models/graphormer/algos_graphormer.pyx', ] def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for file in FILES_TO_FIND: if not (transformers_path / file).exists(): return False return True if __name__ == "__main__": lowercase : str = argparse.ArgumentParser() parser.add_argument('--check_lib', action='store_true', help='Whether to check the build or the actual package.') lowercase : Optional[Any] = parser.parse_args() if args.check_lib: lowercase : List[Any] = importlib.import_module('transformers') lowercase : str = Path(transformers_module.__file__).parent else: lowercase : List[Any] = Path.cwd() / 'build/lib/transformers' if not test_custom_files_are_present(transformers_path): raise ValueError('The built release does not contain the custom files. Fix this before going further!')
311
1
'''simple docstring''' import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Union[str, Any] = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''decoder.output_projection.weight''', '''_float_tensor''', '''encoder.embed_positions._float_tensor''', '''decoder.embed_positions._float_tensor''', ] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A, A : Dict = emb.weight.shape A : Tuple = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) A : Optional[Any] = emb.weight.data return lin_layer def lowerCAmelCase_ ( snake_case__ , snake_case__=None ): '''simple docstring''' A : Union[str, Any] = {} for old_key in state_dict.keys(): A : Optional[Any] = old_key if "moe_layer.experts." in key: if expert_idx is not None: A : Optional[int] = key.replace('''moe_layer.experts.0''' , F'ffn.experts.expert_{expert_idx}' ) else: A : Union[str, Any] = key.replace('''moe_layer.experts.''' , '''ffn.experts.expert_''' ) if "gate" in key: A : List[str] = key.replace('''.moe_layer.gate.wg''' , '''.ffn.router.classifier''' ) if "fc2" and "experts" not in key: A : List[str] = key.replace('''.fc2.''' , '''.ffn.fc2.''' ) if "fc1" and "experts" not in key: A : Union[str, Any] = key.replace('''.fc1.''' , '''.ffn.fc1.''' ) if ".encoder_attn." in key: A : Tuple = key.replace('''.encoder_attn.''' , '''.cross_attention.''' ) if "encoder_attn_layer_norm" in key: A : List[str] = key.replace('''encoder_attn_layer_norm''' , '''cross_attention_layer_norm''' ) if "final_layer_norm" in key: A : Optional[int] = key.replace('''final_layer_norm''' , '''ff_layer_norm''' ) A : Tuple = state_dict[old_key] return new_dict def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ = WEIGHTS_NAME ): '''simple docstring''' A : Dict = [] A : Tuple = 0 os.makedirs(snake_case__ , exist_ok=snake_case__ ) for expert in range(snake_case__ ): A : Union[str, Any] = switch_checkpoint_path + F'-rank-{expert}.pt' if os.path.isfile(snake_case__ ): A : Union[str, Any] = torch.load(snake_case__ )['''model'''] remove_ignore_keys_(snake_case__ ) A : List[Any] = rename_fairseq_keys(snake_case__ , snake_case__ ) A : int = os.path.join( snake_case__ , weights_name.replace('''.bin''' , F'-{len(snake_case__ )+1:05d}-of-???.bin' ) ) torch.save(snake_case__ , snake_case__ ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(snake_case__ )[0]].dtype ) # Add the last block A : List[Any] = os.path.join(snake_case__ , weights_name.replace('''.bin''' , F'-{len(snake_case__ )+1:05d}-of-???.bin' ) ) A : Optional[Any] = torch.load(switch_checkpoint_path + '''-shared.pt''' )['''model'''] remove_ignore_keys_(snake_case__ ) A : Any = rename_fairseq_keys(snake_case__ , snake_case__ ) A : Union[str, Any] = shared_weights['''decoder.embed_tokens.weight'''] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(snake_case__ ) == 1: A : List[str] = os.path.join(snake_case__ , snake_case__ ) torch.save(snake_case__ , snake_case__ ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(snake_case__ , snake_case__ ) # Otherwise, let's build the index A : Union[str, Any] = {} for idx, shard in enumerate(snake_case__ ): A : Any = weights_name.replace('''.bin''' , F'-{idx+1:05d}-of-{len(snake_case__ ):05d}.bin' ) A : Tuple = os.path.join(snake_case__ , weights_name.replace('''.bin''' , F'-{idx+1:05d}-of-???.bin' ) ) os.rename(snake_case__ , os.path.join(snake_case__ , snake_case__ ) ) for key in shard: A : Union[str, Any] = shard_file # Add the metadata A : List[str] = {'''total_size''': total_size} A : Union[str, Any] = {'''metadata''': metadata, '''weight_map''': weight_map} with open(os.path.join(snake_case__ , snake_case__ ) , '''w''' , encoding='''utf-8''' ) as f: A : Tuple = json.dumps(snake_case__ , indent=2 , sort_keys=snake_case__ ) + '''\n''' f.write(snake_case__ ) return metadata, index if __name__ == "__main__": lowercase : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--nllb_moe_checkpoint_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--dtype', default='float32', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b', type=str, required=False, help='Path to the output pytorch model.', ) lowercase : Optional[int] = parser.parse_args() lowercase , lowercase : Any = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 1_28, args.dtype, ) lowercase : Union[str, Any] = NllbMoeConfig.from_pretrained( 'facebook/nllb-200-3.3B', encoder_sparse_step=4, decoder_sparse_step=4, num_experts=1_28 ) config.save_pretrained(args.pytorch_dump_folder_path) lowercase : Dict = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print('Done') model.save_pretrained(args.pytorch_dump_folder_path)
311
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig 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 ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=30 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=2 , ) -> List[str]: """simple docstring""" A : List[str] = parent A : Optional[Any] = batch_size A : Tuple = image_size A : int = patch_size A : Optional[int] = num_channels A : str = is_training A : List[Any] = use_labels A : Any = hidden_size A : Any = num_hidden_layers A : Optional[int] = num_attention_heads A : Any = intermediate_size A : List[str] = hidden_act A : str = hidden_dropout_prob A : Tuple = attention_probs_dropout_prob A : Any = type_sequence_label_size A : Optional[int] = initializer_range A : Dict = scope A : Tuple = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) A : List[Any] = (image_size // patch_size) ** 2 A : Tuple = num_patches + 2 def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A : Tuple = None if self.use_labels: A : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Tuple = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" return DeiTConfig( 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=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : Any = TFDeiTModel(config=SCREAMING_SNAKE_CASE ) A : str = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" A : Tuple = TFDeiTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE ) A : List[Any] = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A : Optional[int] = 1 A : str = TFDeiTForMaskedImageModeling(SCREAMING_SNAKE_CASE ) A : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Tuple = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" A : str = self.type_sequence_label_size A : Optional[Any] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE ) A : Optional[Any] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images A : Optional[Any] = 1 A : List[str] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE ) A : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Optional[int] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Optional[int] = self.prepare_config_and_inputs() A, A, A : Tuple = config_and_inputs A : Any = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class A ( __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) __magic_name__ = ( { '''feature-extraction''': TFDeiTModel, '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) __magic_name__ = False __magic_name__ = False __magic_name__ = False __magic_name__ = False def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = TFDeiTModelTester(self ) A : Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''DeiT does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" pass def __lowerCAmelCase ( self ) -> str: """simple docstring""" A, A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) A : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE , tf.keras.layers.Dense ) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A, A : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) A : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A : Union[str, Any] = [*signature.parameters.keys()] A : List[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ) -> Tuple: """simple docstring""" A : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def __lowerCAmelCase ( self ) -> str: """simple docstring""" for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A : List[str] = TFDeiTModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_ ( ): '''simple docstring''' A : str = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class A ( unittest.TestCase ): @cached_property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) if is_vision_available() else None ) @slow def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Union[str, Any] = TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) A : Dict = self.default_image_processor A : List[str] = prepare_img() A : Any = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='''tf''' ) # forward pass A : Optional[int] = model(**SCREAMING_SNAKE_CASE ) # verify the logits A : List[Any] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE ) A : str = tf.constant([-1.0_266, 0.1_912, -1.2_861] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
1
'''simple docstring''' import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available from ..wavaveca.test_feature_extraction_wavaveca import floats_list if is_pyctcdecode_available(): from huggingface_hub import snapshot_download from pyctcdecode import BeamSearchDecoderCTC from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput if is_torch_available(): from transformers import WavaVecaForCTC @require_pyctcdecode class A ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Optional[Any] = '''| <pad> <unk> <s> </s> a b c d e f g h i j k'''.split() A : Dict = dict(zip(SCREAMING_SNAKE_CASE , range(len(SCREAMING_SNAKE_CASE ) ) ) ) A : Tuple = { '''unk_token''': '''<unk>''', '''bos_token''': '''<s>''', '''eos_token''': '''</s>''', } A : List[str] = { '''feature_size''': 1, '''padding_value''': 0.0, '''sampling_rate''': 16000, '''return_attention_mask''': False, '''do_normalize''': True, } A : Union[str, Any] = tempfile.mkdtemp() A : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) A : Union[str, Any] = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE ) + '''\n''' ) with open(self.feature_extraction_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE ) + '''\n''' ) # load decoder from hub A : Optional[int] = '''hf-internal-testing/ngram-beam-search-decoder''' def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : Dict = self.add_kwargs_tokens_map.copy() kwargs.update(SCREAMING_SNAKE_CASE ) return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Any = self.get_tokenizer() A : Optional[Any] = self.get_feature_extractor() A : int = self.get_decoder() A : List[str] = WavaVecaProcessorWithLM(tokenizer=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE , decoder=SCREAMING_SNAKE_CASE ) processor.save_pretrained(self.tmpdirname ) A : List[Any] = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname ) # tokenizer self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE ) # feature extractor self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE ) # 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 , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : int = WavaVecaProcessorWithLM( tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) processor.save_pretrained(self.tmpdirname ) # make sure that error is thrown when decoder alphabet doesn't match A : Any = 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 __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : int = self.get_tokenizer() # add token to trigger raise tokenizer.add_tokens(['''xx'''] ) with self.assertRaisesRegex(SCREAMING_SNAKE_CASE , '''include''' ): WavaVecaProcessorWithLM( tokenizer=SCREAMING_SNAKE_CASE , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : int = self.get_feature_extractor() A : int = self.get_tokenizer() A : Union[str, Any] = self.get_decoder() A : Any = WavaVecaProcessorWithLM(tokenizer=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE , decoder=SCREAMING_SNAKE_CASE ) A : int = floats_list((3, 1000) ) A : Any = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors='''np''' ) A : Dict = processor(SCREAMING_SNAKE_CASE , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Optional[Any] = self.get_feature_extractor() A : Union[str, Any] = self.get_tokenizer() A : Optional[Any] = self.get_decoder() A : Tuple = WavaVecaProcessorWithLM(tokenizer=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE , decoder=SCREAMING_SNAKE_CASE ) A : int = '''This is a test string''' A : Optional[Any] = processor(text=SCREAMING_SNAKE_CASE ) A : Tuple = tokenizer(SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=(2, 10, 16) , SCREAMING_SNAKE_CASE=77 ) -> str: """simple docstring""" np.random.seed(SCREAMING_SNAKE_CASE ) return np.random.rand(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Dict = self.get_feature_extractor() A : Dict = self.get_tokenizer() A : Optional[int] = self.get_decoder() A : Dict = WavaVecaProcessorWithLM(tokenizer=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE , decoder=SCREAMING_SNAKE_CASE ) A : Optional[Any] = self._get_dummy_logits(shape=(10, 16) , seed=13 ) A : Union[str, Any] = processor.decode(SCREAMING_SNAKE_CASE ) A : List[str] = decoder.decode_beams(SCREAMING_SNAKE_CASE )[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 __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : List[str] = self.get_feature_extractor() A : Optional[Any] = self.get_tokenizer() A : List[str] = self.get_decoder() A : Dict = WavaVecaProcessorWithLM(tokenizer=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE , decoder=SCREAMING_SNAKE_CASE ) A : Dict = self._get_dummy_logits() # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM. # otherwise, the LM won't be available to the pool's sub-processes. # manual logic used to allow parameterized test for both pool=None and pool=Pool(...) if pool_context is None: A : Tuple = processor.batch_decode(SCREAMING_SNAKE_CASE ) else: with get_context(SCREAMING_SNAKE_CASE ).Pool() as pool: A : List[Any] = processor.batch_decode(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : int = list(SCREAMING_SNAKE_CASE ) with get_context('''fork''' ).Pool() as p: A : Tuple = decoder.decode_beams_batch(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A, A, A : Tuple = [], [], [] 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(SCREAMING_SNAKE_CASE , decoded_processor.text ) self.assertListEqual(['''<s> <s> </s>''', '''<s> <s> <s>'''] , decoded_processor.text ) self.assertListEqual(SCREAMING_SNAKE_CASE , decoded_processor.logit_score ) self.assertListEqual(SCREAMING_SNAKE_CASE , decoded_processor.lm_score ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : List[str] = self.get_feature_extractor() A : Union[str, Any] = self.get_tokenizer() A : Any = self.get_decoder() A : Optional[Any] = WavaVecaProcessorWithLM(tokenizer=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE , decoder=SCREAMING_SNAKE_CASE ) A : Optional[int] = self._get_dummy_logits() A : Optional[Any] = 15 A : str = -20.0 A : Union[str, Any] = -4.0 A : str = processor.batch_decode( SCREAMING_SNAKE_CASE , beam_width=SCREAMING_SNAKE_CASE , beam_prune_logp=SCREAMING_SNAKE_CASE , token_min_logp=SCREAMING_SNAKE_CASE , ) A : Any = decoded_processor_out.text A : List[Any] = list(SCREAMING_SNAKE_CASE ) with get_context('''fork''' ).Pool() as pool: A : Union[str, Any] = decoder.decode_beams_batch( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beam_width=SCREAMING_SNAKE_CASE , beam_prune_logp=SCREAMING_SNAKE_CASE , token_min_logp=SCREAMING_SNAKE_CASE , ) A : int = [d[0][0] for d in decoded_decoder_out] A : Dict = [d[0][2] for d in decoded_decoder_out] A : Union[str, Any] = [d[0][3] for d in decoded_decoder_out] self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertListEqual(['''</s> <s> <s>''', '''<s> <s> <s>'''] , SCREAMING_SNAKE_CASE ) self.assertTrue(np.array_equal(SCREAMING_SNAKE_CASE , decoded_processor_out.logit_score ) ) self.assertTrue(np.allclose([-20.054, -18.447] , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) self.assertTrue(np.array_equal(SCREAMING_SNAKE_CASE , decoded_processor_out.lm_score ) ) self.assertTrue(np.allclose([-15.554, -13.9_474] , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[int] = self.get_feature_extractor() A : Optional[Any] = self.get_tokenizer() A : Any = self.get_decoder() A : Optional[int] = WavaVecaProcessorWithLM(tokenizer=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE , decoder=SCREAMING_SNAKE_CASE ) A : Dict = self._get_dummy_logits() A : Tuple = 2.0 A : Union[str, Any] = 5.0 A : Optional[int] = -20.0 A : Optional[int] = True A : List[str] = processor.batch_decode( SCREAMING_SNAKE_CASE , alpha=SCREAMING_SNAKE_CASE , beta=SCREAMING_SNAKE_CASE , unk_score_offset=SCREAMING_SNAKE_CASE , lm_score_boundary=SCREAMING_SNAKE_CASE , ) A : Optional[Any] = decoded_processor_out.text A : int = list(SCREAMING_SNAKE_CASE ) decoder.reset_params( alpha=SCREAMING_SNAKE_CASE , beta=SCREAMING_SNAKE_CASE , unk_score_offset=SCREAMING_SNAKE_CASE , lm_score_boundary=SCREAMING_SNAKE_CASE , ) with get_context('''fork''' ).Pool() as pool: A : List[Any] = decoder.decode_beams_batch( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) A : str = [d[0][0] for d in decoded_decoder_out] self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertListEqual(['''<s> </s> <s> </s> </s>''', '''</s> </s> <s> </s> </s>'''] , SCREAMING_SNAKE_CASE ) A : Optional[int] = 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 , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Union[str, Any] = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) A : Optional[Any] = processor.decoder.model_container[processor.decoder._model_key] A : Optional[Any] = Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute() A : List[str] = os.listdir(SCREAMING_SNAKE_CASE ) A : Tuple = ['''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(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Union[str, Any] = snapshot_download('''hf-internal-testing/processor_with_lm''' ) A : Optional[int] = WavaVecaProcessorWithLM.from_pretrained(SCREAMING_SNAKE_CASE ) A : int = processor.decoder.model_container[processor.decoder._model_key] A : Any = Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute() A : Optional[int] = os.listdir(SCREAMING_SNAKE_CASE ) A : Any = os.listdir(SCREAMING_SNAKE_CASE ) local_decoder_files.sort() expected_decoder_files.sort() # test that both decoder form hub and local files in cache are the same self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : int = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) A : List[str] = AutoProcessor.from_pretrained('''hf-internal-testing/processor_with_lm''' ) A : Dict = floats_list((3, 1000) ) A : Dict = processor_wavaveca(SCREAMING_SNAKE_CASE , return_tensors='''np''' ) A : List[str] = processor_auto(SCREAMING_SNAKE_CASE , return_tensors='''np''' ) for key in input_wavaveca.keys(): self.assertAlmostEqual(input_wavaveca[key].sum() , input_auto[key].sum() , delta=1e-2 ) A : Union[str, Any] = self._get_dummy_logits() A : Dict = processor_wavaveca.batch_decode(SCREAMING_SNAKE_CASE ) A : str = processor_auto.batch_decode(SCREAMING_SNAKE_CASE ) self.assertListEqual(decoded_wavaveca.text , decoded_auto.text ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Union[str, Any] = self.get_feature_extractor() A : Optional[Any] = self.get_tokenizer() A : int = self.get_decoder() A : Tuple = WavaVecaProcessorWithLM(tokenizer=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE , decoder=SCREAMING_SNAKE_CASE ) self.assertListEqual( processor.model_input_names , feature_extractor.model_input_names , msg='''`processor` and `feature_extractor` model input names do not match''' , ) @staticmethod def __lowerCAmelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" A : Optional[int] = [d[key] for d in offsets] return retrieved_list def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Dict = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) A : Dict = self._get_dummy_logits()[0] A : List[str] = processor.decode(SCREAMING_SNAKE_CASE , output_word_offsets=SCREAMING_SNAKE_CASE ) # 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(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) 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 __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Optional[int] = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) A : List[str] = self._get_dummy_logits() A : Any = processor.batch_decode(SCREAMING_SNAKE_CASE , output_word_offsets=SCREAMING_SNAKE_CASE ) # 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(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) self.assertListEqual( [''' '''.join(self.get_from_offsets(SCREAMING_SNAKE_CASE , '''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 __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" import torch A : Any = load_dataset('''common_voice''' , '''en''' , split='''train''' , streaming=SCREAMING_SNAKE_CASE ) A : int = ds.cast_column('''audio''' , datasets.Audio(sampling_rate=16000 ) ) A : str = iter(SCREAMING_SNAKE_CASE ) A : Optional[Any] = next(SCREAMING_SNAKE_CASE ) A : int = AutoProcessor.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' ) A : Union[str, Any] = WavaVecaForCTC.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' ) # compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train A : Union[str, Any] = processor(sample['''audio''']['''array'''] , return_tensors='''pt''' ).input_values with torch.no_grad(): A : List[str] = model(SCREAMING_SNAKE_CASE ).logits.cpu().numpy() A : Optional[int] = processor.decode(logits[0] , output_word_offsets=SCREAMING_SNAKE_CASE ) A : Union[str, Any] = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate A : Dict = [ { '''start_time''': d['''start_offset'''] * time_offset, '''end_time''': d['''end_offset'''] * time_offset, '''word''': d['''word'''], } for d in output['''word_offsets'''] ] A : int = '''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(SCREAMING_SNAKE_CASE , '''word''' ) ) , SCREAMING_SNAKE_CASE ) self.assertEqual(''' '''.join(self.get_from_offsets(SCREAMING_SNAKE_CASE , '''word''' ) ) , output.text ) # output times A : Optional[int] = torch.tensor(self.get_from_offsets(SCREAMING_SNAKE_CASE , '''start_time''' ) ) A : int = torch.tensor(self.get_from_offsets(SCREAMING_SNAKE_CASE , '''end_time''' ) ) # fmt: off A : int = torch.tensor([1.4_199, 1.6_599, 2.2_599, 3.0, 3.24, 3.5_999, 3.7_999, 4.0_999, 4.26, 4.94, 5.28, 5.6_599, 5.78, 5.94, 6.32, 6.5_399, 6.6_599] ) A : List[str] = torch.tensor([1.5_399, 1.8_999, 2.9, 3.16, 3.5_399, 3.72, 4.0_199, 4.1_799, 4.76, 5.1_599, 5.5_599, 5.6_999, 5.86, 6.1_999, 6.38, 6.6_199, 6.94] ) # fmt: on self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=0.01 ) ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=0.01 ) )
311
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase : List[str] = { 'configuration_cpmant': ['CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CpmAntConfig'], 'tokenization_cpmant': ['CpmAntTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[Any] = [ 'CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST', 'CpmAntForCausalLM', 'CpmAntModel', 'CpmAntPreTrainedModel', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys lowercase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
311
1
'''simple docstring''' import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) lowercase : Optional[Any] = logging.getLogger() def lowerCAmelCase_ ( ): '''simple docstring''' A : Tuple = argparse.ArgumentParser() parser.add_argument('''-f''' ) A : Union[str, Any] = parser.parse_args() return args.f class A ( __snake_case ): def __lowerCAmelCase ( self ) -> None: """simple docstring""" A : str = logging.StreamHandler(sys.stdout ) logger.addHandler(SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" A : Tuple = get_gpu_count() if n_gpu > 1: pass # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560 # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py" # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split() # cmd = [sys.executable] + distributed_args + args # execute_subprocess_async(cmd, env=self.get_env()) # XXX: test the results - need to save them first into .json file else: args.insert(0 , '''run_glue_deebert.py''' ) with patch.object(SCREAMING_SNAKE_CASE , '''argv''' , SCREAMING_SNAKE_CASE ): A : Optional[Any] = run_glue_deebert.main() for value in result.values(): self.assertGreaterEqual(SCREAMING_SNAKE_CASE , 0.666 ) @slow @require_torch_non_multi_gpu def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Optional[Any] = ''' --model_type roberta --model_name_or_path roberta-base --task_name MRPC --do_train --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --max_seq_length 128 --per_gpu_eval_batch_size=1 --per_gpu_train_batch_size=8 --learning_rate 2e-4 --num_train_epochs 3 --overwrite_output_dir --seed 42 --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --save_steps 0 --overwrite_cache --eval_after_first_stage '''.split() self.run_and_check(SCREAMING_SNAKE_CASE ) A : Dict = ''' --model_type roberta --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --task_name MRPC --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --max_seq_length 128 --eval_each_highway --eval_highway --overwrite_cache --per_gpu_eval_batch_size=1 '''.split() self.run_and_check(SCREAMING_SNAKE_CASE ) A : Dict = ''' --model_type roberta --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --task_name MRPC --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --max_seq_length 128 --early_exit_entropy 0.1 --eval_highway --overwrite_cache --per_gpu_eval_batch_size=1 '''.split() self.run_and_check(SCREAMING_SNAKE_CASE )
311
'''simple docstring''' from __future__ import annotations lowercase : Union[str, Any] = list[tuple[int, int]] lowercase : Optional[Any] = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] lowercase : Any = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" A : int = pos_x A : Optional[Any] = pos_y A : Optional[Any] = (pos_y, pos_x) A : str = goal_x A : Optional[int] = goal_y A : List[Any] = g_cost A : str = parent A : str = self.calculate_heuristic() def __lowerCAmelCase ( self ) -> float: """simple docstring""" A : Optional[int] = abs(self.pos_x - self.goal_x ) A : Optional[Any] = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self , SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" return self.f_cost < other.f_cost class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , SCREAMING_SNAKE_CASE ) A : Tuple = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , SCREAMING_SNAKE_CASE ) A : Optional[Any] = [self.start] A : list[Node] = [] A : Tuple = False def __lowerCAmelCase ( self ) -> Path | None: """simple docstring""" while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() A : Optional[int] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: A : Optional[int] = True return self.retrace_path(SCREAMING_SNAKE_CASE ) self.closed_nodes.append(SCREAMING_SNAKE_CASE ) A : Any = self.get_successors(SCREAMING_SNAKE_CASE ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(SCREAMING_SNAKE_CASE ) else: # retrieve the best current path A : str = self.open_nodes.pop(self.open_nodes.index(SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(SCREAMING_SNAKE_CASE ) else: self.open_nodes.append(SCREAMING_SNAKE_CASE ) if not self.reached: return [self.start.pos] return None def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> list[Node]: """simple docstring""" A : List[Any] = [] for action in delta: A : List[str] = parent.pos_x + action[1] A : Dict = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , SCREAMING_SNAKE_CASE , ) ) return successors def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Path: """simple docstring""" A : int = node A : Union[str, Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) A : int = current_node.parent path.reverse() return path if __name__ == "__main__": lowercase : Tuple = (0, 0) lowercase : List[str] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print('------') lowercase : int = GreedyBestFirst(init, goal) lowercase : Union[str, Any] = greedy_bf.search() if path: for pos_x, pos_y in path: lowercase : Dict = 2 for elem in grid: print(elem)
311
1
'''simple docstring''' import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=8 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=36 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=None , ) -> Optional[Any]: """simple docstring""" A : Dict = parent A : Optional[Any] = batch_size A : Dict = seq_length A : Optional[Any] = is_training A : str = use_input_mask A : List[str] = use_token_type_ids A : List[Any] = use_labels A : Union[str, Any] = vocab_size A : str = hidden_size A : int = num_hidden_layers A : Optional[Any] = num_attention_heads A : int = intermediate_size A : Optional[int] = hidden_act A : Union[str, Any] = hidden_dropout_prob A : Union[str, Any] = attention_probs_dropout_prob A : List[Any] = max_position_embeddings A : Tuple = type_vocab_size A : Any = type_sequence_label_size A : int = initializer_range A : Union[str, Any] = num_labels A : List[Any] = num_choices A : Union[str, Any] = scope def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Optional[int] = None if self.use_input_mask: A : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) A : str = None if self.use_token_type_ids: A : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A : Optional[int] = None A : Tuple = None A : List[str] = None if self.use_labels: A : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A : int = ids_tensor([self.batch_size] , self.num_choices ) A : Union[str, Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : int = self.get_config() A : Tuple = 300 return config def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" ( ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ) : Dict = self.prepare_config_and_inputs() A : Optional[Any] = True A : List[str] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" A : int = MraModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE ) A : Optional[int] = model(SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE ) A : Dict = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" A : Dict = True A : Any = MraModel(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , ) A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , ) A : Any = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" A : List[Any] = MraForMaskedLM(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[str] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" A : List[str] = MraForQuestionAnswering(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Optional[int] = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , start_positions=SCREAMING_SNAKE_CASE , end_positions=SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" A : List[str] = self.num_labels A : Dict = MraForSequenceClassification(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Any = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" A : Any = self.num_labels A : Tuple = MraForTokenClassification(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" A : int = self.num_choices A : Tuple = MraForMultipleChoice(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : int = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : str = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : List[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : Dict = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Dict = self.prepare_config_and_inputs() ( ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ) : List[str] = config_and_inputs A : Dict = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class A ( __snake_case , unittest.TestCase ): __magic_name__ = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) __magic_name__ = False __magic_name__ = False __magic_name__ = False __magic_name__ = False __magic_name__ = () def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : List[str] = MraModelTester(self ) A : Tuple = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A : int = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) @slow def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A : List[str] = MraModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) @unittest.skip(reason='''MRA does not output attentions''' ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" return @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Tuple = MraModel.from_pretrained('''uw-madison/mra-base-512-4''' ) A : int = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): A : Any = model(SCREAMING_SNAKE_CASE )[0] A : Dict = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : Tuple = torch.tensor( [[[-0.0_140, 0.0_830, -0.0_381], [0.1_546, 0.1_402, 0.0_220], [0.1_162, 0.0_851, 0.0_165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Any = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-512-4''' ) A : Tuple = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): A : List[Any] = model(SCREAMING_SNAKE_CASE )[0] A : Tuple = 50265 A : Tuple = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : Optional[int] = torch.tensor( [[[9.2_595, -3.6_038, 11.8_819], [9.3_869, -3.2_693, 11.0_956], [11.8_524, -3.4_938, 13.1_210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Tuple = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-4096-8-d3''' ) A : int = torch.arange(4096 ).unsqueeze(0 ) with torch.no_grad(): A : Optional[int] = model(SCREAMING_SNAKE_CASE )[0] A : Any = 50265 A : List[str] = torch.Size((1, 4096, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : List[str] = torch.tensor( [[[5.4_789, -2.3_564, 7.5_064], [7.9_067, -1.3_369, 9.9_668], [9.0_712, -1.8_106, 7.0_380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
'''simple docstring''' import argparse import os from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_task_guides.py lowercase : Any = 'src/transformers' lowercase : str = 'docs/source/en/tasks' def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' with open(snake_case__ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: A : Union[str, Any] = f.readlines() # Find the start prompt. A : List[Any] = 0 while not lines[start_index].startswith(snake_case__ ): start_index += 1 start_index += 1 A : List[str] = start_index while not lines[end_index].startswith(snake_case__ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. lowercase : int = direct_transformers_import(TRANSFORMERS_PATH) lowercase : str = { 'asr.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, 'audio_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, 'language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, 'image_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, 'masked_language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, 'multiple_choice.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, 'object_detection.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, 'question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, 'semantic_segmentation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, 'sequence_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, 'summarization.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'token_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, 'translation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'video_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, 'document_question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, 'monocular_depth_estimation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). lowercase : Optional[int] = { 'summarization.md': ('nllb',), 'translation.md': ('nllb',), } def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : int = TASK_GUIDE_TO_MODELS[task_guide] A : List[str] = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(snake_case__ , set() ) A : Union[str, Any] = { code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([F'[{name}](../model_doc/{code})' for code, name in model_names.items()] ) + "\n" def lowerCAmelCase_ ( snake_case__ , snake_case__=False ): '''simple docstring''' A, A, A, A : Optional[int] = _find_text_in_file( filename=os.path.join(snake_case__ , snake_case__ ) , start_prompt='''<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->''' , end_prompt='''<!--End of the generated tip-->''' , ) A : Optional[int] = get_model_list_for_task(snake_case__ ) if current_list != new_list: if overwrite: with open(os.path.join(snake_case__ , snake_case__ ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:] ) else: raise ValueError( F'The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`' ''' to fix this.''' ) if __name__ == "__main__": lowercase : Dict = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') lowercase : List[Any] = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
311
1
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal lowercase : str = datasets.utils.logging.get_logger(__name__) lowercase : Union[str, Any] = ['names', 'prefix'] lowercase : Union[str, Any] = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] lowercase : List[Any] = ['encoding_errors', 'on_bad_lines'] lowercase : Any = ['date_format'] @dataclass class A ( datasets.BuilderConfig ): __magic_name__ = "," __magic_name__ = None __magic_name__ = "infer" __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = False __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = True __magic_name__ = False __magic_name__ = True __magic_name__ = None __magic_name__ = "." __magic_name__ = None __magic_name__ = '"' __magic_name__ = 0 __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = True __magic_name__ = 0 __magic_name__ = True __magic_name__ = False __magic_name__ = None __magic_name__ = 10000 __magic_name__ = None __magic_name__ = "strict" __magic_name__ = "error" __magic_name__ = None def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" if self.delimiter is not None: A : Optional[Any] = self.delimiter if self.column_names is not None: A : Optional[Any] = self.column_names @property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : str = { '''sep''': self.sep, '''header''': self.header, '''names''': self.names, '''index_col''': self.index_col, '''usecols''': self.usecols, '''prefix''': self.prefix, '''mangle_dupe_cols''': self.mangle_dupe_cols, '''engine''': self.engine, '''converters''': self.converters, '''true_values''': self.true_values, '''false_values''': self.false_values, '''skipinitialspace''': self.skipinitialspace, '''skiprows''': self.skiprows, '''nrows''': self.nrows, '''na_values''': self.na_values, '''keep_default_na''': self.keep_default_na, '''na_filter''': self.na_filter, '''verbose''': self.verbose, '''skip_blank_lines''': self.skip_blank_lines, '''thousands''': self.thousands, '''decimal''': self.decimal, '''lineterminator''': self.lineterminator, '''quotechar''': self.quotechar, '''quoting''': self.quoting, '''escapechar''': self.escapechar, '''comment''': self.comment, '''encoding''': self.encoding, '''dialect''': self.dialect, '''error_bad_lines''': self.error_bad_lines, '''warn_bad_lines''': self.warn_bad_lines, '''skipfooter''': self.skipfooter, '''doublequote''': self.doublequote, '''memory_map''': self.memory_map, '''float_precision''': self.float_precision, '''chunksize''': self.chunksize, '''encoding_errors''': self.encoding_errors, '''on_bad_lines''': self.on_bad_lines, '''date_format''': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , SCREAMING_SNAKE_CASE ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class A ( datasets.ArrowBasedBuilder ): __magic_name__ = CsvConfig def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) A : int = dl_manager.download_and_extract(self.config.data_files ) if isinstance(SCREAMING_SNAKE_CASE , (str, list, tuple) ): A : str = data_files if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : int = [files] A : Optional[int] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] A : Tuple = [] for split_name, files in data_files.items(): if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : List[str] = [files] A : List[str] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE ) for file in files] splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE , gen_kwargs={'''files''': files} ) ) return splits def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> pa.Table: """simple docstring""" if self.config.features is not None: A : Optional[int] = self.config.features.arrow_schema if all(not require_storage_cast(SCREAMING_SNAKE_CASE ) for feature in self.config.features.values() ): # cheaper cast A : List[Any] = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=SCREAMING_SNAKE_CASE ) else: # more expensive cast; allows str <-> int/float or str to Audio for example A : int = table_cast(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return pa_table def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" A : Union[str, Any] = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str A : int = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(SCREAMING_SNAKE_CASE ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE ) ): A : Union[str, Any] = pd.read_csv(SCREAMING_SNAKE_CASE , iterator=SCREAMING_SNAKE_CASE , dtype=SCREAMING_SNAKE_CASE , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(SCREAMING_SNAKE_CASE ): A : Dict = pa.Table.from_pandas(SCREAMING_SNAKE_CASE ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE ) except ValueError as e: logger.error(F'Failed to read file \'{file}\' with error {type(SCREAMING_SNAKE_CASE )}: {e}' ) raise
311
'''simple docstring''' def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if len(snake_case__ ) <= 1: return [tuple(snake_case__ )] A : Tuple = [] def generate(snake_case__ , snake_case__ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , snake_case__ ) for i in range(k - 1 ): if k % 2 == 0: # k is even A, A : Optional[Any] = arr[k - 1], arr[i] else: # k is odd A, A : Optional[Any] = arr[k - 1], arr[0] generate(k - 1 , snake_case__ ) generate(len(snake_case__ ) , snake_case__ ) return res if __name__ == "__main__": lowercase : List[str] = input('Enter numbers separated by a comma:\n').strip() lowercase : int = [int(item) for item in user_input.split(',')] print(heaps(arr))
311
1
'''simple docstring''' from __future__ import annotations lowercase : Any = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ): '''simple docstring''' A : List[Any] = [ [0 for col in range(len(grid[0] ) )] for row in range(len(snake_case__ ) ) ] # the reference grid A : Dict = 1 A : int = [ [0 for col in range(len(grid[0] ) )] for row in range(len(snake_case__ ) ) ] # the action grid A : Tuple = init[0] A : Tuple = init[1] A : str = 0 A : int = g + heuristic[x][y] # cost from starting cell to destination cell A : Optional[Any] = [[f, g, x, y]] A : Any = False # flag that is set when search is complete A : Optional[int] = False # flag set if we can't find expand while not found and not resign: if len(snake_case__ ) == 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 : Optional[int] = cell.pop() A : Tuple = next_cell[2] A : Union[str, Any] = next_cell[3] A : Optional[int] = next_cell[1] if x == goal[0] and y == goal[1]: A : Dict = True else: for i in range(len(snake_case__ ) ): # to try out different valid actions A : Union[str, Any] = x + DIRECTIONS[i][0] A : Tuple = y + DIRECTIONS[i][1] if xa >= 0 and xa < len(snake_case__ ) and ya >= 0 and ya < len(grid[0] ): if closed[xa][ya] == 0 and grid[xa][ya] == 0: A : str = g + cost A : Any = ga + heuristic[xa][ya] cell.append([fa, ga, xa, ya] ) A : Optional[int] = 1 A : Tuple = i A : Optional[Any] = [] A : Optional[int] = goal[0] A : Optional[int] = goal[1] invpath.append([x, y] ) # we get the reverse path from here while x != init[0] or y != init[1]: A : Tuple = x - DIRECTIONS[action[x][y]][0] A : List[Any] = y - DIRECTIONS[action[x][y]][1] A : List[str] = xa A : str = ya invpath.append([x, y] ) A : Dict = [] for i in range(len(snake_case__ ) ): path.append(invpath[len(snake_case__ ) - 1 - i] ) return path, action if __name__ == "__main__": lowercase : List[str] = [ [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], ] lowercase : Union[str, Any] = [0, 0] # all coordinates are given in format [y,x] lowercase : Any = [len(grid) - 1, len(grid[0]) - 1] lowercase : Tuple = 1 # the cost map which pushes the path closer to the goal lowercase : List[Any] = [[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])): lowercase : List[Any] = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map lowercase : Union[str, Any] = 99 lowercase , lowercase : List[str] = 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])
311
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class A ( __snake_case ): __magic_name__ = (UniPCMultistepScheduler,) __magic_name__ = (('''num_inference_steps''', 25),) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" A : str = { '''num_train_timesteps''': 1000, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''solver_order''': 2, '''solver_type''': '''bh2''', } config.update(**SCREAMING_SNAKE_CASE ) return config def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=0 , **SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : List[Any] = dict(self.forward_default_kwargs ) A : Union[str, Any] = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE ) A : Optional[Any] = self.dummy_sample A : int = 0.1 * sample A : Union[str, Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A : Optional[Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals A : List[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE ) A : List[Any] = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE ) new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals A : Dict = dummy_past_residuals[: new_scheduler.config.solver_order] A, A : Tuple = sample, sample for t in range(SCREAMING_SNAKE_CASE , time_step + scheduler.config.solver_order + 1 ): A : Any = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample A : Optional[Any] = new_scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=0 , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : Optional[Any] = dict(self.forward_default_kwargs ) A : Tuple = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE ) A : List[Any] = self.dummy_sample A : int = 0.1 * sample A : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A : Optional[int] = self.get_scheduler_config() A : Any = scheduler_class(**SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals (must be after setting timesteps) A : int = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE ) A : int = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residual (must be after setting timesteps) A : Optional[Any] = dummy_past_residuals[: new_scheduler.config.solver_order] A : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample A : List[Any] = new_scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" if scheduler is None: A : Dict = self.scheduler_classes[0] A : Union[str, Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : List[Any] = scheduler_class(**SCREAMING_SNAKE_CASE ) A : Tuple = self.scheduler_classes[0] A : Union[str, Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE ) A : int = 10 A : Tuple = self.dummy_model() A : Any = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): A : int = model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Optional[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample return sample def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Tuple = dict(self.forward_default_kwargs ) A : List[Any] = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE ) for scheduler_class in self.scheduler_classes: A : Dict = self.get_scheduler_config() A : Dict = scheduler_class(**SCREAMING_SNAKE_CASE ) A : Optional[Any] = self.dummy_sample A : Optional[int] = 0.1 * sample if num_inference_steps is not None and hasattr(SCREAMING_SNAKE_CASE , '''set_timesteps''' ): scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) elif num_inference_steps is not None and not hasattr(SCREAMING_SNAKE_CASE , '''set_timesteps''' ): A : Tuple = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) A : Dict = [residual + 0.2, residual + 0.15, residual + 0.10] A : List[str] = dummy_past_residuals[: scheduler.config.solver_order] A : List[Any] = scheduler.timesteps[5] A : Dict = scheduler.timesteps[6] A : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample A : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Union[str, Any] = UniPCMultistepScheduler(**self.get_scheduler_config() ) A : List[Any] = self.full_loop(scheduler=SCREAMING_SNAKE_CASE ) A : List[str] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.2_464 ) < 1e-3 A : Dict = DPMSolverSinglestepScheduler.from_config(scheduler.config ) A : Optional[int] = DEISMultistepScheduler.from_config(scheduler.config ) A : List[Any] = DPMSolverMultistepScheduler.from_config(scheduler.config ) A : List[Any] = UniPCMultistepScheduler.from_config(scheduler.config ) A : Optional[Any] = self.full_loop(scheduler=SCREAMING_SNAKE_CASE ) A : Optional[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.2_464 ) < 1e-3 def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE ) 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=SCREAMING_SNAKE_CASE , prediction_type=SCREAMING_SNAKE_CASE , sample_max_value=SCREAMING_SNAKE_CASE , solver_order=SCREAMING_SNAKE_CASE , solver_type=SCREAMING_SNAKE_CASE , ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" for solver_type in ["bh1", "bh2"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=SCREAMING_SNAKE_CASE , solver_type=SCREAMING_SNAKE_CASE , prediction_type=SCREAMING_SNAKE_CASE , ) A : Dict = self.full_loop( solver_order=SCREAMING_SNAKE_CASE , solver_type=SCREAMING_SNAKE_CASE , prediction_type=SCREAMING_SNAKE_CASE , ) assert not torch.isnan(SCREAMING_SNAKE_CASE ).any(), "Samples have nan numbers" def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE ) self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=SCREAMING_SNAKE_CASE , time_step=0 ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : int = self.full_loop() A : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.2_464 ) < 1e-3 def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : List[Any] = self.full_loop(prediction_type='''v_prediction''' ) A : Any = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.1_014 ) < 1e-3 def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Dict = self.scheduler_classes[0] A : List[Any] = self.get_scheduler_config(thresholding=SCREAMING_SNAKE_CASE , dynamic_thresholding_ratio=0 ) A : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE ) A : Tuple = 10 A : Union[str, Any] = self.dummy_model() A : Dict = self.dummy_sample_deter.half() scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): A : Dict = model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Optional[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample assert sample.dtype == torch.floataa def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" for scheduler_class in self.scheduler_classes: A : Dict = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : Tuple = scheduler_class(**SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(scheduler.config.num_train_timesteps ) assert len(scheduler.timesteps.unique() ) == scheduler.num_inference_steps
311
1
'''simple docstring''' import unittest from transformers import BertGenerationConfig, 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 BertGenerationDecoder, BertGenerationEncoder class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=50 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=None , ) -> str: """simple docstring""" A : Any = parent A : List[Any] = batch_size A : Union[str, Any] = seq_length A : Any = is_training A : int = use_input_mask A : Union[str, Any] = vocab_size A : List[Any] = hidden_size A : List[Any] = num_hidden_layers A : Optional[int] = num_attention_heads A : str = intermediate_size A : Tuple = hidden_act A : Union[str, Any] = hidden_dropout_prob A : Union[str, Any] = attention_probs_dropout_prob A : int = max_position_embeddings A : Optional[int] = initializer_range A : Any = use_labels A : Optional[int] = scope def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Optional[int] = None if self.use_input_mask: A : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: A : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Dict = self.get_config() return config, input_ids, input_mask, token_labels def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" return BertGenerationConfig( 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 , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" ( ( A ), ( A ), ( A ), ( A ), ) : Any = self.prepare_config_and_inputs() A : Tuple = True A : int = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A : str = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" A : List[str] = BertGenerationEncoder(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) A : int = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> Union[str, Any]: """simple docstring""" A : List[str] = True A : Union[str, Any] = BertGenerationEncoder(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , ) A : List[Any] = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" A : Optional[Any] = True A : Tuple = True A : Optional[int] = BertGenerationDecoder(config=SCREAMING_SNAKE_CASE ).to(SCREAMING_SNAKE_CASE ).eval() # first forward pass A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , use_cache=SCREAMING_SNAKE_CASE , ) A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A : List[str] = ids_tensor((self.batch_size, 3) , config.vocab_size ) A : Tuple = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and A : Dict = torch.cat([input_ids, next_tokens] , dim=-1 ) A : List[str] = torch.cat([input_mask, next_mask] , dim=-1 ) A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE , )['''hidden_states'''][0] A : Any = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , past_key_values=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE , )['''hidden_states'''][0] # select random slice A : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() A : List[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() A : str = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" A : Optional[Any] = BertGenerationDecoder(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Optional[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A, A, A, A : Optional[int] = self.prepare_config_and_inputs() A : str = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class A ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () __magic_name__ = (BertGenerationDecoder,) if is_torch_available() else () __magic_name__ = ( {'''feature-extraction''': BertGenerationEncoder, '''text-generation''': BertGenerationDecoder} if is_torch_available() else {} ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : List[str] = BertGenerationEncoderTester(self ) A : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A, A, A, A : Tuple = self.model_tester.prepare_config_and_inputs() A : str = '''bert''' self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : int = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" ( ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ) : Tuple = self.model_tester.prepare_config_and_inputs_for_decoder() A : Union[str, Any] = None self.model_tester.create_and_check_model_as_decoder( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*SCREAMING_SNAKE_CASE ) @slow def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Optional[Any] = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) A : Optional[Any] = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]] ) with torch.no_grad(): A : Dict = model(SCREAMING_SNAKE_CASE )[0] A : Optional[Any] = torch.Size([1, 8, 1024] ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : Dict = torch.tensor( [[[0.1_775, 0.0_083, -0.0_321], [1.6_002, 0.1_287, 0.3_912], [2.1_473, 0.5_791, 0.6_066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[Any] = BertGenerationDecoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) A : Dict = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]] ) with torch.no_grad(): A : Optional[Any] = model(SCREAMING_SNAKE_CASE )[0] A : Optional[Any] = torch.Size([1, 8, 50358] ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : Any = torch.tensor( [[[-0.5_788, -2.5_994, -3.7_054], [0.0_438, 4.7_997, 1.8_795], [1.5_862, 6.6_409, 4.4_638]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM A : Dict = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 0.0 , SCREAMING_SNAKE_CASE = 50 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = "pil" , SCREAMING_SNAKE_CASE = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" if isinstance(self.unet.config.sample_size , SCREAMING_SNAKE_CASE ): A : List[Any] = ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size, ) else: A : Optional[int] = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size) if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and len(SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( F'You have passed a list of generators of length {len(SCREAMING_SNAKE_CASE )}, but requested an effective batch' F' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) A : str = randn_tensor(SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output A : Any = self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 A : int = self.scheduler.step( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , eta=SCREAMING_SNAKE_CASE , use_clipped_model_output=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE ).prev_sample A : Dict = (image / 2 + 0.5).clamp(0 , 1 ) A : Optional[int] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": A : int = self.numpy_to_pil(SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE )
311
1
'''simple docstring''' from __future__ import annotations import inspect import unittest from transformers import ViTConfig 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 TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=30 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=None , ) -> Tuple: """simple docstring""" A : Optional[Any] = parent A : Optional[Any] = batch_size A : str = image_size A : List[Any] = patch_size A : Any = num_channels A : Dict = is_training A : Any = use_labels A : int = hidden_size A : List[str] = num_hidden_layers A : str = num_attention_heads A : Tuple = intermediate_size A : List[Any] = hidden_act A : Any = hidden_dropout_prob A : Dict = attention_probs_dropout_prob A : Any = type_sequence_label_size A : Tuple = initializer_range A : List[Any] = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) A : Optional[Any] = (image_size // patch_size) ** 2 A : Any = num_patches + 1 def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A : Tuple = None if self.use_labels: A : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Optional[int] = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" return ViTConfig( 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=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" A : List[str] = TFViTModel(config=SCREAMING_SNAKE_CASE ) A : Dict = model(SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. A : Union[str, Any] = self.image_size // 2 A : Any = pixel_values[:, :, :image_size, :image_size] A : Optional[int] = model(SCREAMING_SNAKE_CASE , interpolate_pos_encoding=SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE ) A : Optional[Any] = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : Union[str, Any] = self.type_sequence_label_size A : Tuple = TFViTForImageClassification(SCREAMING_SNAKE_CASE ) A : List[str] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. A : Optional[Any] = self.image_size // 2 A : Optional[int] = pixel_values[:, :, :image_size, :image_size] A : Any = model(SCREAMING_SNAKE_CASE , interpolate_pos_encoding=SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images A : Optional[int] = 1 A : List[str] = TFViTForImageClassification(SCREAMING_SNAKE_CASE ) A : Optional[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Union[str, Any] = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : List[Any] = self.prepare_config_and_inputs() A, A, A : List[Any] = config_and_inputs A : Dict = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class A ( __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () __magic_name__ = ( {'''feature-extraction''': TFViTModel, '''image-classification''': TFViTForImageClassification} if is_tf_available() else {} ) __magic_name__ = False __magic_name__ = False __magic_name__ = False def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : List[str] = TFViTModelTester(self ) A : int = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''ViT does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" pass @unittest.skip(reason='''ViT does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" pass def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A, A : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Optional[Any] = model_class(SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) A : List[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE , tf.keras.layers.Layer ) ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A, A : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : List[str] = model_class(SCREAMING_SNAKE_CASE ) A : List[str] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A : List[str] = [*signature.parameters.keys()] A : Optional[int] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE ) @slow def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Optional[Any] = TFViTModel.from_pretrained('''google/vit-base-patch16-224''' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_ ( ): '''simple docstring''' A : Optional[int] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class A ( unittest.TestCase ): @cached_property def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" return ViTImageProcessor.from_pretrained('''google/vit-base-patch16-224''' ) if is_vision_available() else None @slow def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Optional[Any] = TFViTForImageClassification.from_pretrained('''google/vit-base-patch16-224''' ) A : Dict = self.default_image_processor A : Optional[int] = prepare_img() A : Tuple = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='''tf''' ) # forward pass A : Union[str, Any] = model(**SCREAMING_SNAKE_CASE ) # verify the logits A : Dict = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE ) A : List[str] = tf.constant([-0.2_744, 0.8_215, -0.0_836] ) tf.debugging.assert_near(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 )
311
'''simple docstring''' from __future__ import annotations from random import random class A : def __init__( self , SCREAMING_SNAKE_CASE = None ) -> Tuple: """simple docstring""" A : Optional[Any] = value A : Any = random() A : Node | None = None A : Node | None = None def __repr__( self ) -> str: """simple docstring""" from pprint import pformat if self.left is None and self.right is None: return F'\'{self.value}: {self.prior:.5}\'' else: return pformat( {F'{self.value}: {self.prior:.5}': (self.left, self.right)} , indent=1 ) def __str__( self ) -> str: """simple docstring""" A : Optional[Any] = str(self.value ) + ''' ''' A : Union[str, Any] = str(self.left or '''''' ) A : Any = str(self.right or '''''' ) return value + left + right def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: A, A : Any = split(root.left , snake_case__ ) return left, root else: A, A : Optional[int] = split(root.right , snake_case__ ) return root, right def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: A : List[str] = merge(left.right , snake_case__ ) return left else: A : Tuple = merge(snake_case__ , right.left ) return right def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : List[Any] = Node(snake_case__ ) A, A : Tuple = split(snake_case__ , snake_case__ ) return merge(merge(snake_case__ , snake_case__ ) , snake_case__ ) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A, A : Dict = split(snake_case__ , value - 1 ) A, A : Any = split(snake_case__ , snake_case__ ) return merge(snake_case__ , snake_case__ ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if not root: # None return else: inorder(root.left ) print(root.value , end=''',''' ) inorder(root.right ) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' for arg in args.split(): if arg[0] == "+": A : int = insert(snake_case__ , int(arg[1:] ) ) elif arg[0] == "-": A : int = erase(snake_case__ , int(arg[1:] ) ) else: print('''Unknown command''' ) return root def lowerCAmelCase_ ( ): '''simple docstring''' A : Union[str, Any] = None print( '''enter numbers to create a tree, + value to add value into treap, ''' '''- value to erase all nodes with value. \'q\' to quit. ''' ) A : Optional[int] = input() while args != "q": A : str = interact_treap(snake_case__ , snake_case__ ) print(snake_case__ ) A : Union[str, Any] = input() print('''good by!''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
311
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase : int = logging.get_logger(__name__) lowercase : List[str] = { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json', 'google/bigbird-roberta-large': 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json', 'google/bigbird-base-trivia-itc': 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json', # See all BigBird models at https://huggingface.co/models?filter=big_bird } class A ( __snake_case ): __magic_name__ = '''big_bird''' def __init__( self , SCREAMING_SNAKE_CASE=50358 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=4096 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-12 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=66 , SCREAMING_SNAKE_CASE="block_sparse" , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE , ) -> Dict: """simple docstring""" super().__init__( pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , sep_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) A : List[Any] = vocab_size A : Tuple = max_position_embeddings A : str = hidden_size A : List[str] = num_hidden_layers A : Optional[Any] = num_attention_heads A : Any = intermediate_size A : List[str] = hidden_act A : Optional[int] = hidden_dropout_prob A : Optional[Any] = attention_probs_dropout_prob A : Any = initializer_range A : Optional[Any] = type_vocab_size A : Tuple = layer_norm_eps A : Union[str, Any] = use_cache A : str = rescale_embeddings A : int = attention_type A : int = use_bias A : Tuple = block_size A : Dict = num_random_blocks A : List[str] = classifier_dropout class A ( __snake_case ): @property def __lowerCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": A : List[str] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: A : Optional[int] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
311
'''simple docstring''' import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=sys.maxsize ) -> Union[str, Any]: """simple docstring""" A : Tuple = '''bilinear''' A : Optional[int] = max_size A : Dict = short_edge_length def __call__( self , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : Tuple = [] for img in imgs: A, A : str = img.shape[:2] # later: provide list and randomly choose index for resize A : Union[str, Any] = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img A : int = size * 1.0 / min(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if h < w: A, A : Tuple = size, scale * w else: A, A : str = scale * h, size if max(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) > self.max_size: A : List[str] = self.max_size * 1.0 / max(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Tuple = newh * scale A : int = neww * scale A : List[str] = int(neww + 0.5 ) A : int = int(newh + 0.5 ) if img.dtype == np.uinta: A : Dict = Image.fromarray(SCREAMING_SNAKE_CASE ) A : Optional[Any] = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) A : str = np.asarray(SCREAMING_SNAKE_CASE ) else: A : Dict = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw A : List[Any] = nn.functional.interpolate( SCREAMING_SNAKE_CASE , (newh, neww) , mode=self.interp_method , align_corners=SCREAMING_SNAKE_CASE ).squeeze(0 ) img_augs.append(SCREAMING_SNAKE_CASE ) return img_augs class A : def __init__( self , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" A : Any = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) A : str = cfg.INPUT.FORMAT A : int = cfg.SIZE_DIVISIBILITY A : Optional[int] = cfg.PAD_VALUE A : Dict = cfg.INPUT.MAX_SIZE_TEST A : Optional[Any] = cfg.MODEL.DEVICE A : Dict = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) A : Tuple = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) A : str = lambda SCREAMING_SNAKE_CASE : (x - self.pixel_mean) / self.pixel_std def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" A : Union[str, Any] = tuple(max(SCREAMING_SNAKE_CASE ) for s in zip(*[img.shape for img in images] ) ) A : List[str] = [im.shape[-2:] for im in images] A : Optional[Any] = [ nn.functional.pad( SCREAMING_SNAKE_CASE , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ] return torch.stack(SCREAMING_SNAKE_CASE ), torch.tensor(SCREAMING_SNAKE_CASE ) def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ) -> Union[str, Any]: """simple docstring""" with torch.no_grad(): if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : str = [images] if single_image: assert len(SCREAMING_SNAKE_CASE ) == 1 for i in range(len(SCREAMING_SNAKE_CASE ) ): if isinstance(images[i] , torch.Tensor ): images.insert(SCREAMING_SNAKE_CASE , images.pop(SCREAMING_SNAKE_CASE ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( SCREAMING_SNAKE_CASE , torch.as_tensor(img_tensorize(images.pop(SCREAMING_SNAKE_CASE ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge A : Tuple = torch.tensor([im.shape[:2] for im in images] ) A : Dict = self.aug(SCREAMING_SNAKE_CASE ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic A : Tuple = [self.normalizer(SCREAMING_SNAKE_CASE ) for x in images] # now pad them to do the following operations A, A : Optional[int] = self.pad(SCREAMING_SNAKE_CASE ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad A : Tuple = torch.true_divide(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' assert torch.isfinite(snake_case__ ).all(), "Box tensor contains infinite or NaN!" A, A : str = box_size tensor[:, 0].clamp_(min=0 , max=snake_case__ ) tensor[:, 1].clamp_(min=0 , max=snake_case__ ) tensor[:, 2].clamp_(min=0 , max=snake_case__ ) tensor[:, 3].clamp_(min=0 , max=snake_case__ )
311
1
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig 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 ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=30 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=2 , ) -> List[str]: """simple docstring""" A : List[str] = parent A : Optional[Any] = batch_size A : Tuple = image_size A : int = patch_size A : Optional[int] = num_channels A : str = is_training A : List[Any] = use_labels A : Any = hidden_size A : Any = num_hidden_layers A : Optional[int] = num_attention_heads A : Any = intermediate_size A : List[str] = hidden_act A : str = hidden_dropout_prob A : Tuple = attention_probs_dropout_prob A : Any = type_sequence_label_size A : Optional[int] = initializer_range A : Dict = scope A : Tuple = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) A : List[Any] = (image_size // patch_size) ** 2 A : Tuple = num_patches + 2 def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A : Tuple = None if self.use_labels: A : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Tuple = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" return DeiTConfig( 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=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : Any = TFDeiTModel(config=SCREAMING_SNAKE_CASE ) A : str = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" A : Tuple = TFDeiTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE ) A : List[Any] = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A : Optional[int] = 1 A : str = TFDeiTForMaskedImageModeling(SCREAMING_SNAKE_CASE ) A : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Tuple = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" A : str = self.type_sequence_label_size A : Optional[Any] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE ) A : Optional[Any] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images A : Optional[Any] = 1 A : List[str] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE ) A : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Optional[int] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Optional[int] = self.prepare_config_and_inputs() A, A, A : Tuple = config_and_inputs A : Any = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class A ( __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) __magic_name__ = ( { '''feature-extraction''': TFDeiTModel, '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) __magic_name__ = False __magic_name__ = False __magic_name__ = False __magic_name__ = False def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = TFDeiTModelTester(self ) A : Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''DeiT does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" pass def __lowerCAmelCase ( self ) -> str: """simple docstring""" A, A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) A : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE , tf.keras.layers.Dense ) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A, A : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) A : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A : Union[str, Any] = [*signature.parameters.keys()] A : List[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ) -> Tuple: """simple docstring""" A : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def __lowerCAmelCase ( self ) -> str: """simple docstring""" for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A : List[str] = TFDeiTModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_ ( ): '''simple docstring''' A : str = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class A ( unittest.TestCase ): @cached_property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) if is_vision_available() else None ) @slow def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Union[str, Any] = TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) A : Dict = self.default_image_processor A : List[str] = prepare_img() A : Any = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='''tf''' ) # forward pass A : Optional[int] = model(**SCREAMING_SNAKE_CASE ) # verify the logits A : List[Any] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE ) A : str = tf.constant([-1.0_266, 0.1_912, -1.2_861] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
'''simple docstring''' import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": lowercase : Tuple = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml parser.add_argument( '--original_config_file', default=None, type=str, 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( '--scheduler_type', default='pndm', type=str, help='Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']', ) parser.add_argument( '--pipeline_type', default=None, type=str, help=( 'The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\'' '. If `None` pipeline will be automatically inferred.' ), ) parser.add_argument( '--image_size', default=None, 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( '--prediction_type', default=None, type=str, help=( 'The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable' ' Diffusion v2 Base. Use \'v_prediction\' 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.)') parser.add_argument( '--stable_unclip', type=str, default=None, required=False, help='Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.', ) parser.add_argument( '--stable_unclip_prior', type=str, default=None, required=False, help='Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.', ) parser.add_argument( '--clip_stats_path', type=str, help='Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.', required=False, ) parser.add_argument( '--controlnet', action='store_true', default=None, help='Set flag if this is a controlnet checkpoint.' ) parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--vae_path', type=str, default=None, required=False, help='Set to a path, hub id to an already converted vae to not convert it again.', ) lowercase : Tuple = parser.parse_args() lowercase : Union[str, Any] = download_from_original_stable_diffusion_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, prediction_type=args.prediction_type, model_type=args.pipeline_type, extract_ema=args.extract_ema, scheduler_type=args.scheduler_type, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, stable_unclip=args.stable_unclip, stable_unclip_prior=args.stable_unclip_prior, clip_stats_path=args.clip_stats_path, controlnet=args.controlnet, vae_path=args.vae_path, ) if args.half: pipe.to(torch_dtype=torch.floataa) if args.controlnet: # only save the controlnet model pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) else: pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
311
1
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig 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 TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=[10, 20, 30, 40] , SCREAMING_SNAKE_CASE=[1, 1, 2, 1] , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE="relu" , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=None , ) -> str: """simple docstring""" A : List[str] = parent A : Tuple = batch_size A : List[Any] = image_size A : int = num_channels A : Any = embeddings_size A : List[str] = hidden_sizes A : List[Any] = depths A : Any = is_training A : List[str] = use_labels A : List[str] = hidden_act A : Optional[int] = num_labels A : List[Any] = scope A : Union[str, Any] = len(SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A : Optional[Any] = None if self.use_labels: A : Union[str, Any] = ids_tensor([self.batch_size] , self.num_labels ) A : Union[str, Any] = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" A : List[Any] = TFResNetModel(config=SCREAMING_SNAKE_CASE ) A : int = model(SCREAMING_SNAKE_CASE ) # 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 __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" A : List[str] = self.num_labels A : int = TFResNetForImageClassification(SCREAMING_SNAKE_CASE ) A : List[Any] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Union[str, Any] = self.prepare_config_and_inputs() A, A, A : List[Any] = config_and_inputs A : List[str] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class A ( __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () __magic_name__ = ( {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification} if is_tf_available() else {} ) __magic_name__ = False __magic_name__ = False __magic_name__ = False __magic_name__ = False __magic_name__ = False def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : str = TFResNetModelTester(self ) A : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """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 __lowerCAmelCase ( self ) -> Any: """simple docstring""" return @unittest.skip(reason='''ResNet does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" pass @unittest.skip(reason='''ResNet does not support input and output embeddings''' ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" pass def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A, A : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) A : int = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A : Optional[Any] = [*signature.parameters.keys()] A : Tuple = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" def check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : int = model_class(SCREAMING_SNAKE_CASE ) A : Optional[int] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) A : Optional[int] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states A : Dict = self.model_tester.num_stages self.assertEqual(len(SCREAMING_SNAKE_CASE ) , expected_num_stages + 1 ) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) A, A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() A : str = ['''basic''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: A : Tuple = layer_type A : str = True check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A : List[str] = True check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE ) @slow def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A : Tuple = TFResNetModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_ ( ): '''simple docstring''' A : Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class A ( unittest.TestCase ): @cached_property def __lowerCAmelCase ( self ) -> int: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Dict = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) A : str = self.default_image_processor A : Tuple = prepare_img() A : Any = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='''tf''' ) # forward pass A : List[Any] = model(**SCREAMING_SNAKE_CASE ) # verify the logits A : Dict = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE ) A : Union[str, Any] = tf.constant([-11.1_069, -9.7_877, -8.3_777] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal lowercase : str = datasets.utils.logging.get_logger(__name__) lowercase : Union[str, Any] = ['names', 'prefix'] lowercase : Union[str, Any] = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] lowercase : List[Any] = ['encoding_errors', 'on_bad_lines'] lowercase : Any = ['date_format'] @dataclass class A ( datasets.BuilderConfig ): __magic_name__ = "," __magic_name__ = None __magic_name__ = "infer" __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = False __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = True __magic_name__ = False __magic_name__ = True __magic_name__ = None __magic_name__ = "." __magic_name__ = None __magic_name__ = '"' __magic_name__ = 0 __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = True __magic_name__ = 0 __magic_name__ = True __magic_name__ = False __magic_name__ = None __magic_name__ = 10000 __magic_name__ = None __magic_name__ = "strict" __magic_name__ = "error" __magic_name__ = None def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" if self.delimiter is not None: A : Optional[Any] = self.delimiter if self.column_names is not None: A : Optional[Any] = self.column_names @property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : str = { '''sep''': self.sep, '''header''': self.header, '''names''': self.names, '''index_col''': self.index_col, '''usecols''': self.usecols, '''prefix''': self.prefix, '''mangle_dupe_cols''': self.mangle_dupe_cols, '''engine''': self.engine, '''converters''': self.converters, '''true_values''': self.true_values, '''false_values''': self.false_values, '''skipinitialspace''': self.skipinitialspace, '''skiprows''': self.skiprows, '''nrows''': self.nrows, '''na_values''': self.na_values, '''keep_default_na''': self.keep_default_na, '''na_filter''': self.na_filter, '''verbose''': self.verbose, '''skip_blank_lines''': self.skip_blank_lines, '''thousands''': self.thousands, '''decimal''': self.decimal, '''lineterminator''': self.lineterminator, '''quotechar''': self.quotechar, '''quoting''': self.quoting, '''escapechar''': self.escapechar, '''comment''': self.comment, '''encoding''': self.encoding, '''dialect''': self.dialect, '''error_bad_lines''': self.error_bad_lines, '''warn_bad_lines''': self.warn_bad_lines, '''skipfooter''': self.skipfooter, '''doublequote''': self.doublequote, '''memory_map''': self.memory_map, '''float_precision''': self.float_precision, '''chunksize''': self.chunksize, '''encoding_errors''': self.encoding_errors, '''on_bad_lines''': self.on_bad_lines, '''date_format''': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , SCREAMING_SNAKE_CASE ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class A ( datasets.ArrowBasedBuilder ): __magic_name__ = CsvConfig def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) A : int = dl_manager.download_and_extract(self.config.data_files ) if isinstance(SCREAMING_SNAKE_CASE , (str, list, tuple) ): A : str = data_files if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : int = [files] A : Optional[int] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] A : Tuple = [] for split_name, files in data_files.items(): if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : List[str] = [files] A : List[str] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE ) for file in files] splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE , gen_kwargs={'''files''': files} ) ) return splits def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> pa.Table: """simple docstring""" if self.config.features is not None: A : Optional[int] = self.config.features.arrow_schema if all(not require_storage_cast(SCREAMING_SNAKE_CASE ) for feature in self.config.features.values() ): # cheaper cast A : List[Any] = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=SCREAMING_SNAKE_CASE ) else: # more expensive cast; allows str <-> int/float or str to Audio for example A : int = table_cast(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return pa_table def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" A : Union[str, Any] = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str A : int = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(SCREAMING_SNAKE_CASE ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE ) ): A : Union[str, Any] = pd.read_csv(SCREAMING_SNAKE_CASE , iterator=SCREAMING_SNAKE_CASE , dtype=SCREAMING_SNAKE_CASE , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(SCREAMING_SNAKE_CASE ): A : Dict = pa.Table.from_pandas(SCREAMING_SNAKE_CASE ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE ) except ValueError as e: logger.error(F'Failed to read file \'{file}\' with error {type(SCREAMING_SNAKE_CASE )}: {e}' ) raise
311
1
'''simple docstring''' from math import isclose, sqrt def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : List[Any] = point_y / 4 / point_x A : List[str] = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) A : Tuple = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) A : List[str] = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 A : str = outgoing_gradient**2 + 4 A : List[str] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) A : str = (point_y - outgoing_gradient * point_x) ** 2 - 100 A : List[Any] = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) A : int = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point A : Any = x_minus if isclose(snake_case__ , snake_case__ ) else x_plus A : Dict = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def lowerCAmelCase_ ( snake_case__ = 1.4 , snake_case__ = -9.6 ): '''simple docstring''' A : int = 0 A : float = first_x_coord A : float = first_y_coord A : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): A, A, A : Union[str, Any] = next_point(snake_case__ , snake_case__ , snake_case__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f'''{solution() = }''')
311
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : int = logging.get_logger(__name__) lowercase : int = { 'asapp/sew-tiny-100k': 'https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json', # See all SEW models at https://huggingface.co/models?filter=sew } class A ( __snake_case ): __magic_name__ = '''sew''' def __init__( self , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-5 , SCREAMING_SNAKE_CASE="group" , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , SCREAMING_SNAKE_CASE=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=0.05 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE="mean" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=256 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=2 , **SCREAMING_SNAKE_CASE , ) -> Tuple: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE , pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE ) A : Optional[Any] = hidden_size A : Any = feat_extract_norm A : Optional[int] = feat_extract_activation A : Tuple = list(SCREAMING_SNAKE_CASE ) A : List[str] = list(SCREAMING_SNAKE_CASE ) A : List[str] = list(SCREAMING_SNAKE_CASE ) A : int = conv_bias A : List[Any] = num_conv_pos_embeddings A : Tuple = num_conv_pos_embedding_groups A : int = len(self.conv_dim ) A : Dict = num_hidden_layers A : Optional[int] = intermediate_size A : Any = squeeze_factor A : int = hidden_act A : str = num_attention_heads A : Dict = hidden_dropout A : Optional[Any] = attention_dropout A : List[str] = activation_dropout A : Union[str, Any] = feat_proj_dropout A : Union[str, Any] = final_dropout A : int = layerdrop A : Optional[Any] = layer_norm_eps A : Any = initializer_range A : Tuple = vocab_size 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)`,''' F'but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)' F'= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 A : Optional[Any] = apply_spec_augment A : Optional[Any] = mask_time_prob A : Union[str, Any] = mask_time_length A : Optional[Any] = mask_time_min_masks A : str = mask_feature_prob A : Tuple = mask_feature_length A : Any = mask_feature_min_masks # ctc loss A : List[Any] = ctc_loss_reduction A : Dict = ctc_zero_infinity # sequence classification A : int = use_weighted_layer_sum A : Optional[int] = classifier_proj_size @property def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
311
1
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin lowercase : Union[str, Any] = get_tests_dir('fixtures/test_sentencepiece.model') lowercase : Dict = {'target_lang': 'fi', 'source_lang': 'en'} lowercase : int = '>>zh<<' lowercase : Union[str, Any] = 'Helsinki-NLP/' if is_torch_available(): lowercase : str = 'pt' elif is_tf_available(): lowercase : Union[str, Any] = 'tf' else: lowercase : List[str] = 'jax' @require_sentencepiece class A ( __snake_case , unittest.TestCase ): __magic_name__ = MarianTokenizer __magic_name__ = False __magic_name__ = True def __lowerCAmelCase ( self ) -> Any: """simple docstring""" super().setUp() A : Union[str, Any] = ['''</s>''', '''<unk>''', '''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''', '''\u0120''', '''<pad>'''] A : Dict = dict(zip(SCREAMING_SNAKE_CASE , range(len(SCREAMING_SNAKE_CASE ) ) ) ) A : Union[str, Any] = Path(self.tmpdirname ) save_json(SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES['''vocab'''] ) save_json(SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES['''tokenizer_config_file'''] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES['''source_spm'''] ) copyfile(SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES['''target_spm'''] ) A : Dict = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> MarianTokenizer: """simple docstring""" return MarianTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" return ( "This is a test", "This is a test", ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Tuple = '''</s>''' A : Union[str, Any] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''</s>''' ) self.assertEqual(vocab_keys[1] , '''<unk>''' ) self.assertEqual(vocab_keys[-1] , '''<pad>''' ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , 9 ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : str = MarianTokenizer.from_pretrained(F'{ORG_NAME}opus-mt-en-de' ) A : str = en_de_tokenizer(['''I am a small frog'''] , return_tensors=SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : List[Any] = [38, 121, 14, 697, 38848, 0] self.assertListEqual(SCREAMING_SNAKE_CASE , batch.input_ids[0] ) A : Union[str, Any] = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE ) A : List[Any] = [x.name for x in Path(SCREAMING_SNAKE_CASE ).glob('''*''' )] self.assertIn('''source.spm''' , SCREAMING_SNAKE_CASE ) MarianTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : List[Any] = self.get_tokenizer() A : Any = tok( ['''I am a small frog''' * 1000, '''I am a small frog'''] , padding=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertEqual(batch.input_ids.shape , (2, 512) ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Dict = self.get_tokenizer() A : List[str] = tok(['''I am a tiny frog''', '''I am a small frog'''] , padding=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Optional[Any] = {'''input_ids''': [[43495, 462, 20, 42164, 1369, 52, 464, 132, 1703, 492, 13, 7491, 38999, 6, 8, 464, 132, 1703, 492, 13, 4669, 37867, 13, 7525, 27, 1593, 988, 13, 33972, 7029, 6, 20, 8251, 383, 2, 270, 5866, 3788, 2, 2353, 8251, 12338, 2, 13958, 387, 2, 3629, 6953, 188, 2900, 2, 13958, 8011, 11501, 23, 8460, 4073, 34009, 20, 435, 11439, 27, 8, 8460, 4073, 6004, 20, 9988, 375, 27, 33, 266, 1945, 1076, 1350, 37867, 3288, 5, 577, 1076, 4374, 8, 5082, 5, 26453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 10767, 6, 316, 304, 4239, 3, 0], [148, 15722, 19, 1839, 12, 1350, 13, 22327, 5082, 5418, 47567, 35938, 59, 318, 19552, 108, 2183, 54, 14976, 4835, 32, 547, 1114, 8, 315, 2417, 5, 92, 19088, 3, 0, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100], [36, 6395, 12570, 39147, 11597, 6, 266, 4, 45405, 7296, 3, 0, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100]], '''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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE , model_name='''Helsinki-NLP/opus-mt-en-de''' , revision='''1a8c2263da11e68e50938f97e10cd57820bd504c''' , decode_kwargs={'''use_source_tokenizer''': True} , ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : str = MarianTokenizer.from_pretrained('''hf-internal-testing/test-marian-two-vocabs''' ) A : Tuple = '''Tämä on testi''' A : str = '''This is a test''' A : Tuple = [76, 7, 2047, 2] A : List[Any] = [69, 12, 11, 940, 2] A : Optional[int] = tokenizer(SCREAMING_SNAKE_CASE ).input_ids self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Dict = tokenizer(text_target=SCREAMING_SNAKE_CASE ).input_ids self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : List[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
311
'''simple docstring''' import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Dict = SwinConfig() A : List[Any] = swin_name.split('''_''' ) A : Tuple = name_split[1] A : Union[str, Any] = int(name_split[4] ) A : str = int(name_split[3][-1] ) if model_size == "tiny": A : Optional[int] = 96 A : Optional[Any] = (2, 2, 6, 2) A : Any = (3, 6, 12, 24) elif model_size == "small": A : Optional[int] = 96 A : str = (2, 2, 18, 2) A : Tuple = (3, 6, 12, 24) elif model_size == "base": A : int = 128 A : Optional[Any] = (2, 2, 18, 2) A : List[str] = (4, 8, 16, 32) else: A : Dict = 192 A : Optional[Any] = (2, 2, 18, 2) A : Optional[Any] = (6, 12, 24, 48) if "in22k" in swin_name: A : Dict = 2_1841 else: A : str = 1000 A : List[str] = '''huggingface/label-files''' A : Any = '''imagenet-1k-id2label.json''' A : Any = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='''dataset''' ) , '''r''' ) ) A : str = {int(snake_case__ ): v for k, v in idalabel.items()} A : Tuple = idalabel A : Tuple = {v: k for k, v in idalabel.items()} A : Tuple = img_size A : Dict = num_classes A : Optional[Any] = embed_dim A : str = depths A : str = num_heads A : Optional[int] = window_size return config def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if "patch_embed.proj" in name: A : Any = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: A : Tuple = name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: A : Optional[int] = '''encoder.''' + name if "attn.proj" in name: A : List[str] = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: A : List[str] = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: A : Any = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: A : Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: A : Dict = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: A : str = name.replace('''mlp.fc2''' , '''output.dense''' ) if name == "norm.weight": A : Tuple = '''layernorm.weight''' if name == "norm.bias": A : Tuple = '''layernorm.bias''' if "head" in name: A : Any = name.replace('''head''' , '''classifier''' ) else: A : List[Any] = '''swin.''' + name return name def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' for key in orig_state_dict.copy().keys(): A : Dict = orig_state_dict.pop(snake_case__ ) if "mask" in key: continue elif "qkv" in key: A : Dict = key.split('''.''' ) A : Optional[int] = int(key_split[1] ) A : List[str] = int(key_split[3] ) A : Optional[int] = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: A : Any = val[:dim, :] A : Dict = val[ dim : dim * 2, : ] A : List[str] = val[-dim:, :] else: A : Any = val[ :dim ] A : Optional[int] = val[ dim : dim * 2 ] A : Any = val[ -dim: ] else: A : str = val return orig_state_dict def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : Tuple = timm.create_model(snake_case__ , pretrained=snake_case__ ) timm_model.eval() A : Optional[Any] = get_swin_config(snake_case__ ) A : Optional[int] = SwinForImageClassification(snake_case__ ) model.eval() A : List[str] = convert_state_dict(timm_model.state_dict() , snake_case__ ) model.load_state_dict(snake_case__ ) A : Optional[int] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' A : Any = AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swin_name.replace('''_''' , '''-''' ) ) ) A : List[Any] = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) A : List[Any] = image_processor(images=snake_case__ , return_tensors='''pt''' ) A : Any = timm_model(inputs['''pixel_values'''] ) A : Optional[Any] = model(**snake_case__ ).logits assert torch.allclose(snake_case__ , snake_case__ , atol=1E-3 ) print(F'Saving model {swin_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case__ ) if __name__ == "__main__": lowercase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swin_name', default='swin_tiny_patch4_window7_224', type=str, help='Name of the Swin timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) lowercase : int = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
311
1
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A, A : Optional[int] = image.size A, A : Any = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 A : Union[str, Any] = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) A : Optional[Any] = np.array(snake_case__ ).astype(np.floataa ) / 2_55.0 A : int = image[None].transpose(0 , 3 , 1 , 2 ) A : Optional[Any] = torch.from_numpy(snake_case__ ) return 2.0 * image - 1.0 class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__() self.register_modules(vqvae=SCREAMING_SNAKE_CASE , unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = 100 , SCREAMING_SNAKE_CASE = 0.0 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = "pil" , SCREAMING_SNAKE_CASE = True , ) -> Union[Tuple, ImagePipelineOutput]: """simple docstring""" if isinstance(SCREAMING_SNAKE_CASE , PIL.Image.Image ): A : Tuple = 1 elif isinstance(SCREAMING_SNAKE_CASE , torch.Tensor ): A : Optional[int] = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE )}' ) if isinstance(SCREAMING_SNAKE_CASE , PIL.Image.Image ): A : List[str] = preprocess(SCREAMING_SNAKE_CASE ) A, A : Dict = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image A : Dict = (batch_size, self.unet.config.in_channels // 2, height, width) A : Tuple = next(self.unet.parameters() ).dtype A : List[Any] = randn_tensor(SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , device=self.device , dtype=SCREAMING_SNAKE_CASE ) A : Union[str, Any] = image.to(device=self.device , dtype=SCREAMING_SNAKE_CASE ) # set timesteps and move to the correct device self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE , device=self.device ) A : Dict = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler A : List[str] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] A : Dict = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) A : Dict = {} if accepts_eta: A : Union[str, Any] = eta for t in self.progress_bar(SCREAMING_SNAKE_CASE ): # concat latents and low resolution image in the channel dimension. A : Optional[Any] = torch.cat([latents, image] , dim=1 ) A : str = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # predict the noise residual A : List[Any] = self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).sample # compute the previous noisy sample x_t -> x_t-1 A : Tuple = self.scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample # decode the image latents with the VQVAE A : List[Any] = self.vqvae.decode(SCREAMING_SNAKE_CASE ).sample A : List[Any] = torch.clamp(SCREAMING_SNAKE_CASE , -1.0 , 1.0 ) A : Tuple = image / 2 + 0.5 A : Any = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": A : Optional[Any] = self.numpy_to_pil(SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE )
311
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : Optional[int] = logging.get_logger(__name__) lowercase : Tuple = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class A ( __snake_case ): __magic_name__ = '''pix2struct_text_model''' __magic_name__ = ['''past_key_values'''] __magic_name__ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , SCREAMING_SNAKE_CASE=50244 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Optional[Any]: """simple docstring""" A : str = vocab_size A : List[str] = hidden_size A : List[Any] = d_kv A : Optional[Any] = d_ff A : Dict = num_layers A : Dict = num_heads A : Optional[int] = relative_attention_num_buckets A : Optional[Any] = relative_attention_max_distance A : Dict = dropout_rate A : Dict = layer_norm_epsilon A : Tuple = initializer_factor A : Union[str, Any] = use_cache A : int = eos_token_id A : List[str] = decoder_start_token_id # for backwards compatibility A : int = dense_act_fn super().__init__( pad_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , decoder_start_token_id=SCREAMING_SNAKE_CASE , tie_word_embeddings=SCREAMING_SNAKE_CASE , is_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) A, A : Optional[Any] = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": A : Union[str, Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A ( __snake_case ): __magic_name__ = '''pix2struct_vision_model''' def __init__( self , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=1e-10 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=4096 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=128 , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) A : List[str] = hidden_size A : Optional[Any] = patch_embed_hidden_size A : Union[str, Any] = d_ff A : Dict = dropout_rate A : str = num_hidden_layers A : Dict = num_attention_heads A : Tuple = initializer_range A : List[str] = initializer_factor A : Union[str, Any] = attention_dropout A : Tuple = layer_norm_eps A : int = dense_act_fn A : Optional[int] = seq_len A : Tuple = relative_attention_num_buckets A : str = relative_attention_max_distance A : Optional[Any] = d_kv @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) A, A : int = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": A : Optional[Any] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A ( __snake_case ): __magic_name__ = '''pix2struct''' __magic_name__ = True def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(tie_word_embeddings=SCREAMING_SNAKE_CASE , is_encoder_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) if text_config is None: A : Dict = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: A : str = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) A : Dict = PixaStructTextConfig(**SCREAMING_SNAKE_CASE ) A : Any = PixaStructVisionConfig(**SCREAMING_SNAKE_CASE ) A : Any = self.text_config.decoder_start_token_id A : Any = self.text_config.pad_token_id A : Dict = self.text_config.eos_token_id A : Union[str, Any] = initializer_factor A : Tuple = initializer_range A : Optional[Any] = self.initializer_range A : int = self.initializer_range A : Tuple = is_vqa @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Tuple = copy.deepcopy(self.__dict__ ) A : Dict = self.text_config.to_dict() A : int = self.vision_config.to_dict() A : Any = self.__class__.model_type return output
311
1
'''simple docstring''' from collections import defaultdict class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : List[str] = total # total no of tasks (N) # DP table will have a dimension of (2^M)*N # initially all values are set to -1 A : int = [ [-1 for i in range(total + 1 )] for j in range(2 ** len(SCREAMING_SNAKE_CASE ) ) ] A : Optional[int] = defaultdict(SCREAMING_SNAKE_CASE ) # stores the list of persons for each task # final_mask is used to check if all persons are included by setting all bits # to 1 A : Dict = (1 << len(SCREAMING_SNAKE_CASE )) - 1 def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" if mask == self.final_mask: return 1 # if not everyone gets the task and no more tasks are available, return 0 if task_no > self.total_tasks: return 0 # if case already considered if self.dp[mask][task_no] != -1: return self.dp[mask][task_no] # Number of ways when we don't this task in the arrangement A : Any = self.count_ways_until(SCREAMING_SNAKE_CASE , task_no + 1 ) # now assign the tasks one by one to all possible persons and recursively # assign for the remaining tasks. if task_no in self.task: for p in self.task[task_no]: # if p is already given a task if mask & (1 << p): continue # assign this task to p and change the mask value. And recursively # assign tasks with the new mask value. total_ways_util += self.count_ways_until(mask | (1 << p) , task_no + 1 ) # save the value. A : Optional[Any] = total_ways_util return self.dp[mask][task_no] def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" for i in range(len(SCREAMING_SNAKE_CASE ) ): for j in task_performed[i]: self.task[j].append(SCREAMING_SNAKE_CASE ) # call the function to fill the DP table, final answer is stored in dp[0][1] return self.count_ways_until(0 , 1 ) if __name__ == "__main__": lowercase : Optional[Any] = 5 # total no of tasks (the value of N) # the list of tasks that can be done by M persons. lowercase : Union[str, Any] = [[1, 3, 4], [1, 2, 5], [3, 4]] print( AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( task_performed ) )
311
'''simple docstring''' from __future__ import annotations def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : List[str] = 2 A : Dict = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(snake_case__ ) if n > 1: factors.append(snake_case__ ) return factors if __name__ == "__main__": import doctest doctest.testmod()
311
1
'''simple docstring''' import csv import tweepy # Twitter API credentials lowercase : str = '' lowercase : Dict = '' lowercase : Tuple = '' lowercase : Dict = '' def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Optional[Any] = tweepy.OAuthHandler(snake_case__ , snake_case__ ) auth.set_access_token(snake_case__ , snake_case__ ) A : List[str] = tweepy.API(snake_case__ ) # initialize a list to hold all the tweepy Tweets A : Any = [] # make initial request for most recent tweets (200 is the maximum allowed count) A : int = api.user_timeline(screen_name=snake_case__ , count=200 ) # save most recent tweets alltweets.extend(snake_case__ ) # save the id of the oldest tweet less one A : Dict = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(snake_case__ ) > 0: print(F'getting tweets before {oldest}' ) # all subsequent requests use the max_id param to prevent duplicates A : Optional[Any] = api.user_timeline( screen_name=snake_case__ , count=200 , max_id=snake_case__ ) # save most recent tweets alltweets.extend(snake_case__ ) # update the id of the oldest tweet less one A : Union[str, Any] = alltweets[-1].id - 1 print(F'...{len(snake_case__ )} tweets downloaded so far' ) # transform the tweepy tweets into a 2D array that will populate the csv A : Tuple = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F'new_{screen_name}_tweets.csv' , '''w''' ) as f: A : Union[str, Any] = csv.writer(snake_case__ ) writer.writerow(['''id''', '''created_at''', '''text'''] ) writer.writerows(snake_case__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets('FirePing32')
311
'''simple docstring''' # Function to print upper half of diamond (pyramid) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for i in range(0 , snake_case__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(''' ''' , end='''''' ) for _ in range(0 , i + 1 ): # printing stars print('''* ''' , end='''''' ) print() def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for i in range(snake_case__ , 0 , -1 ): for _ in range(snake_case__ , 0 , -1 ): # printing stars print('''* ''' , end='''''' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(''' ''' , end='''''' ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if n <= 0: print(''' ... .... nothing printing :(''' ) return floyd(snake_case__ ) # upper half reverse_floyd(snake_case__ ) # lower half if __name__ == "__main__": print(R'| /\ | |- | |- |--| |\ /| |-') print(R'|/ \| |- |_ |_ |__| | \/ | |_') lowercase : List[str] = 1 while K: lowercase : List[Any] = int(input('enter the number and , and see the magic : ')) print() pretty_print(user_number) lowercase : Any = int(input('press 0 to exit... and 1 to continue...')) print('Good Bye...')
311
1
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() lowercase : Dict = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__=False , snake_case__=True ): '''simple docstring''' if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) A, A, A, A : List[Any] = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: A : Dict = cached_file(snake_case__ , snake_case__ , force_download=not use_cached_models ) A : Optional[Any] = config_class.from_json_file(snake_case__ ) A : int = True A : Dict = True print(F'Building TensorFlow model from configuration: {config}' ) A : Tuple = model_class(snake_case__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): A : Union[str, Any] = cached_file( snake_case__ , snake_case__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: A : List[Any] = load_pytorch_checkpoint_in_tfa_model(snake_case__ , snake_case__ ) if compare_with_pt_model: A : int = tf_model(tf_model.dummy_inputs , training=snake_case__ ) # build the network A : List[Any] = torch.load(snake_case__ , map_location='''cpu''' ) A : Dict = pt_model_class.from_pretrained( pretrained_model_name_or_path=snake_case__ , config=snake_case__ , state_dict=snake_case__ ) with torch.no_grad(): A : Dict = pt_model(**pt_model.dummy_inputs ) A : Dict = pto[0].numpy() A : List[str] = tfo[0].numpy() A : Tuple = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(snake_case__ , save_format='''h5''' ) def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__=None , snake_case__=None , snake_case__=False , snake_case__=False , snake_case__=False , snake_case__=False , ): '''simple docstring''' if args_model_type is None: A : Dict = list(MODEL_CLASSES.keys() ) else: A : Optional[Any] = [args_model_type] for j, model_type in enumerate(snake_case__ , start=1 ): print('''=''' * 100 ) print(F' Converting model type {j}/{len(snake_case__ )}: {model_type}' ) print('''=''' * 100 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) A, A, A, A, A : Tuple = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: A : Tuple = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: A : Tuple = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(snake_case__ , snake_case__ ) , start=1 ): print('''-''' * 100 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue A : str = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(snake_case__ )}: {model_shortcut_name} - model_type {model_type}' ) print('''-''' * 100 ) if config_shortcut_name in aws_config_map: A : int = cached_file(snake_case__ , snake_case__ , force_download=not use_cached_models ) else: A : List[str] = config_shortcut_name if model_shortcut_name in aws_model_maps: A : Optional[Any] = cached_file(snake_case__ , snake_case__ , force_download=not use_cached_models ) else: A : Any = model_shortcut_name if os.path.isfile(snake_case__ ): A : Optional[Any] = '''converted_model''' convert_pt_checkpoint_to_tf( model_type=snake_case__ , pytorch_checkpoint_path=snake_case__ , config_file=snake_case__ , tf_dump_path=os.path.join(snake_case__ , model_shortcut_name + '''-tf_model.h5''' ) , compare_with_pt_model=snake_case__ , ) if remove_cached_files: os.remove(snake_case__ ) os.remove(snake_case__ ) if __name__ == "__main__": lowercase : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f'''Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and ''' 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') lowercase : Tuple = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
311
'''simple docstring''' # limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 50 , SCREAMING_SNAKE_CASE = "pil" , SCREAMING_SNAKE_CASE = True , **SCREAMING_SNAKE_CASE , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" A : List[Any] = torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=SCREAMING_SNAKE_CASE , ) A : Optional[Any] = image.to(self.device ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output A : Tuple = self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 A : List[Any] = self.scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample A : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) A : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": A : List[Any] = self.numpy_to_pil(SCREAMING_SNAKE_CASE ) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE ), "This is a local test"
311
1
'''simple docstring''' from __future__ import annotations def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Dict = str(snake_case__ ) return n == n[::-1] def lowerCAmelCase_ ( snake_case__ = 100_0000 ): '''simple docstring''' A : str = 0 for i in range(1 , snake_case__ ): if is_palindrome(snake_case__ ) and is_palindrome(bin(snake_case__ ).split('''b''' )[1] ): total += i return total if __name__ == "__main__": print(solution(int(str(input().strip()))))
311
'''simple docstring''' import unittest from transformers import BertGenerationConfig, 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 BertGenerationDecoder, BertGenerationEncoder class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=50 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=None , ) -> str: """simple docstring""" A : Any = parent A : List[Any] = batch_size A : Union[str, Any] = seq_length A : Any = is_training A : int = use_input_mask A : Union[str, Any] = vocab_size A : List[Any] = hidden_size A : List[Any] = num_hidden_layers A : Optional[int] = num_attention_heads A : str = intermediate_size A : Tuple = hidden_act A : Union[str, Any] = hidden_dropout_prob A : Union[str, Any] = attention_probs_dropout_prob A : int = max_position_embeddings A : Optional[int] = initializer_range A : Any = use_labels A : Optional[int] = scope def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Optional[int] = None if self.use_input_mask: A : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: A : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Dict = self.get_config() return config, input_ids, input_mask, token_labels def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" return BertGenerationConfig( 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 , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" ( ( A ), ( A ), ( A ), ( A ), ) : Any = self.prepare_config_and_inputs() A : Tuple = True A : int = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A : str = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" A : List[str] = BertGenerationEncoder(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) A : int = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> Union[str, Any]: """simple docstring""" A : List[str] = True A : Union[str, Any] = BertGenerationEncoder(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , ) A : List[Any] = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" A : Optional[Any] = True A : Tuple = True A : Optional[int] = BertGenerationDecoder(config=SCREAMING_SNAKE_CASE ).to(SCREAMING_SNAKE_CASE ).eval() # first forward pass A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , use_cache=SCREAMING_SNAKE_CASE , ) A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A : List[str] = ids_tensor((self.batch_size, 3) , config.vocab_size ) A : Tuple = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and A : Dict = torch.cat([input_ids, next_tokens] , dim=-1 ) A : List[str] = torch.cat([input_mask, next_mask] , dim=-1 ) A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE , )['''hidden_states'''][0] A : Any = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , past_key_values=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE , )['''hidden_states'''][0] # select random slice A : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() A : List[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() A : str = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" A : Optional[Any] = BertGenerationDecoder(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Optional[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A, A, A, A : Optional[int] = self.prepare_config_and_inputs() A : str = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class A ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () __magic_name__ = (BertGenerationDecoder,) if is_torch_available() else () __magic_name__ = ( {'''feature-extraction''': BertGenerationEncoder, '''text-generation''': BertGenerationDecoder} if is_torch_available() else {} ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : List[str] = BertGenerationEncoderTester(self ) A : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A, A, A, A : Tuple = self.model_tester.prepare_config_and_inputs() A : str = '''bert''' self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : int = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" ( ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ) : Tuple = self.model_tester.prepare_config_and_inputs_for_decoder() A : Union[str, Any] = None self.model_tester.create_and_check_model_as_decoder( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*SCREAMING_SNAKE_CASE ) @slow def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Optional[Any] = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) A : Optional[Any] = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]] ) with torch.no_grad(): A : Dict = model(SCREAMING_SNAKE_CASE )[0] A : Optional[Any] = torch.Size([1, 8, 1024] ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : Dict = torch.tensor( [[[0.1_775, 0.0_083, -0.0_321], [1.6_002, 0.1_287, 0.3_912], [2.1_473, 0.5_791, 0.6_066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[Any] = BertGenerationDecoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) A : Dict = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]] ) with torch.no_grad(): A : Optional[Any] = model(SCREAMING_SNAKE_CASE )[0] A : Optional[Any] = torch.Size([1, 8, 50358] ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : Any = torch.tensor( [[[-0.5_788, -2.5_994, -3.7_054], [0.0_438, 4.7_997, 1.8_795], [1.5_862, 6.6_409, 4.4_638]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowercase : Dict = { 'configuration_encodec': [ 'ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EncodecConfig', ], 'feature_extraction_encodec': ['EncodecFeatureExtractor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : str = [ 'ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST', 'EncodecModel', 'EncodecPreTrainedModel', ] if TYPE_CHECKING: from .configuration_encodec import ( ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP, EncodecConfig, ) from .feature_extraction_encodec import EncodecFeatureExtractor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encodec import ( ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST, EncodecModel, EncodecPreTrainedModel, ) else: import sys lowercase : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
311
'''simple docstring''' import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' return 1.0 / (1.0 + np.exp(-_outputs )) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Optional[int] = np.max(_outputs , axis=-1 , keepdims=snake_case__ ) A : Any = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=snake_case__ ) class A ( __snake_case ): __magic_name__ = '''sigmoid''' __magic_name__ = '''softmax''' __magic_name__ = '''none''' @add_end_docstrings( __snake_case , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class A ( __snake_case ): __magic_name__ = False __magic_name__ = ClassificationFunction.NONE def __init__( self , **SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE="" , **SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" A : Optional[Any] = tokenizer_kwargs A : int = {} if hasattr(self.model.config , '''return_all_scores''' ) and return_all_scores is None: A : int = self.model.config.return_all_scores if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) or top_k is None: A : Union[str, Any] = top_k A : Dict = False elif return_all_scores is not None: warnings.warn( '''`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of''' ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.''' , SCREAMING_SNAKE_CASE , ) if return_all_scores: A : Optional[int] = None else: A : Dict = 1 if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : Dict = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: A : int = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : str = super().__call__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. A : Any = '''top_k''' not in kwargs if isinstance(args[0] , SCREAMING_SNAKE_CASE ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Dict[str, GenericTensor]: """simple docstring""" A : List[Any] = self.framework if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): return self.tokenizer(**SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and len(SCREAMING_SNAKE_CASE ) == 1 and isinstance(inputs[0] , SCREAMING_SNAKE_CASE ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a''' ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.''' ) return self.tokenizer(SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" return self.model(**SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=True ) -> List[str]: """simple docstring""" if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: A : Optional[int] = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: A : Any = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , '''function_to_apply''' ) and function_to_apply is None: A : Optional[int] = self.model.config.function_to_apply else: A : Optional[int] = ClassificationFunction.NONE A : Any = model_outputs['''logits'''][0] A : List[Any] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: A : int = sigmoid(SCREAMING_SNAKE_CASE ) elif function_to_apply == ClassificationFunction.SOFTMAX: A : Any = softmax(SCREAMING_SNAKE_CASE ) elif function_to_apply == ClassificationFunction.NONE: A : int = outputs else: raise ValueError(F'Unrecognized `function_to_apply` argument: {function_to_apply}' ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} A : int = [ {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(SCREAMING_SNAKE_CASE ) ] if not _legacy: dict_scores.sort(key=lambda SCREAMING_SNAKE_CASE : x["score"] , reverse=SCREAMING_SNAKE_CASE ) if top_k is not None: A : Union[str, Any] = dict_scores[:top_k] return dict_scores
311
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : Optional[int] = logging.get_logger(__name__) lowercase : Tuple = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class A ( __snake_case ): __magic_name__ = '''pix2struct_text_model''' __magic_name__ = ['''past_key_values'''] __magic_name__ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , SCREAMING_SNAKE_CASE=50244 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Optional[Any]: """simple docstring""" A : str = vocab_size A : List[str] = hidden_size A : List[Any] = d_kv A : Optional[Any] = d_ff A : Dict = num_layers A : Dict = num_heads A : Optional[int] = relative_attention_num_buckets A : Optional[Any] = relative_attention_max_distance A : Dict = dropout_rate A : Dict = layer_norm_epsilon A : Tuple = initializer_factor A : Union[str, Any] = use_cache A : int = eos_token_id A : List[str] = decoder_start_token_id # for backwards compatibility A : int = dense_act_fn super().__init__( pad_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , decoder_start_token_id=SCREAMING_SNAKE_CASE , tie_word_embeddings=SCREAMING_SNAKE_CASE , is_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) A, A : Optional[Any] = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": A : Union[str, Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A ( __snake_case ): __magic_name__ = '''pix2struct_vision_model''' def __init__( self , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=1e-10 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=4096 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=128 , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) A : List[str] = hidden_size A : Optional[Any] = patch_embed_hidden_size A : Union[str, Any] = d_ff A : Dict = dropout_rate A : str = num_hidden_layers A : Dict = num_attention_heads A : Tuple = initializer_range A : List[str] = initializer_factor A : Union[str, Any] = attention_dropout A : Tuple = layer_norm_eps A : int = dense_act_fn A : Optional[int] = seq_len A : Tuple = relative_attention_num_buckets A : str = relative_attention_max_distance A : Optional[Any] = d_kv @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) A, A : int = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": A : Optional[Any] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A ( __snake_case ): __magic_name__ = '''pix2struct''' __magic_name__ = True def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(tie_word_embeddings=SCREAMING_SNAKE_CASE , is_encoder_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) if text_config is None: A : Dict = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: A : str = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) A : Dict = PixaStructTextConfig(**SCREAMING_SNAKE_CASE ) A : Any = PixaStructVisionConfig(**SCREAMING_SNAKE_CASE ) A : Any = self.text_config.decoder_start_token_id A : Any = self.text_config.pad_token_id A : Dict = self.text_config.eos_token_id A : Union[str, Any] = initializer_factor A : Tuple = initializer_range A : Optional[Any] = self.initializer_range A : int = self.initializer_range A : Tuple = is_vqa @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Tuple = copy.deepcopy(self.__dict__ ) A : Dict = self.text_config.to_dict() A : int = self.vision_config.to_dict() A : Any = self.__class__.model_type return output
311
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCAmelCase_ ( snake_case__ = "laptop" ): '''simple docstring''' A : Tuple = F'https://www.amazon.in/laptop/s?k={product}' A : Optional[int] = { '''User-Agent''': '''Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36''', '''Accept-Language''': '''en-US, en;q=0.5''', } A : Any = BeautifulSoup(requests.get(snake_case__ , headers=snake_case__ ).text ) # Initialize a Pandas dataframe with the column titles A : List[str] = DataFrame( columns=[ '''Product Title''', '''Product Link''', '''Current Price of the product''', '''Product Rating''', '''MRP of the product''', '''Discount''', ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( '''div''' , attrs={'''class''': '''s-result-item''', '''data-component-type''': '''s-search-result'''} , ) , soup.find_all('''div''' , attrs={'''class''': '''a-row a-size-base a-color-base'''} ) , ): try: A : Optional[Any] = item.ha.text A : Union[str, Any] = '''https://www.amazon.in/''' + item.ha.a['''href'''] A : Tuple = item.find('''span''' , attrs={'''class''': '''a-offscreen'''} ).text try: A : int = item.find('''span''' , attrs={'''class''': '''a-icon-alt'''} ).text except AttributeError: A : Optional[int] = '''Not available''' try: A : str = ( '''₹''' + item.find( '''span''' , attrs={'''class''': '''a-price a-text-price'''} ).text.split('''₹''' )[1] ) except AttributeError: A : List[Any] = '''''' try: A : Dict = float( ( ( float(product_mrp.strip('''₹''' ).replace(''',''' , '''''' ) ) - float(product_price.strip('''₹''' ).replace(''',''' , '''''' ) ) ) / float(product_mrp.strip('''₹''' ).replace(''',''' , '''''' ) ) ) * 100 ) except ValueError: A : str = float('''nan''' ) except AttributeError: pass A : Union[str, Any] = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] A : List[str] = ''' ''' A : Optional[Any] = ''' ''' data_frame.index += 1 return data_frame if __name__ == "__main__": lowercase : Union[str, Any] = 'headphones' get_amazon_product_data(product).to_csv(f'''Amazon Product Data for {product}.csv''')
311
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, ) lowercase : List[str] = logging.getLogger(__name__) lowercase : List[Any] = {'facebook/bart-base': BartForConditionalGeneration} lowercase : int = {'facebook/bart-base': BartTokenizer} def lowerCAmelCase_ ( ): '''simple docstring''' A : Optional[Any] = argparse.ArgumentParser(description='''Export Bart model + Beam Search to ONNX graph.''' ) parser.add_argument( '''--validation_file''' , type=snake_case__ , default=snake_case__ , help='''A csv or a json file containing the validation data.''' ) parser.add_argument( '''--max_length''' , type=snake_case__ , default=5 , help='''The maximum total input sequence length after tokenization.''' , ) parser.add_argument( '''--num_beams''' , type=snake_case__ , default=snake_case__ , 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=snake_case__ , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=snake_case__ , ) parser.add_argument( '''--config_name''' , type=snake_case__ , default=snake_case__ , help='''Pretrained config name or path if not the same as model_name''' , ) parser.add_argument( '''--device''' , type=snake_case__ , default='''cpu''' , help='''Device where the model will be run''' , ) parser.add_argument('''--output_file_path''' , type=snake_case__ , default=snake_case__ , help='''Where to store the final ONNX file.''' ) A : str = parser.parse_args() return args def lowerCAmelCase_ ( snake_case__ , snake_case__="cpu" ): '''simple docstring''' A : int = model_dict[model_name].from_pretrained(snake_case__ ).to(snake_case__ ) A : Union[str, Any] = tokenizer_dict[model_name].from_pretrained(snake_case__ ) if model_name in ["facebook/bart-base"]: A : Dict = 0 A : Any = None A : Optional[Any] = 0 return huggingface_model, tokenizer def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' model.eval() A : List[str] = None A : List[str] = torch.jit.script(BARTBeamSearchGenerator(snake_case__ ) ) with torch.no_grad(): A : Any = '''My friends are cool but they eat too many carbs.''' A : List[str] = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1024 , return_tensors='''pt''' ).to(model.device ) A : int = model.generate( inputs['''input_ids'''] , attention_mask=inputs['''attention_mask'''] , num_beams=snake_case__ , max_length=snake_case__ , early_stopping=snake_case__ , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( snake_case__ , ( inputs['''input_ids'''], inputs['''attention_mask'''], num_beams, max_length, model.config.decoder_start_token_id, ) , snake_case__ , 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=snake_case__ , ) logger.info('''Model exported to {}'''.format(snake_case__ ) ) A : Any = remove_dup_initializers(os.path.abspath(snake_case__ ) ) logger.info('''Deduplicated and optimized model written to {}'''.format(snake_case__ ) ) A : Optional[int] = onnxruntime.InferenceSession(snake_case__ ) A : Optional[int] = ort_sess.run( snake_case__ , { '''input_ids''': inputs['''input_ids'''].cpu().numpy(), '''attention_mask''': inputs['''attention_mask'''].cpu().numpy(), '''num_beams''': np.array(snake_case__ ), '''max_length''': np.array(snake_case__ ), '''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 lowerCAmelCase_ ( ): '''simple docstring''' A : Optional[int] = parse_args() A : Optional[int] = 5 A : List[str] = 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() A : Dict = torch.device(args.device ) A, A : Any = load_model_tokenizer(args.model_name_or_path , snake_case__ ) if model.config.decoder_start_token_id is None: raise ValueError('''Make sure that `config.decoder_start_token_id` is correctly defined''' ) model.to(snake_case__ ) if args.max_length: A : Dict = args.max_length if args.num_beams: A : Dict = args.num_beams if args.output_file_path: A : Optional[int] = args.output_file_path else: A : Union[str, Any] = '''BART.onnx''' logger.info('''Exporting model to ONNX''' ) export_and_validate_model(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) if __name__ == "__main__": main()
311
'''simple docstring''' import colorsys from PIL import Image # type: ignore def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : Optional[int] = x A : str = y for step in range(snake_case__ ): # noqa: B007 A : str = a * a - b * b + x A : List[str] = 2 * a * b + y A : str = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255 ) for i in colorsys.hsv_to_rgb(snake_case__ , 1 , 1 ) ) def lowerCAmelCase_ ( snake_case__ = 800 , snake_case__ = 600 , snake_case__ = -0.6 , snake_case__ = 0 , snake_case__ = 3.2 , snake_case__ = 50 , snake_case__ = True , ): '''simple docstring''' A : List[Any] = Image.new('''RGB''' , (image_width, image_height) ) A : Tuple = img.load() # loop through the image-coordinates for image_x in range(snake_case__ ): for image_y in range(snake_case__ ): # determine the figure-coordinates based on the image-coordinates A : Optional[int] = figure_width / image_width * image_height A : Tuple = figure_center_x + (image_x / image_width - 0.5) * figure_width A : List[str] = figure_center_y + (image_y / image_height - 0.5) * figure_height A : str = get_distance(snake_case__ , snake_case__ , snake_case__ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: A : str = get_color_coded_rgb(snake_case__ ) else: A : List[Any] = get_black_and_white_rgb(snake_case__ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure lowercase : Optional[Any] = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
311
1
'''simple docstring''' from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for param in module.parameters(): A : Optional[Any] = False def lowerCAmelCase_ ( ): '''simple docstring''' A : List[Any] = '''cuda''' if torch.cuda.is_available() else '''cpu''' if torch.backends.mps.is_available() and torch.backends.mps.is_built(): A : Optional[Any] = '''mps''' if device == "mps": print( '''WARNING: MPS currently doesn\'t seem to work, and messes up backpropagation without any visible torch''' ''' errors. I recommend using CUDA on a colab notebook or CPU instead if you\'re facing inexplicable issues''' ''' with generations.''' ) return device def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : List[str] = plt.imshow(snake_case__ ) fig.axes.get_xaxis().set_visible(snake_case__ ) fig.axes.get_yaxis().set_visible(snake_case__ ) plt.show() def lowerCAmelCase_ ( ): '''simple docstring''' A : List[str] = datetime.now() A : List[Any] = current_time.strftime('''%H:%M:%S''' ) return timestamp
311
'''simple docstring''' import argparse import importlib from pathlib import Path # Test all the extensions added in the setup lowercase : Optional[int] = [ 'kernels/rwkv/wkv_cuda.cu', 'kernels/rwkv/wkv_op.cpp', 'kernels/deformable_detr/ms_deform_attn.h', 'kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh', 'models/graphormer/algos_graphormer.pyx', ] def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for file in FILES_TO_FIND: if not (transformers_path / file).exists(): return False return True if __name__ == "__main__": lowercase : str = argparse.ArgumentParser() parser.add_argument('--check_lib', action='store_true', help='Whether to check the build or the actual package.') lowercase : Optional[Any] = parser.parse_args() if args.check_lib: lowercase : List[Any] = importlib.import_module('transformers') lowercase : str = Path(transformers_module.__file__).parent else: lowercase : List[Any] = Path.cwd() / 'build/lib/transformers' if not test_custom_files_are_present(transformers_path): raise ValueError('The built release does not contain the custom files. Fix this before going further!')
311
1
'''simple docstring''' from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging lowercase : Union[str, Any] = logging.get_logger(__name__) class A ( __snake_case ): __magic_name__ = ['''pixel_values'''] def __init__( self , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = 1 / 255 , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = 8 , **SCREAMING_SNAKE_CASE , ) -> None: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) A : Union[str, Any] = do_rescale A : List[Any] = rescale_factor A : int = do_pad A : List[str] = pad_size def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE ) -> np.ndarray: """simple docstring""" return rescale(SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None ) -> int: """simple docstring""" A, A : Dict = get_image_size(SCREAMING_SNAKE_CASE ) A : List[Any] = (old_height // size + 1) * size - old_height A : int = (old_width // size + 1) * size - old_width return pad(SCREAMING_SNAKE_CASE , ((0, pad_height), (0, pad_width)) , mode='''symmetric''' , data_format=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" A : List[Any] = do_rescale if do_rescale is not None else self.do_rescale A : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor A : Tuple = do_pad if do_pad is not None else self.do_pad A : Any = pad_size if pad_size is not None else self.pad_size A : Optional[int] = make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) # All transformations expect numpy arrays. A : Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: A : int = [self.rescale(image=SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE ) for image in images] if do_pad: A : Dict = [self.pad(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE ) for image in images] A : Union[str, Any] = [to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] A : Optional[int] = {'''pixel_values''': images} return BatchFeature(data=SCREAMING_SNAKE_CASE , tensor_type=SCREAMING_SNAKE_CASE )
311
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig 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 ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=30 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=2 , ) -> List[str]: """simple docstring""" A : List[str] = parent A : Optional[Any] = batch_size A : Tuple = image_size A : int = patch_size A : Optional[int] = num_channels A : str = is_training A : List[Any] = use_labels A : Any = hidden_size A : Any = num_hidden_layers A : Optional[int] = num_attention_heads A : Any = intermediate_size A : List[str] = hidden_act A : str = hidden_dropout_prob A : Tuple = attention_probs_dropout_prob A : Any = type_sequence_label_size A : Optional[int] = initializer_range A : Dict = scope A : Tuple = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) A : List[Any] = (image_size // patch_size) ** 2 A : Tuple = num_patches + 2 def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A : Tuple = None if self.use_labels: A : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Tuple = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" return DeiTConfig( 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=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : Any = TFDeiTModel(config=SCREAMING_SNAKE_CASE ) A : str = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" A : Tuple = TFDeiTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE ) A : List[Any] = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A : Optional[int] = 1 A : str = TFDeiTForMaskedImageModeling(SCREAMING_SNAKE_CASE ) A : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Tuple = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" A : str = self.type_sequence_label_size A : Optional[Any] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE ) A : Optional[Any] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images A : Optional[Any] = 1 A : List[str] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE ) A : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Optional[int] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Optional[int] = self.prepare_config_and_inputs() A, A, A : Tuple = config_and_inputs A : Any = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class A ( __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) __magic_name__ = ( { '''feature-extraction''': TFDeiTModel, '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) __magic_name__ = False __magic_name__ = False __magic_name__ = False __magic_name__ = False def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = TFDeiTModelTester(self ) A : Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''DeiT does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" pass def __lowerCAmelCase ( self ) -> str: """simple docstring""" A, A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) A : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE , tf.keras.layers.Dense ) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A, A : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) A : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A : Union[str, Any] = [*signature.parameters.keys()] A : List[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ) -> Tuple: """simple docstring""" A : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def __lowerCAmelCase ( self ) -> str: """simple docstring""" for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A : List[str] = TFDeiTModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_ ( ): '''simple docstring''' A : str = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class A ( unittest.TestCase ): @cached_property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) if is_vision_available() else None ) @slow def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Union[str, Any] = TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) A : Dict = self.default_image_processor A : List[str] = prepare_img() A : Any = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='''tf''' ) # forward pass A : Optional[int] = model(**SCREAMING_SNAKE_CASE ) # verify the logits A : List[Any] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE ) A : str = tf.constant([-1.0_266, 0.1_912, -1.2_861] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
1
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' assert isinstance(snake_case__ , snake_case__ ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : int = tmp_path / '''cache''' A : List[str] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : List[str] = SqlDatasetReader( '''dataset''' , '''sqlite:///''' + sqlite_path , cache_dir=snake_case__ , keep_in_memory=snake_case__ ).read() _check_sql_dataset(snake_case__ , snake_case__ ) @require_sqlalchemy @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : Tuple = tmp_path / '''cache''' A : Tuple = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} A : Optional[Any] = features.copy() if features else default_expected_features A : List[str] = ( Features({feature: Value(snake_case__ ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[Any] = SqlDatasetReader('''dataset''' , '''sqlite:///''' + sqlite_path , features=snake_case__ , cache_dir=snake_case__ ).read() _check_sql_dataset(snake_case__ , snake_case__ ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' with contextlib.closing(sqlitea.connect(snake_case__ ) ) as con: A : Tuple = con.cursor() cur.execute('''SELECT * FROM dataset''' ) for row in cur: yield row @require_sqlalchemy def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : List[str] = tmp_path / '''cache''' A : str = os.path.join(snake_case__ , '''tmp.sql''' ) A : Tuple = SqlDatasetReader('''dataset''' , '''sqlite:///''' + sqlite_path , cache_dir=snake_case__ ).read() SqlDatasetWriter(snake_case__ , '''dataset''' , '''sqlite:///''' + output_sqlite_path , num_proc=1 ).write() A : int = iter_sql_file(snake_case__ ) A : List[str] = iter_sql_file(snake_case__ ) for rowa, rowa in zip(snake_case__ , snake_case__ ): assert rowa == rowa @require_sqlalchemy def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : str = tmp_path / '''cache''' A : Dict = os.path.join(snake_case__ , '''tmp.sql''' ) A : Optional[int] = SqlDatasetReader('''dataset''' , '''sqlite:///''' + sqlite_path , cache_dir=snake_case__ ).read() SqlDatasetWriter(snake_case__ , '''dataset''' , '''sqlite:///''' + output_sqlite_path , num_proc=2 ).write() A : str = iter_sql_file(snake_case__ ) A : Dict = iter_sql_file(snake_case__ ) for rowa, rowa in zip(snake_case__ , snake_case__ ): assert rowa == rowa @require_sqlalchemy def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : Dict = tmp_path / '''cache''' A : Optional[int] = os.path.join(snake_case__ , '''tmp.sql''' ) A : int = SqlDatasetReader('''dataset''' , '''sqlite:///''' + sqlite_path , cache_dir=snake_case__ ).read() with pytest.raises(snake_case__ ): SqlDatasetWriter(snake_case__ , '''dataset''' , '''sqlite:///''' + output_sqlite_path , num_proc=0 ).write()
311
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase : List[str] = { 'configuration_cpmant': ['CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CpmAntConfig'], 'tokenization_cpmant': ['CpmAntTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[Any] = [ 'CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST', 'CpmAntForCausalLM', 'CpmAntModel', 'CpmAntPreTrainedModel', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys lowercase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
311
1
'''simple docstring''' import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class A : @staticmethod def __lowerCAmelCase ( *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" pass @is_pipeline_test @require_vision class A ( unittest.TestCase ): @require_torch def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : List[str] = pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , ) A : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) A : str = image_classifier(SCREAMING_SNAKE_CASE , candidate_labels=['''a''', '''b''', '''c'''] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(SCREAMING_SNAKE_CASE ) , [ [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}], [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''c'''}, {'''score''': 0.333, '''label''': '''b'''}], ] , ) A : Union[str, Any] = image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE ) , [ [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, ], ] , ) @require_tf def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Tuple = pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , framework='''tf''' ) A : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) A : Any = image_classifier(SCREAMING_SNAKE_CASE , candidate_labels=['''a''', '''b''', '''c'''] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE ) , [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}] , ) A : Dict = image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE ) , [ [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE )}, ], ] , ) @slow @require_torch def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : List[str] = pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , ) # This is an image of 2 cats with remotes and no planes A : Optional[int] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) A : Optional[Any] = image_classifier(SCREAMING_SNAKE_CASE , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) A : List[str] = image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , ) @slow @require_tf def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : List[Any] = pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , framework='''tf''' ) # This is an image of 2 cats with remotes and no planes A : Optional[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) A : Optional[int] = image_classifier(SCREAMING_SNAKE_CASE , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) A : Dict = image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , )
311
'''simple docstring''' from __future__ import annotations lowercase : Union[str, Any] = list[tuple[int, int]] lowercase : Optional[Any] = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] lowercase : Any = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" A : int = pos_x A : Optional[Any] = pos_y A : Optional[Any] = (pos_y, pos_x) A : str = goal_x A : Optional[int] = goal_y A : List[Any] = g_cost A : str = parent A : str = self.calculate_heuristic() def __lowerCAmelCase ( self ) -> float: """simple docstring""" A : Optional[int] = abs(self.pos_x - self.goal_x ) A : Optional[Any] = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self , SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" return self.f_cost < other.f_cost class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , SCREAMING_SNAKE_CASE ) A : Tuple = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , SCREAMING_SNAKE_CASE ) A : Optional[Any] = [self.start] A : list[Node] = [] A : Tuple = False def __lowerCAmelCase ( self ) -> Path | None: """simple docstring""" while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() A : Optional[int] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: A : Optional[int] = True return self.retrace_path(SCREAMING_SNAKE_CASE ) self.closed_nodes.append(SCREAMING_SNAKE_CASE ) A : Any = self.get_successors(SCREAMING_SNAKE_CASE ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(SCREAMING_SNAKE_CASE ) else: # retrieve the best current path A : str = self.open_nodes.pop(self.open_nodes.index(SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(SCREAMING_SNAKE_CASE ) else: self.open_nodes.append(SCREAMING_SNAKE_CASE ) if not self.reached: return [self.start.pos] return None def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> list[Node]: """simple docstring""" A : List[Any] = [] for action in delta: A : List[str] = parent.pos_x + action[1] A : Dict = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , SCREAMING_SNAKE_CASE , ) ) return successors def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Path: """simple docstring""" A : int = node A : Union[str, Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) A : int = current_node.parent path.reverse() return path if __name__ == "__main__": lowercase : Tuple = (0, 0) lowercase : List[str] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print('------') lowercase : int = GreedyBestFirst(init, goal) lowercase : Union[str, Any] = greedy_bf.search() if path: for pos_x, pos_y in path: lowercase : Dict = 2 for elem in grid: print(elem)
311
1
'''simple docstring''' from __future__ import annotations from random import random class A : def __init__( self , SCREAMING_SNAKE_CASE = None ) -> Tuple: """simple docstring""" A : Optional[Any] = value A : Any = random() A : Node | None = None A : Node | None = None def __repr__( self ) -> str: """simple docstring""" from pprint import pformat if self.left is None and self.right is None: return F'\'{self.value}: {self.prior:.5}\'' else: return pformat( {F'{self.value}: {self.prior:.5}': (self.left, self.right)} , indent=1 ) def __str__( self ) -> str: """simple docstring""" A : Optional[Any] = str(self.value ) + ''' ''' A : Union[str, Any] = str(self.left or '''''' ) A : Any = str(self.right or '''''' ) return value + left + right def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: A, A : Any = split(root.left , snake_case__ ) return left, root else: A, A : Optional[int] = split(root.right , snake_case__ ) return root, right def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: A : List[str] = merge(left.right , snake_case__ ) return left else: A : Tuple = merge(snake_case__ , right.left ) return right def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : List[Any] = Node(snake_case__ ) A, A : Tuple = split(snake_case__ , snake_case__ ) return merge(merge(snake_case__ , snake_case__ ) , snake_case__ ) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A, A : Dict = split(snake_case__ , value - 1 ) A, A : Any = split(snake_case__ , snake_case__ ) return merge(snake_case__ , snake_case__ ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if not root: # None return else: inorder(root.left ) print(root.value , end=''',''' ) inorder(root.right ) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' for arg in args.split(): if arg[0] == "+": A : int = insert(snake_case__ , int(arg[1:] ) ) elif arg[0] == "-": A : int = erase(snake_case__ , int(arg[1:] ) ) else: print('''Unknown command''' ) return root def lowerCAmelCase_ ( ): '''simple docstring''' A : Union[str, Any] = None print( '''enter numbers to create a tree, + value to add value into treap, ''' '''- value to erase all nodes with value. \'q\' to quit. ''' ) A : Optional[int] = input() while args != "q": A : str = interact_treap(snake_case__ , snake_case__ ) print(snake_case__ ) A : Union[str, Any] = input() print('''good by!''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
311
'''simple docstring''' import argparse import os from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_task_guides.py lowercase : Any = 'src/transformers' lowercase : str = 'docs/source/en/tasks' def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' with open(snake_case__ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: A : Union[str, Any] = f.readlines() # Find the start prompt. A : List[Any] = 0 while not lines[start_index].startswith(snake_case__ ): start_index += 1 start_index += 1 A : List[str] = start_index while not lines[end_index].startswith(snake_case__ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. lowercase : int = direct_transformers_import(TRANSFORMERS_PATH) lowercase : str = { 'asr.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, 'audio_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, 'language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, 'image_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, 'masked_language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, 'multiple_choice.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, 'object_detection.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, 'question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, 'semantic_segmentation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, 'sequence_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, 'summarization.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'token_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, 'translation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'video_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, 'document_question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, 'monocular_depth_estimation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). lowercase : Optional[int] = { 'summarization.md': ('nllb',), 'translation.md': ('nllb',), } def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : int = TASK_GUIDE_TO_MODELS[task_guide] A : List[str] = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(snake_case__ , set() ) A : Union[str, Any] = { code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([F'[{name}](../model_doc/{code})' for code, name in model_names.items()] ) + "\n" def lowerCAmelCase_ ( snake_case__ , snake_case__=False ): '''simple docstring''' A, A, A, A : Optional[int] = _find_text_in_file( filename=os.path.join(snake_case__ , snake_case__ ) , start_prompt='''<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->''' , end_prompt='''<!--End of the generated tip-->''' , ) A : Optional[int] = get_model_list_for_task(snake_case__ ) if current_list != new_list: if overwrite: with open(os.path.join(snake_case__ , snake_case__ ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:] ) else: raise ValueError( F'The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`' ''' to fix this.''' ) if __name__ == "__main__": lowercase : Dict = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') lowercase : List[Any] = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
311
1
'''simple docstring''' import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging lowercase : List[Any] = logging.get_logger(__name__) lowercase : Dict = R'\n Args:\n input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):\n Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax\n or scores for each vocabulary token after SoftMax.\n kwargs (`Dict[str, Any]`, *optional*):\n Additional stopping criteria specific kwargs.\n\n Return:\n `bool`. `False` indicates we should continue, `True` indicates we should stop.\n\n' class A ( __snake_case ): @add_start_docstrings(SCREAMING_SNAKE_CASE ) def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" raise NotImplementedError('''StoppingCriteria needs to be subclassed''' ) class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None ) -> Dict: """simple docstring""" A : Union[str, Any] = max_length A : List[Any] = max_position_embeddings @add_start_docstrings(SCREAMING_SNAKE_CASE ) def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" A : Any = input_ids.shape[-1] A : List[Any] = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( '''This is a friendly reminder - the current text generation call will exceed the model\'s predefined ''' F'maximum length ({self.max_position_embeddings}). Depending on the model, you may observe ' '''exceptions, performance degradation, or nothing at all.''' ) return is_done class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" warnings.warn( '''The class `MaxNewTokensCriteria` is deprecated. ''' F'Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` ' '''with `max_length = start_length + max_new_tokens` instead.''' , SCREAMING_SNAKE_CASE , ) A : Optional[Any] = start_length A : Optional[int] = max_new_tokens A : Optional[Any] = start_length + max_new_tokens @add_start_docstrings(SCREAMING_SNAKE_CASE ) def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" return input_ids.shape[-1] >= self.max_length class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None ) -> List[Any]: """simple docstring""" A : List[str] = max_time A : Optional[int] = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(SCREAMING_SNAKE_CASE ) def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" return time.time() - self.initial_timestamp > self.max_time class A ( __snake_case ): @add_start_docstrings(SCREAMING_SNAKE_CASE ) def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" return any(criteria(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for criteria in self ) @property def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" for stopping_criterium in self: if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): return stopping_criterium.max_length elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): return stopping_criterium.max_length return None def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : Any = stopping_criteria.max_length A : Dict = deepcopy(snake_case__ ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn('''You set different `max_length` for stopping criteria and `max_length` parameter''' , snake_case__ ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=snake_case__ ) ) return new_stopping_criteria
311
'''simple docstring''' def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if len(snake_case__ ) <= 1: return [tuple(snake_case__ )] A : Tuple = [] def generate(snake_case__ , snake_case__ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , snake_case__ ) for i in range(k - 1 ): if k % 2 == 0: # k is even A, A : Optional[Any] = arr[k - 1], arr[i] else: # k is odd A, A : Optional[Any] = arr[k - 1], arr[0] generate(k - 1 , snake_case__ ) generate(len(snake_case__ ) , snake_case__ ) return res if __name__ == "__main__": lowercase : List[str] = input('Enter numbers separated by a comma:\n').strip() lowercase : int = [int(item) for item in user_input.split(',')] print(heaps(arr))
311
1
'''simple docstring''' import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class A ( __snake_case , unittest.TestCase ): __magic_name__ = BertTokenizer __magic_name__ = BertTokenizerFast __magic_name__ = True __magic_name__ = True __magic_name__ = filter_non_english def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" super().setUp() A : int = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] A : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" A : Optional[Any] = '''UNwant\u00E9d,running''' A : Optional[Any] = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Any = self.tokenizer_class(self.vocab_file ) A : Optional[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(SCREAMING_SNAKE_CASE , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) , [9, 6, 7, 12, 10, 11] ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" if not self.test_rust_tokenizer: return A : List[str] = self.get_tokenizer() A : str = self.get_rust_tokenizer() A : List[str] = '''UNwant\u00E9d,running''' A : Optional[Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE ) A : Union[str, Any] = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : List[Any] = tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) A : Any = rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : List[Any] = self.get_rust_tokenizer() A : str = tokenizer.encode(SCREAMING_SNAKE_CASE ) A : List[str] = rust_tokenizer.encode(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # With lower casing A : List[str] = self.get_tokenizer(do_lower_case=SCREAMING_SNAKE_CASE ) A : Dict = self.get_rust_tokenizer(do_lower_case=SCREAMING_SNAKE_CASE ) A : Union[str, Any] = '''UNwant\u00E9d,running''' A : Optional[Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE ) A : Optional[Any] = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : List[Any] = tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) A : Optional[int] = rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Dict = self.get_rust_tokenizer() A : Optional[Any] = tokenizer.encode(SCREAMING_SNAKE_CASE ) A : str = rust_tokenizer.encode(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Optional[Any] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Tuple = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Union[str, Any] = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE , strip_accents=SCREAMING_SNAKE_CASE ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : List[Any] = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE , strip_accents=SCREAMING_SNAKE_CASE ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : List[Any] = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Union[str, Any] = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[int] = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE , strip_accents=SCREAMING_SNAKE_CASE ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Optional[Any] = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE , strip_accents=SCREAMING_SNAKE_CASE ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : List[str] = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Union[str, Any] = BasicTokenizer() A : Optional[Any] = '''a\n\'ll !!to?\'d of, can\'t.''' A : Dict = ['''a''', '''\'''', '''ll''', '''!''', '''!''', '''to''', '''?''', '''\'''', '''d''', '''of''', ''',''', '''can''', '''\'''', '''t''', '''.'''] self.assertListEqual(tokenizer.tokenize(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : str = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] A : List[str] = {} for i, token in enumerate(SCREAMING_SNAKE_CASE ): A : int = i A : Any = WordpieceTokenizer(vocab=SCREAMING_SNAKE_CASE , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''unwanted running''' ) , ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.tokenize('''unwantedX running''' ) , ['''[UNK]''', '''runn''', '''##ing'''] ) def __lowerCAmelCase ( 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 __lowerCAmelCase ( 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 __lowerCAmelCase ( self ) -> Dict: """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 __lowerCAmelCase ( self ) -> int: """simple docstring""" A : int = self.get_tokenizer() A : Any = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(SCREAMING_SNAKE_CASE ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Union[str, Any] = self.tokenizer_class.from_pretrained('''bert-base-uncased''' ) A : Tuple = tokenizer.encode('''sequence builders''' , add_special_tokens=SCREAMING_SNAKE_CASE ) A : str = tokenizer.encode('''multi-sequence build''' , add_special_tokens=SCREAMING_SNAKE_CASE ) A : Tuple = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE ) A : List[Any] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): A : Optional[Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) A : Dict = F'A, naïve {tokenizer_r.mask_token} AllenNLP sentence.' A : Optional[int] = tokenizer_r.encode_plus( SCREAMING_SNAKE_CASE , return_attention_mask=SCREAMING_SNAKE_CASE , return_token_type_ids=SCREAMING_SNAKE_CASE , return_offsets_mapping=SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE , ) A : Optional[Any] = tokenizer_r.do_lower_case if hasattr(SCREAMING_SNAKE_CASE , '''do_lower_case''' ) else False A : Dict = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''A'''), ((1, 2), ''','''), ((3, 5), '''na'''), ((5, 6), '''##ï'''), ((6, 8), '''##ve'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''Allen'''), ((21, 23), '''##NL'''), ((23, 24), '''##P'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''a'''), ((1, 2), ''','''), ((3, 8), '''naive'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''allen'''), ((21, 23), '''##nl'''), ((23, 24), '''##p'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['''input_ids'''] ) ) self.assertEqual([e[0] for e in expected_results] , tokens['''offset_mapping'''] ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Union[str, Any] = ['''的''', '''人''', '''有'''] A : str = ''''''.join(SCREAMING_SNAKE_CASE ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): A : List[Any] = True A : List[str] = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) A : Dict = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) A : Optional[int] = tokenizer_p.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) A : Optional[int] = tokenizer_r.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) A : Optional[int] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE ) A : Tuple = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Any = False A : Union[str, Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) A : Any = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) A : str = tokenizer_r.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) A : int = tokenizer_p.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) A : int = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE ) A : Tuple = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE ) # it is expected that only the first Chinese character is not preceded by "##". A : List[str] = [ F'##{token}' if idx != 0 else token for idx, token in enumerate(SCREAMING_SNAKE_CASE ) ] self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
311
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class A ( __snake_case ): __magic_name__ = (UniPCMultistepScheduler,) __magic_name__ = (('''num_inference_steps''', 25),) def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" A : str = { '''num_train_timesteps''': 1000, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''solver_order''': 2, '''solver_type''': '''bh2''', } config.update(**SCREAMING_SNAKE_CASE ) return config def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=0 , **SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : List[Any] = dict(self.forward_default_kwargs ) A : Union[str, Any] = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE ) A : Optional[Any] = self.dummy_sample A : int = 0.1 * sample A : Union[str, Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A : Optional[Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals A : List[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE ) A : List[Any] = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE ) new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals A : Dict = dummy_past_residuals[: new_scheduler.config.solver_order] A, A : Tuple = sample, sample for t in range(SCREAMING_SNAKE_CASE , time_step + scheduler.config.solver_order + 1 ): A : Any = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample A : Optional[Any] = new_scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=0 , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : Optional[Any] = dict(self.forward_default_kwargs ) A : Tuple = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE ) A : List[Any] = self.dummy_sample A : int = 0.1 * sample A : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A : Optional[int] = self.get_scheduler_config() A : Any = scheduler_class(**SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals (must be after setting timesteps) A : int = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE ) A : int = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE ) # copy over dummy past residuals new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # copy over dummy past residual (must be after setting timesteps) A : Optional[Any] = dummy_past_residuals[: new_scheduler.config.solver_order] A : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample A : List[Any] = new_scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" if scheduler is None: A : Dict = self.scheduler_classes[0] A : Union[str, Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : List[Any] = scheduler_class(**SCREAMING_SNAKE_CASE ) A : Tuple = self.scheduler_classes[0] A : Union[str, Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE ) A : int = 10 A : Tuple = self.dummy_model() A : Any = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): A : int = model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Optional[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample return sample def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Tuple = dict(self.forward_default_kwargs ) A : List[Any] = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE ) for scheduler_class in self.scheduler_classes: A : Dict = self.get_scheduler_config() A : Dict = scheduler_class(**SCREAMING_SNAKE_CASE ) A : Optional[Any] = self.dummy_sample A : Optional[int] = 0.1 * sample if num_inference_steps is not None and hasattr(SCREAMING_SNAKE_CASE , '''set_timesteps''' ): scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) elif num_inference_steps is not None and not hasattr(SCREAMING_SNAKE_CASE , '''set_timesteps''' ): A : Tuple = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) A : Dict = [residual + 0.2, residual + 0.15, residual + 0.10] A : List[str] = dummy_past_residuals[: scheduler.config.solver_order] A : List[Any] = scheduler.timesteps[5] A : Dict = scheduler.timesteps[6] A : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample A : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Union[str, Any] = UniPCMultistepScheduler(**self.get_scheduler_config() ) A : List[Any] = self.full_loop(scheduler=SCREAMING_SNAKE_CASE ) A : List[str] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.2_464 ) < 1e-3 A : Dict = DPMSolverSinglestepScheduler.from_config(scheduler.config ) A : Optional[int] = DEISMultistepScheduler.from_config(scheduler.config ) A : List[Any] = DPMSolverMultistepScheduler.from_config(scheduler.config ) A : List[Any] = UniPCMultistepScheduler.from_config(scheduler.config ) A : Optional[Any] = self.full_loop(scheduler=SCREAMING_SNAKE_CASE ) A : Optional[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.2_464 ) < 1e-3 def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE ) 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=SCREAMING_SNAKE_CASE , prediction_type=SCREAMING_SNAKE_CASE , sample_max_value=SCREAMING_SNAKE_CASE , solver_order=SCREAMING_SNAKE_CASE , solver_type=SCREAMING_SNAKE_CASE , ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" for solver_type in ["bh1", "bh2"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=SCREAMING_SNAKE_CASE , solver_type=SCREAMING_SNAKE_CASE , prediction_type=SCREAMING_SNAKE_CASE , ) A : Dict = self.full_loop( solver_order=SCREAMING_SNAKE_CASE , solver_type=SCREAMING_SNAKE_CASE , prediction_type=SCREAMING_SNAKE_CASE , ) assert not torch.isnan(SCREAMING_SNAKE_CASE ).any(), "Samples have nan numbers" def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE ) self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=SCREAMING_SNAKE_CASE , time_step=0 ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : int = self.full_loop() A : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.2_464 ) < 1e-3 def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : List[Any] = self.full_loop(prediction_type='''v_prediction''' ) A : Any = torch.mean(torch.abs(SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.1_014 ) < 1e-3 def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Dict = self.scheduler_classes[0] A : List[Any] = self.get_scheduler_config(thresholding=SCREAMING_SNAKE_CASE , dynamic_thresholding_ratio=0 ) A : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE ) A : Tuple = 10 A : Union[str, Any] = self.dummy_model() A : Dict = self.dummy_sample_deter.half() scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): A : Dict = model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Optional[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample assert sample.dtype == torch.floataa def __lowerCAmelCase ( self , **SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" for scheduler_class in self.scheduler_classes: A : Dict = self.get_scheduler_config(**SCREAMING_SNAKE_CASE ) A : Tuple = scheduler_class(**SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(scheduler.config.num_train_timesteps ) assert len(scheduler.timesteps.unique() ) == scheduler.num_inference_steps
311
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer lowercase : str = logging.get_logger(__name__) lowercase : Any = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} lowercase : Tuple = { 'vocab_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt' ), 'squeezebert/squeezebert-mnli': 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt', 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli': ( 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json' ), }, } lowercase : List[str] = { 'squeezebert/squeezebert-uncased': 5_12, 'squeezebert/squeezebert-mnli': 5_12, 'squeezebert/squeezebert-mnli-headless': 5_12, } lowercase : List[Any] = { 'squeezebert/squeezebert-uncased': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli-headless': {'do_lower_case': True}, } class A ( __snake_case ): __magic_name__ = VOCAB_FILES_NAMES __magic_name__ = PRETRAINED_VOCAB_FILES_MAP __magic_name__ = PRETRAINED_INIT_CONFIGURATION __magic_name__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __magic_name__ = SqueezeBertTokenizer def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE="[UNK]" , SCREAMING_SNAKE_CASE="[SEP]" , SCREAMING_SNAKE_CASE="[PAD]" , SCREAMING_SNAKE_CASE="[CLS]" , SCREAMING_SNAKE_CASE="[MASK]" , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE , ) -> Optional[int]: """simple docstring""" super().__init__( SCREAMING_SNAKE_CASE , tokenizer_file=SCREAMING_SNAKE_CASE , do_lower_case=SCREAMING_SNAKE_CASE , unk_token=SCREAMING_SNAKE_CASE , sep_token=SCREAMING_SNAKE_CASE , pad_token=SCREAMING_SNAKE_CASE , cls_token=SCREAMING_SNAKE_CASE , mask_token=SCREAMING_SNAKE_CASE , tokenize_chinese_chars=SCREAMING_SNAKE_CASE , strip_accents=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) A : Any = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , SCREAMING_SNAKE_CASE ) != do_lower_case or normalizer_state.get('''strip_accents''' , SCREAMING_SNAKE_CASE ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , SCREAMING_SNAKE_CASE ) != tokenize_chinese_chars ): A : Tuple = getattr(SCREAMING_SNAKE_CASE , normalizer_state.pop('''type''' ) ) A : Optional[Any] = do_lower_case A : Any = strip_accents A : Tuple = tokenize_chinese_chars A : Dict = normalizer_class(**SCREAMING_SNAKE_CASE ) A : Optional[Any] = do_lower_case def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None ) -> Tuple: """simple docstring""" A : Dict = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None ) -> List[int]: """simple docstring""" A : int = [self.sep_token_id] A : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None ) -> Tuple[str]: """simple docstring""" A : Union[str, Any] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE , name=SCREAMING_SNAKE_CASE ) return tuple(SCREAMING_SNAKE_CASE )
311
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM A : Dict = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 0.0 , SCREAMING_SNAKE_CASE = 50 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = "pil" , SCREAMING_SNAKE_CASE = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" if isinstance(self.unet.config.sample_size , SCREAMING_SNAKE_CASE ): A : List[Any] = ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size, ) else: A : Optional[int] = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size) if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and len(SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( F'You have passed a list of generators of length {len(SCREAMING_SNAKE_CASE )}, but requested an effective batch' F' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) A : str = randn_tensor(SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output A : Any = self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 A : int = self.scheduler.step( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , eta=SCREAMING_SNAKE_CASE , use_clipped_model_output=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE ).prev_sample A : Dict = (image / 2 + 0.5).clamp(0 , 1 ) A : Optional[int] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": A : int = self.numpy_to_pil(SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE )
311
1
'''simple docstring''' from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand try: from fastapi import Body, FastAPI, HTTPException from fastapi.routing import APIRoute from pydantic import BaseModel from starlette.responses import JSONResponse from uvicorn import run lowercase : List[str] = True except (ImportError, AttributeError): lowercase : Any = object def lowerCAmelCase_ ( *snake_case__ , **snake_case__ ): '''simple docstring''' pass lowercase : List[str] = False lowercase : Optional[int] = logging.get_logger('transformers-cli/serving') def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : List[str] = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) return ServeCommand(snake_case__ , args.host , args.port , args.workers ) class A ( __snake_case ): __magic_name__ = 42 class A ( __snake_case ): __magic_name__ = 42 __magic_name__ = 42 class A ( __snake_case ): __magic_name__ = 42 class A ( __snake_case ): __magic_name__ = 42 class A ( __snake_case ): @staticmethod def __lowerCAmelCase ( SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" A : Optional[int] = parser.add_parser( '''serve''' , help='''CLI tool to run inference requests through REST and GraphQL endpoints.''' ) serve_parser.add_argument( '''--task''' , type=SCREAMING_SNAKE_CASE , choices=get_supported_tasks() , help='''The task to run the pipeline on''' , ) serve_parser.add_argument('''--host''' , type=SCREAMING_SNAKE_CASE , default='''localhost''' , help='''Interface the server will listen on.''' ) serve_parser.add_argument('''--port''' , type=SCREAMING_SNAKE_CASE , default=8888 , help='''Port the serving will listen to.''' ) serve_parser.add_argument('''--workers''' , type=SCREAMING_SNAKE_CASE , default=1 , help='''Number of http workers''' ) serve_parser.add_argument('''--model''' , type=SCREAMING_SNAKE_CASE , help='''Model\'s name or path to stored model.''' ) serve_parser.add_argument('''--config''' , type=SCREAMING_SNAKE_CASE , help='''Model\'s config name or path to stored model.''' ) serve_parser.add_argument('''--tokenizer''' , type=SCREAMING_SNAKE_CASE , help='''Tokenizer name to use.''' ) serve_parser.add_argument( '''--device''' , type=SCREAMING_SNAKE_CASE , default=-1 , help='''Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)''' , ) serve_parser.set_defaults(func=SCREAMING_SNAKE_CASE ) def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" A : Optional[Any] = pipeline A : Any = host A : List[Any] = port A : str = workers if not _serve_dependencies_installed: raise RuntimeError( '''Using serve command requires FastAPI and uvicorn. ''' '''Please install transformers with [serving]: pip install "transformers[serving]".''' '''Or install FastAPI and uvicorn separately.''' ) else: logger.info(F'Serving model over {host}:{port}' ) A : Union[str, Any] = FastAPI( routes=[ APIRoute( '''/''' , self.model_info , response_model=SCREAMING_SNAKE_CASE , response_class=SCREAMING_SNAKE_CASE , methods=['''GET'''] , ), APIRoute( '''/tokenize''' , self.tokenize , response_model=SCREAMING_SNAKE_CASE , response_class=SCREAMING_SNAKE_CASE , methods=['''POST'''] , ), APIRoute( '''/detokenize''' , self.detokenize , response_model=SCREAMING_SNAKE_CASE , response_class=SCREAMING_SNAKE_CASE , methods=['''POST'''] , ), APIRoute( '''/forward''' , self.forward , response_model=SCREAMING_SNAKE_CASE , response_class=SCREAMING_SNAKE_CASE , methods=['''POST'''] , ), ] , timeout=600 , ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" run(self._app , host=self.host , port=self.port , workers=self.workers ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE = Body(SCREAMING_SNAKE_CASE , embed=SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE = Body(SCREAMING_SNAKE_CASE , embed=SCREAMING_SNAKE_CASE ) ) -> List[Any]: """simple docstring""" try: A : int = self._pipeline.tokenizer.tokenize(SCREAMING_SNAKE_CASE ) if return_ids: A : int = self._pipeline.tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) return ServeTokenizeResult(tokens=SCREAMING_SNAKE_CASE , tokens_ids=SCREAMING_SNAKE_CASE ) else: return ServeTokenizeResult(tokens=SCREAMING_SNAKE_CASE ) except Exception as e: raise HTTPException(status_code=500 , detail={'''model''': '''''', '''error''': str(SCREAMING_SNAKE_CASE )} ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE = Body(SCREAMING_SNAKE_CASE , embed=SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE = Body(SCREAMING_SNAKE_CASE , embed=SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE = Body(SCREAMING_SNAKE_CASE , embed=SCREAMING_SNAKE_CASE ) , ) -> Dict: """simple docstring""" try: A : Optional[int] = self._pipeline.tokenizer.decode(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return ServeDeTokenizeResult(model='''''' , text=SCREAMING_SNAKE_CASE ) except Exception as e: raise HTTPException(status_code=500 , detail={'''model''': '''''', '''error''': str(SCREAMING_SNAKE_CASE )} ) async def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=Body(SCREAMING_SNAKE_CASE , embed=SCREAMING_SNAKE_CASE ) ) -> List[str]: """simple docstring""" if len(SCREAMING_SNAKE_CASE ) == 0: return ServeForwardResult(output=[] , attention=[] ) try: # Forward through the model A : Tuple = self._pipeline(SCREAMING_SNAKE_CASE ) return ServeForwardResult(output=SCREAMING_SNAKE_CASE ) except Exception as e: raise HTTPException(500 , {'''error''': str(SCREAMING_SNAKE_CASE )} )
311
'''simple docstring''' from __future__ import annotations from random import random class A : def __init__( self , SCREAMING_SNAKE_CASE = None ) -> Tuple: """simple docstring""" A : Optional[Any] = value A : Any = random() A : Node | None = None A : Node | None = None def __repr__( self ) -> str: """simple docstring""" from pprint import pformat if self.left is None and self.right is None: return F'\'{self.value}: {self.prior:.5}\'' else: return pformat( {F'{self.value}: {self.prior:.5}': (self.left, self.right)} , indent=1 ) def __str__( self ) -> str: """simple docstring""" A : Optional[Any] = str(self.value ) + ''' ''' A : Union[str, Any] = str(self.left or '''''' ) A : Any = str(self.right or '''''' ) return value + left + right def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: A, A : Any = split(root.left , snake_case__ ) return left, root else: A, A : Optional[int] = split(root.right , snake_case__ ) return root, right def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: A : List[str] = merge(left.right , snake_case__ ) return left else: A : Tuple = merge(snake_case__ , right.left ) return right def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : List[Any] = Node(snake_case__ ) A, A : Tuple = split(snake_case__ , snake_case__ ) return merge(merge(snake_case__ , snake_case__ ) , snake_case__ ) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A, A : Dict = split(snake_case__ , value - 1 ) A, A : Any = split(snake_case__ , snake_case__ ) return merge(snake_case__ , snake_case__ ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if not root: # None return else: inorder(root.left ) print(root.value , end=''',''' ) inorder(root.right ) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' for arg in args.split(): if arg[0] == "+": A : int = insert(snake_case__ , int(arg[1:] ) ) elif arg[0] == "-": A : int = erase(snake_case__ , int(arg[1:] ) ) else: print('''Unknown command''' ) return root def lowerCAmelCase_ ( ): '''simple docstring''' A : Union[str, Any] = None print( '''enter numbers to create a tree, + value to add value into treap, ''' '''- value to erase all nodes with value. \'q\' to quit. ''' ) A : Optional[int] = input() while args != "q": A : str = interact_treap(snake_case__ , snake_case__ ) print(snake_case__ ) A : Union[str, Any] = input() print('''good by!''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
311
1
'''simple docstring''' import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : Union[str, Any] = np.array([[1, item, train_mtch[i]] for i, item in enumerate(snake_case__ )] ) A : Dict = np.array(snake_case__ ) A : Dict = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() , snake_case__ ) ) , x.transpose() ) , snake_case__ ) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2] ) def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : Optional[Any] = (1, 2, 1) A : Tuple = (1, 1, 0, 7) A : Optional[int] = SARIMAX( snake_case__ , exog=snake_case__ , order=snake_case__ , seasonal_order=snake_case__ ) A : Any = model.fit(disp=snake_case__ , maxiter=600 , method='''nm''' ) A : int = model_fit.predict(1 , len(snake_case__ ) , exog=[test_match] ) return result[0] def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : Tuple = SVR(kernel='''rbf''' , C=1 , gamma=0.1 , epsilon=0.1 ) regressor.fit(snake_case__ , snake_case__ ) A : Any = regressor.predict(snake_case__ ) return y_pred[0] def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' train_user.sort() A : Optional[Any] = np.percentile(snake_case__ , 25 ) A : int = np.percentile(snake_case__ , 75 ) A : Union[str, Any] = qa - qa A : Optional[Any] = qa - (iqr * 0.1) return low_lim def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : str = 0 A : str = 0 for i in list_vote: if i > actual_result: A : int = not_safe + 1 else: if abs(abs(snake_case__ ) - abs(snake_case__ ) ) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) lowercase : Tuple = [[1_82_31, 0.0, 1], [2_26_21, 1.0, 2], [1_56_75, 0.0, 3], [2_35_83, 1.0, 4]] lowercase : List[Any] = pd.DataFrame( data_input, columns=['total_user', 'total_even', 'days'] ) lowercase : Optional[Any] = Normalizer().fit_transform(data_input_df.values) # split data lowercase : Tuple = normalize_df[:, 2].tolist() lowercase : List[Any] = normalize_df[:, 0].tolist() lowercase : Dict = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) lowercase : Optional[int] = normalize_df[:, [1, 2]].tolist() lowercase : Dict = x[: len(x) - 1] lowercase : Union[str, Any] = x[len(x) - 1 :] # for linear regression & sarimax lowercase : Optional[Any] = total_date[: len(total_date) - 1] lowercase : Dict = total_user[: len(total_user) - 1] lowercase : int = total_match[: len(total_match) - 1] lowercase : Union[str, Any] = total_date[len(total_date) - 1 :] lowercase : Optional[Any] = total_user[len(total_user) - 1 :] lowercase : Optional[int] = total_match[len(total_match) - 1 :] # voting system with forecasting lowercase : Tuple = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data lowercase : Optional[Any] = '' if data_safety_checker(res_vote, tst_user) else 'not ' print('Today\'s data is {not_str}safe.')
311
'''simple docstring''' import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=sys.maxsize ) -> Union[str, Any]: """simple docstring""" A : Tuple = '''bilinear''' A : Optional[int] = max_size A : Dict = short_edge_length def __call__( self , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : Tuple = [] for img in imgs: A, A : str = img.shape[:2] # later: provide list and randomly choose index for resize A : Union[str, Any] = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img A : int = size * 1.0 / min(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if h < w: A, A : Tuple = size, scale * w else: A, A : str = scale * h, size if max(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) > self.max_size: A : List[str] = self.max_size * 1.0 / max(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) A : Tuple = newh * scale A : int = neww * scale A : List[str] = int(neww + 0.5 ) A : int = int(newh + 0.5 ) if img.dtype == np.uinta: A : Dict = Image.fromarray(SCREAMING_SNAKE_CASE ) A : Optional[Any] = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) A : str = np.asarray(SCREAMING_SNAKE_CASE ) else: A : Dict = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw A : List[Any] = nn.functional.interpolate( SCREAMING_SNAKE_CASE , (newh, neww) , mode=self.interp_method , align_corners=SCREAMING_SNAKE_CASE ).squeeze(0 ) img_augs.append(SCREAMING_SNAKE_CASE ) return img_augs class A : def __init__( self , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" A : Any = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) A : str = cfg.INPUT.FORMAT A : int = cfg.SIZE_DIVISIBILITY A : Optional[int] = cfg.PAD_VALUE A : Dict = cfg.INPUT.MAX_SIZE_TEST A : Optional[Any] = cfg.MODEL.DEVICE A : Dict = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) A : Tuple = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) A : str = lambda SCREAMING_SNAKE_CASE : (x - self.pixel_mean) / self.pixel_std def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" A : Union[str, Any] = tuple(max(SCREAMING_SNAKE_CASE ) for s in zip(*[img.shape for img in images] ) ) A : List[str] = [im.shape[-2:] for im in images] A : Optional[Any] = [ nn.functional.pad( SCREAMING_SNAKE_CASE , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ] return torch.stack(SCREAMING_SNAKE_CASE ), torch.tensor(SCREAMING_SNAKE_CASE ) def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ) -> Union[str, Any]: """simple docstring""" with torch.no_grad(): if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : str = [images] if single_image: assert len(SCREAMING_SNAKE_CASE ) == 1 for i in range(len(SCREAMING_SNAKE_CASE ) ): if isinstance(images[i] , torch.Tensor ): images.insert(SCREAMING_SNAKE_CASE , images.pop(SCREAMING_SNAKE_CASE ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( SCREAMING_SNAKE_CASE , torch.as_tensor(img_tensorize(images.pop(SCREAMING_SNAKE_CASE ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge A : Tuple = torch.tensor([im.shape[:2] for im in images] ) A : Dict = self.aug(SCREAMING_SNAKE_CASE ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic A : Tuple = [self.normalizer(SCREAMING_SNAKE_CASE ) for x in images] # now pad them to do the following operations A, A : Optional[int] = self.pad(SCREAMING_SNAKE_CASE ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad A : Tuple = torch.true_divide(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' assert torch.isfinite(snake_case__ ).all(), "Box tensor contains infinite or NaN!" A, A : str = box_size tensor[:, 0].clamp_(min=0 , max=snake_case__ ) tensor[:, 1].clamp_(min=0 , max=snake_case__ ) tensor[:, 2].clamp_(min=0 , max=snake_case__ ) tensor[:, 3].clamp_(min=0 , max=snake_case__ )
311
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase : Union[str, Any] = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Union[str, Any] = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys lowercase : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
311
'''simple docstring''' import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": lowercase : Tuple = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml parser.add_argument( '--original_config_file', default=None, type=str, 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( '--scheduler_type', default='pndm', type=str, help='Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']', ) parser.add_argument( '--pipeline_type', default=None, type=str, help=( 'The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\'' '. If `None` pipeline will be automatically inferred.' ), ) parser.add_argument( '--image_size', default=None, 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( '--prediction_type', default=None, type=str, help=( 'The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable' ' Diffusion v2 Base. Use \'v_prediction\' 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.)') parser.add_argument( '--stable_unclip', type=str, default=None, required=False, help='Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.', ) parser.add_argument( '--stable_unclip_prior', type=str, default=None, required=False, help='Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.', ) parser.add_argument( '--clip_stats_path', type=str, help='Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.', required=False, ) parser.add_argument( '--controlnet', action='store_true', default=None, help='Set flag if this is a controlnet checkpoint.' ) parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--vae_path', type=str, default=None, required=False, help='Set to a path, hub id to an already converted vae to not convert it again.', ) lowercase : Tuple = parser.parse_args() lowercase : Union[str, Any] = download_from_original_stable_diffusion_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, prediction_type=args.prediction_type, model_type=args.pipeline_type, extract_ema=args.extract_ema, scheduler_type=args.scheduler_type, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, stable_unclip=args.stable_unclip, stable_unclip_prior=args.stable_unclip_prior, clip_stats_path=args.clip_stats_path, controlnet=args.controlnet, vae_path=args.vae_path, ) if args.half: pipe.to(torch_dtype=torch.floataa) if args.controlnet: # only save the controlnet model pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) else: pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
311
1
'''simple docstring''' from torch import nn def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(F'Unsupported activation function: {act_fn}' )
311
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal lowercase : str = datasets.utils.logging.get_logger(__name__) lowercase : Union[str, Any] = ['names', 'prefix'] lowercase : Union[str, Any] = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] lowercase : List[Any] = ['encoding_errors', 'on_bad_lines'] lowercase : Any = ['date_format'] @dataclass class A ( datasets.BuilderConfig ): __magic_name__ = "," __magic_name__ = None __magic_name__ = "infer" __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = False __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = True __magic_name__ = False __magic_name__ = True __magic_name__ = None __magic_name__ = "." __magic_name__ = None __magic_name__ = '"' __magic_name__ = 0 __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = True __magic_name__ = 0 __magic_name__ = True __magic_name__ = False __magic_name__ = None __magic_name__ = 10000 __magic_name__ = None __magic_name__ = "strict" __magic_name__ = "error" __magic_name__ = None def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" if self.delimiter is not None: A : Optional[Any] = self.delimiter if self.column_names is not None: A : Optional[Any] = self.column_names @property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : str = { '''sep''': self.sep, '''header''': self.header, '''names''': self.names, '''index_col''': self.index_col, '''usecols''': self.usecols, '''prefix''': self.prefix, '''mangle_dupe_cols''': self.mangle_dupe_cols, '''engine''': self.engine, '''converters''': self.converters, '''true_values''': self.true_values, '''false_values''': self.false_values, '''skipinitialspace''': self.skipinitialspace, '''skiprows''': self.skiprows, '''nrows''': self.nrows, '''na_values''': self.na_values, '''keep_default_na''': self.keep_default_na, '''na_filter''': self.na_filter, '''verbose''': self.verbose, '''skip_blank_lines''': self.skip_blank_lines, '''thousands''': self.thousands, '''decimal''': self.decimal, '''lineterminator''': self.lineterminator, '''quotechar''': self.quotechar, '''quoting''': self.quoting, '''escapechar''': self.escapechar, '''comment''': self.comment, '''encoding''': self.encoding, '''dialect''': self.dialect, '''error_bad_lines''': self.error_bad_lines, '''warn_bad_lines''': self.warn_bad_lines, '''skipfooter''': self.skipfooter, '''doublequote''': self.doublequote, '''memory_map''': self.memory_map, '''float_precision''': self.float_precision, '''chunksize''': self.chunksize, '''encoding_errors''': self.encoding_errors, '''on_bad_lines''': self.on_bad_lines, '''date_format''': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , SCREAMING_SNAKE_CASE ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class A ( datasets.ArrowBasedBuilder ): __magic_name__ = CsvConfig def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) A : int = dl_manager.download_and_extract(self.config.data_files ) if isinstance(SCREAMING_SNAKE_CASE , (str, list, tuple) ): A : str = data_files if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : int = [files] A : Optional[int] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] A : Tuple = [] for split_name, files in data_files.items(): if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : List[str] = [files] A : List[str] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE ) for file in files] splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE , gen_kwargs={'''files''': files} ) ) return splits def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> pa.Table: """simple docstring""" if self.config.features is not None: A : Optional[int] = self.config.features.arrow_schema if all(not require_storage_cast(SCREAMING_SNAKE_CASE ) for feature in self.config.features.values() ): # cheaper cast A : List[Any] = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=SCREAMING_SNAKE_CASE ) else: # more expensive cast; allows str <-> int/float or str to Audio for example A : int = table_cast(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return pa_table def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" A : Union[str, Any] = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str A : int = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(SCREAMING_SNAKE_CASE ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE ) ): A : Union[str, Any] = pd.read_csv(SCREAMING_SNAKE_CASE , iterator=SCREAMING_SNAKE_CASE , dtype=SCREAMING_SNAKE_CASE , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(SCREAMING_SNAKE_CASE ): A : Dict = pa.Table.from_pandas(SCREAMING_SNAKE_CASE ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE ) except ValueError as e: logger.error(F'Failed to read file \'{file}\' with error {type(SCREAMING_SNAKE_CASE )}: {e}' ) raise
311
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowercase : str = logging.get_logger(__name__) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : List[str] = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: A : int = 192 A : Dict = 768 A : Optional[int] = 12 A : Any = 3 A : Optional[Any] = [800, 1333] A : List[str] = False elif yolos_name == "yolos_s_dWr": A : Union[str, Any] = 330 A : Tuple = 14 A : Tuple = 6 A : Optional[int] = 1320 elif "yolos_s" in yolos_name: A : Optional[int] = 384 A : Any = 1536 A : Dict = 12 A : Tuple = 6 elif "yolos_b" in yolos_name: A : Optional[int] = [800, 1344] A : Dict = 91 A : Union[str, Any] = '''huggingface/label-files''' A : Optional[Any] = '''coco-detection-id2label.json''' A : Optional[int] = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='''dataset''' ) , '''r''' ) ) A : List[str] = {int(snake_case__ ): v for k, v in idalabel.items()} A : Optional[int] = idalabel A : Tuple = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ = False ): '''simple docstring''' for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A : str = state_dict.pop(F'blocks.{i}.attn.qkv.weight' ) A : Any = state_dict.pop(F'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A : Union[str, Any] = in_proj_weight[: config.hidden_size, :] A : str = in_proj_bias[: config.hidden_size] A : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A : Optional[Any] = in_proj_weight[-config.hidden_size :, :] A : List[str] = in_proj_bias[-config.hidden_size :] def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if "backbone" in name: A : List[str] = name.replace('''backbone''' , '''vit''' ) if "cls_token" in name: A : str = name.replace('''cls_token''' , '''embeddings.cls_token''' ) if "det_token" in name: A : Any = name.replace('''det_token''' , '''embeddings.detection_tokens''' ) if "mid_pos_embed" in name: A : List[str] = name.replace('''mid_pos_embed''' , '''encoder.mid_position_embeddings''' ) if "pos_embed" in name: A : Tuple = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' ) if "patch_embed.proj" in name: A : str = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "blocks" in name: A : List[str] = name.replace('''blocks''' , '''encoder.layer''' ) if "attn.proj" in name: A : Tuple = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: A : Optional[int] = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: A : int = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: A : Any = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: A : Union[str, Any] = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: A : Optional[int] = name.replace('''mlp.fc2''' , '''output.dense''' ) if "class_embed" in name: A : Dict = name.replace('''class_embed''' , '''class_labels_classifier''' ) if "bbox_embed" in name: A : Optional[Any] = name.replace('''bbox_embed''' , '''bbox_predictor''' ) if "vit.norm" in name: A : str = name.replace('''vit.norm''' , '''vit.layernorm''' ) return name def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' for key in orig_state_dict.copy().keys(): A : Dict = orig_state_dict.pop(snake_case__ ) if "qkv" in key: A : Union[str, Any] = key.split('''.''' ) A : Union[str, Any] = int(key_split[2] ) A : str = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: A : Any = val[:dim, :] A : Tuple = val[ dim : dim * 2, : ] A : Optional[Any] = val[-dim:, :] else: A : int = val[:dim] A : List[Any] = val[dim : dim * 2] A : Optional[Any] = val[-dim:] else: A : Tuple = val return orig_state_dict def lowerCAmelCase_ ( ): '''simple docstring''' A : Tuple = '''http://images.cocodataset.org/val2017/000000039769.jpg''' A : str = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ = False ): '''simple docstring''' A : Optional[int] = get_yolos_config(snake_case__ ) # load original state_dict A : Dict = torch.load(snake_case__ , map_location='''cpu''' )['''model'''] # load 🤗 model A : List[str] = YolosForObjectDetection(snake_case__ ) model.eval() A : Optional[Any] = convert_state_dict(snake_case__ , snake_case__ ) model.load_state_dict(snake_case__ ) # Check outputs on an image, prepared by YolosImageProcessor A : Optional[Any] = 800 if yolos_name != '''yolos_ti''' else 512 A : Any = YolosImageProcessor(format='''coco_detection''' , size=snake_case__ ) A : str = image_processor(images=prepare_img() , return_tensors='''pt''' ) A : Optional[int] = model(**snake_case__ ) A, A : Tuple = outputs.logits, outputs.pred_boxes A, A : str = None, None if yolos_name == "yolos_ti": A : Tuple = torch.tensor( [[-39.50_22, -11.98_20, -17.68_88], [-29.95_74, -9.97_69, -17.76_91], [-42.32_81, -20.72_00, -30.62_94]] ) A : Any = torch.tensor( [[0.40_21, 0.08_36, 0.79_79], [0.01_84, 0.26_09, 0.03_64], [0.17_81, 0.20_04, 0.20_95]] ) elif yolos_name == "yolos_s_200_pre": A : Any = torch.tensor( [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]] ) A : List[Any] = torch.tensor( [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]] ) elif yolos_name == "yolos_s_300_pre": A : int = torch.tensor( [[-36.22_20, -14.43_85, -23.54_57], [-35.69_70, -14.75_83, -21.39_35], [-31.59_39, -13.60_42, -16.80_49]] ) A : str = torch.tensor( [[0.76_14, 0.23_16, 0.47_28], [0.71_68, 0.44_95, 0.38_55], [0.49_96, 0.14_66, 0.99_96]] ) elif yolos_name == "yolos_s_dWr": A : Any = torch.tensor( [[-42.86_68, -24.10_49, -41.16_90], [-34.74_56, -14.12_74, -24.91_94], [-33.78_98, -12.19_46, -25.64_95]] ) A : Any = torch.tensor( [[0.55_87, 0.27_73, 0.06_05], [0.50_04, 0.30_14, 0.99_94], [0.49_99, 0.15_48, 0.99_94]] ) elif yolos_name == "yolos_base": A : Tuple = torch.tensor( [[-40.60_64, -24.30_84, -32.64_47], [-55.19_90, -30.77_19, -35.58_77], [-51.43_11, -33.35_07, -35.64_62]] ) A : Dict = torch.tensor( [[0.55_55, 0.27_94, 0.06_55], [0.90_49, 0.26_64, 0.18_94], [0.91_83, 0.19_84, 0.16_35]] ) else: raise ValueError(F'Unknown yolos_name: {yolos_name}' ) assert torch.allclose(logits[0, :3, :3] , snake_case__ , atol=1E-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , snake_case__ , atol=1E-4 ) Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) print(F'Saving model {yolos_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case__ ) if push_to_hub: A : Dict = { '''yolos_ti''': '''yolos-tiny''', '''yolos_s_200_pre''': '''yolos-small''', '''yolos_s_300_pre''': '''yolos-small-300''', '''yolos_s_dWr''': '''yolos-small-dwr''', '''yolos_base''': '''yolos-base''', } print('''Pushing to the hub...''' ) A : List[str] = model_mapping[yolos_name] image_processor.push_to_hub(snake_case__ , organization='''hustvl''' ) model.push_to_hub(snake_case__ , organization='''hustvl''' ) if __name__ == "__main__": lowercase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--yolos_name', default='yolos_s_200_pre', type=str, help=( 'Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',' ' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.' ), ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original state dict (.pth file).' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) lowercase : str = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
311
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : int = logging.get_logger(__name__) lowercase : int = { 'asapp/sew-tiny-100k': 'https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json', # See all SEW models at https://huggingface.co/models?filter=sew } class A ( __snake_case ): __magic_name__ = '''sew''' def __init__( self , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-5 , SCREAMING_SNAKE_CASE="group" , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , SCREAMING_SNAKE_CASE=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=0.05 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE="mean" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=256 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=2 , **SCREAMING_SNAKE_CASE , ) -> Tuple: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE , pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE ) A : Optional[Any] = hidden_size A : Any = feat_extract_norm A : Optional[int] = feat_extract_activation A : Tuple = list(SCREAMING_SNAKE_CASE ) A : List[str] = list(SCREAMING_SNAKE_CASE ) A : List[str] = list(SCREAMING_SNAKE_CASE ) A : int = conv_bias A : List[Any] = num_conv_pos_embeddings A : Tuple = num_conv_pos_embedding_groups A : int = len(self.conv_dim ) A : Dict = num_hidden_layers A : Optional[int] = intermediate_size A : Any = squeeze_factor A : int = hidden_act A : str = num_attention_heads A : Dict = hidden_dropout A : Optional[Any] = attention_dropout A : List[str] = activation_dropout A : Union[str, Any] = feat_proj_dropout A : Union[str, Any] = final_dropout A : int = layerdrop A : Optional[Any] = layer_norm_eps A : Any = initializer_range A : Tuple = vocab_size 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)`,''' F'but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)' F'= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 A : Optional[Any] = apply_spec_augment A : Optional[Any] = mask_time_prob A : Union[str, Any] = mask_time_length A : Optional[Any] = mask_time_min_masks A : str = mask_feature_prob A : Tuple = mask_feature_length A : Any = mask_feature_min_masks # ctc loss A : List[Any] = ctc_loss_reduction A : Dict = ctc_zero_infinity # sequence classification A : int = use_weighted_layer_sum A : Optional[int] = classifier_proj_size @property def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
311
1
'''simple docstring''' import math import tensorflow as tf from packaging import version def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Optional[Any] = tf.convert_to_tensor(snake_case__ ) A : List[Any] = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) )) return x * cdf def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Any = tf.convert_to_tensor(snake_case__ ) A : Dict = tf.cast(math.pi , x.dtype ) A : Optional[Any] = tf.cast(0.04_47_15 , x.dtype ) A : List[str] = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(snake_case__ , 3 )) )) return x * cdf def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Optional[int] = tf.convert_to_tensor(snake_case__ ) return x * tf.tanh(tf.math.softplus(snake_case__ ) ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Union[str, Any] = tf.convert_to_tensor(snake_case__ ) A : List[Any] = tf.cast(0.04_47_15 , x.dtype ) A : int = tf.cast(0.79_78_84_56_08 , x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Any = tf.convert_to_tensor(snake_case__ ) A : List[Any] = tf.cast(1.7_02 , x.dtype ) return x * tf.math.sigmoid(coeff * x ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' return tf.clip_by_value(_gelu(snake_case__ ) , -10 , 10 ) def lowerCAmelCase_ ( snake_case__ , snake_case__=-1 ): '''simple docstring''' A, A : Optional[Any] = tf.split(snake_case__ , 2 , axis=snake_case__ ) return a * tf.math.sigmoid(snake_case__ ) if version.parse(tf.version.VERSION) >= version.parse('2.4'): def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' return tf.keras.activations.gelu(snake_case__ , approximate=snake_case__ ) lowercase : Union[str, Any] = tf.keras.activations.gelu lowercase : str = approximate_gelu_wrap else: lowercase : Tuple = _gelu lowercase : Optional[int] = _gelu_new lowercase : str = { '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_ ( snake_case__ ): '''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() )}' )
311
'''simple docstring''' import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Dict = SwinConfig() A : List[Any] = swin_name.split('''_''' ) A : Tuple = name_split[1] A : Union[str, Any] = int(name_split[4] ) A : str = int(name_split[3][-1] ) if model_size == "tiny": A : Optional[int] = 96 A : Optional[Any] = (2, 2, 6, 2) A : Any = (3, 6, 12, 24) elif model_size == "small": A : Optional[int] = 96 A : str = (2, 2, 18, 2) A : Tuple = (3, 6, 12, 24) elif model_size == "base": A : int = 128 A : Optional[Any] = (2, 2, 18, 2) A : List[str] = (4, 8, 16, 32) else: A : Dict = 192 A : Optional[Any] = (2, 2, 18, 2) A : Optional[Any] = (6, 12, 24, 48) if "in22k" in swin_name: A : Dict = 2_1841 else: A : str = 1000 A : List[str] = '''huggingface/label-files''' A : Any = '''imagenet-1k-id2label.json''' A : Any = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='''dataset''' ) , '''r''' ) ) A : str = {int(snake_case__ ): v for k, v in idalabel.items()} A : Tuple = idalabel A : Tuple = {v: k for k, v in idalabel.items()} A : Tuple = img_size A : Dict = num_classes A : Optional[Any] = embed_dim A : str = depths A : str = num_heads A : Optional[int] = window_size return config def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if "patch_embed.proj" in name: A : Any = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: A : Tuple = name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: A : Optional[int] = '''encoder.''' + name if "attn.proj" in name: A : List[str] = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: A : List[str] = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: A : Any = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: A : Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: A : Dict = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: A : str = name.replace('''mlp.fc2''' , '''output.dense''' ) if name == "norm.weight": A : Tuple = '''layernorm.weight''' if name == "norm.bias": A : Tuple = '''layernorm.bias''' if "head" in name: A : Any = name.replace('''head''' , '''classifier''' ) else: A : List[Any] = '''swin.''' + name return name def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' for key in orig_state_dict.copy().keys(): A : Dict = orig_state_dict.pop(snake_case__ ) if "mask" in key: continue elif "qkv" in key: A : Dict = key.split('''.''' ) A : Optional[int] = int(key_split[1] ) A : List[str] = int(key_split[3] ) A : Optional[int] = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: A : Any = val[:dim, :] A : Dict = val[ dim : dim * 2, : ] A : List[str] = val[-dim:, :] else: A : Any = val[ :dim ] A : Optional[int] = val[ dim : dim * 2 ] A : Any = val[ -dim: ] else: A : str = val return orig_state_dict def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : Tuple = timm.create_model(snake_case__ , pretrained=snake_case__ ) timm_model.eval() A : Optional[Any] = get_swin_config(snake_case__ ) A : Optional[int] = SwinForImageClassification(snake_case__ ) model.eval() A : List[str] = convert_state_dict(timm_model.state_dict() , snake_case__ ) model.load_state_dict(snake_case__ ) A : Optional[int] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' A : Any = AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swin_name.replace('''_''' , '''-''' ) ) ) A : List[Any] = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) A : List[Any] = image_processor(images=snake_case__ , return_tensors='''pt''' ) A : Any = timm_model(inputs['''pixel_values'''] ) A : Optional[Any] = model(**snake_case__ ).logits assert torch.allclose(snake_case__ , snake_case__ , atol=1E-3 ) print(F'Saving model {swin_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case__ ) if __name__ == "__main__": lowercase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swin_name', default='swin_tiny_patch4_window7_224', type=str, help='Name of the Swin timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) lowercase : int = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
311
1
'''simple docstring''' from __future__ import annotations class A : def __init__( self , SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" A : Any = data A : Node | None = None A : Node | None = None def lowerCAmelCase_ ( snake_case__ ): # In Order traversal of the tree '''simple docstring''' if tree: display(tree.left ) print(tree.data ) display(tree.right ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' return 1 + max(depth_of_tree(tree.left ) , depth_of_tree(tree.right ) ) if tree else 0 def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def lowerCAmelCase_ ( ): # Main function for testing. '''simple docstring''' A : Tuple = Node(1 ) A : int = Node(2 ) A : Optional[Any] = Node(3 ) A : List[Any] = Node(4 ) A : Tuple = Node(5 ) A : Union[str, Any] = Node(6 ) A : Tuple = Node(7 ) A : Any = Node(8 ) A : int = Node(9 ) print(is_full_binary_tree(snake_case__ ) ) print(depth_of_tree(snake_case__ ) ) print('''Tree is: ''' ) display(snake_case__ ) if __name__ == "__main__": main()
311
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : Optional[int] = logging.get_logger(__name__) lowercase : Tuple = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class A ( __snake_case ): __magic_name__ = '''pix2struct_text_model''' __magic_name__ = ['''past_key_values'''] __magic_name__ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , SCREAMING_SNAKE_CASE=50244 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Optional[Any]: """simple docstring""" A : str = vocab_size A : List[str] = hidden_size A : List[Any] = d_kv A : Optional[Any] = d_ff A : Dict = num_layers A : Dict = num_heads A : Optional[int] = relative_attention_num_buckets A : Optional[Any] = relative_attention_max_distance A : Dict = dropout_rate A : Dict = layer_norm_epsilon A : Tuple = initializer_factor A : Union[str, Any] = use_cache A : int = eos_token_id A : List[str] = decoder_start_token_id # for backwards compatibility A : int = dense_act_fn super().__init__( pad_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , decoder_start_token_id=SCREAMING_SNAKE_CASE , tie_word_embeddings=SCREAMING_SNAKE_CASE , is_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) A, A : Optional[Any] = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": A : Union[str, Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A ( __snake_case ): __magic_name__ = '''pix2struct_vision_model''' def __init__( self , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=1e-10 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=4096 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=128 , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) A : List[str] = hidden_size A : Optional[Any] = patch_embed_hidden_size A : Union[str, Any] = d_ff A : Dict = dropout_rate A : str = num_hidden_layers A : Dict = num_attention_heads A : Tuple = initializer_range A : List[str] = initializer_factor A : Union[str, Any] = attention_dropout A : Tuple = layer_norm_eps A : int = dense_act_fn A : Optional[int] = seq_len A : Tuple = relative_attention_num_buckets A : str = relative_attention_max_distance A : Optional[Any] = d_kv @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) A, A : int = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": A : Optional[Any] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A ( __snake_case ): __magic_name__ = '''pix2struct''' __magic_name__ = True def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(tie_word_embeddings=SCREAMING_SNAKE_CASE , is_encoder_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) if text_config is None: A : Dict = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: A : str = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) A : Dict = PixaStructTextConfig(**SCREAMING_SNAKE_CASE ) A : Any = PixaStructVisionConfig(**SCREAMING_SNAKE_CASE ) A : Any = self.text_config.decoder_start_token_id A : Any = self.text_config.pad_token_id A : Dict = self.text_config.eos_token_id A : Union[str, Any] = initializer_factor A : Tuple = initializer_range A : Optional[Any] = self.initializer_range A : int = self.initializer_range A : Tuple = is_vqa @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Tuple = copy.deepcopy(self.__dict__ ) A : Dict = self.text_config.to_dict() A : int = self.vision_config.to_dict() A : Any = self.__class__.model_type return output
311
1
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional import evaluate import numpy as np import torch from datasets import load_dataset from PIL import Image from torchvision.transforms import ( CenterCrop, Compose, Normalize, RandomHorizontalFlip, RandomResizedCrop, Resize, ToTensor, ) import transformers from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForImageClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version lowercase : Union[str, 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-classification/requirements.txt') lowercase : str = list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys()) lowercase : Any = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' with open(snake_case__ , '''rb''' ) as f: A : Any = Image.open(snake_case__ ) return im.convert('''RGB''' ) @dataclass class A : __magic_name__ = field( default=__snake_case , metadata={ '''help''': '''Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).''' } , ) __magic_name__ = field( default=__snake_case , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __magic_name__ = field(default=__snake_case , metadata={'''help''': '''A folder containing the training data.'''} ) __magic_name__ = field(default=__snake_case , metadata={'''help''': '''A folder containing the validation data.'''} ) __magic_name__ = field( default=0.15 , metadata={'''help''': '''Percent to split off of train for validation.'''} ) __magic_name__ = field( default=__snake_case , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) __magic_name__ = field( default=__snake_case , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None): raise ValueError( '''You must specify either a dataset name from the hub or a train and/or validation directory.''' ) @dataclass class A : __magic_name__ = field( default='''google/vit-base-patch16-224-in21k''' , metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} , ) __magic_name__ = field( default=__snake_case , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(__snake_case )} , ) __magic_name__ = field( default=__snake_case , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) __magic_name__ = field( default=__snake_case , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) __magic_name__ = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) __magic_name__ = field(default=__snake_case , metadata={'''help''': '''Name or path of preprocessor config.'''} ) __magic_name__ = field( default=__snake_case , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) __magic_name__ = field( default=__snake_case , metadata={'''help''': '''Will enable to load a pretrained model whose head dimensions are different.'''} , ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : int = torch.stack([example['''pixel_values'''] for example in examples] ) A : str = torch.tensor([example['''labels'''] for example in examples] ) return {"pixel_values": pixel_values, "labels": labels} def lowerCAmelCase_ ( ): '''simple docstring''' A : Union[str, Any] = 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 : str = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: A, A, A : 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_image_classification''' , snake_case__ , snake_case__ ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() A : Tuple = training_args.get_process_log_level() logger.setLevel(snake_case__ ) transformers.utils.logging.set_verbosity(snake_case__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. A : Optional[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: A : 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.''' ) # Set seed before initializing model. set_seed(training_args.seed ) # Initialize our dataset and prepare it for the 'image-classification' task. if data_args.dataset_name is not None: A : str = load_dataset( data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir , task='''image-classification''' , use_auth_token=True if model_args.use_auth_token else None , ) else: A : int = {} if data_args.train_dir is not None: A : int = os.path.join(data_args.train_dir , '''**''' ) if data_args.validation_dir is not None: A : Optional[int] = os.path.join(data_args.validation_dir , '''**''' ) A : int = load_dataset( '''imagefolder''' , data_files=snake_case__ , cache_dir=model_args.cache_dir , task='''image-classification''' , ) # If we don't have a validation split, split off a percentage of train as validation. A : str = None if '''validation''' in dataset.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , snake_case__ ) and data_args.train_val_split > 0.0: A : Dict = dataset['''train'''].train_test_split(data_args.train_val_split ) A : List[str] = split['''train'''] A : str = split['''test'''] # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. A : int = dataset['''train'''].features['''labels'''].names A, A : List[Any] = {}, {} for i, label in enumerate(snake_case__ ): A : List[str] = str(snake_case__ ) A : Tuple = label # Load the accuracy metric from the datasets package A : Dict = evaluate.load('''accuracy''' ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(snake_case__ ): return metric.compute(predictions=np.argmax(p.predictions , axis=1 ) , references=p.label_ids ) A : int = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(snake_case__ ) , labelaid=snake_case__ , idalabel=snake_case__ , finetuning_task='''image-classification''' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) A : Dict = AutoModelForImageClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=snake_case__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) A : Any = AutoImageProcessor.from_pretrained( model_args.image_processor_name or model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # Define torchvision transforms to be applied to each image. if "shortest_edge" in image_processor.size: A : Optional[Any] = image_processor.size['''shortest_edge'''] else: A : Optional[Any] = (image_processor.size['''height'''], image_processor.size['''width''']) A : Optional[Any] = Normalize(mean=image_processor.image_mean , std=image_processor.image_std ) A : List[str] = Compose( [ RandomResizedCrop(snake_case__ ), RandomHorizontalFlip(), ToTensor(), normalize, ] ) A : Tuple = Compose( [ Resize(snake_case__ ), CenterCrop(snake_case__ ), ToTensor(), normalize, ] ) def train_transforms(snake_case__ ): A : List[Any] = [ _train_transforms(pil_img.convert('''RGB''' ) ) for pil_img in example_batch['''image'''] ] return example_batch def val_transforms(snake_case__ ): A : Optional[int] = [_val_transforms(pil_img.convert('''RGB''' ) ) for pil_img in example_batch['''image''']] return example_batch if training_args.do_train: if "train" not in dataset: raise ValueError('''--do_train requires a train dataset''' ) if data_args.max_train_samples is not None: A : Optional[Any] = ( dataset['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms dataset["train"].set_transform(snake_case__ ) if training_args.do_eval: if "validation" not in dataset: raise ValueError('''--do_eval requires a validation dataset''' ) if data_args.max_eval_samples is not None: A : Tuple = ( dataset['''validation'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms dataset["validation"].set_transform(snake_case__ ) # Initalize our trainer A : Dict = Trainer( model=snake_case__ , args=snake_case__ , train_dataset=dataset['''train'''] if training_args.do_train else None , eval_dataset=dataset['''validation'''] if training_args.do_eval else None , compute_metrics=snake_case__ , tokenizer=snake_case__ , data_collator=snake_case__ , ) # Training if training_args.do_train: A : Optional[int] = None if training_args.resume_from_checkpoint is not None: A : List[str] = training_args.resume_from_checkpoint elif last_checkpoint is not None: A : List[str] = last_checkpoint A : Tuple = trainer.train(resume_from_checkpoint=snake_case__ ) trainer.save_model() trainer.log_metrics('''train''' , train_result.metrics ) trainer.save_metrics('''train''' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: A : str = trainer.evaluate() trainer.log_metrics('''eval''' , snake_case__ ) trainer.save_metrics('''eval''' , snake_case__ ) # Write model card and (optionally) push to hub A : Any = { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''image-classification''', '''dataset''': data_args.dataset_name, '''tags''': ['''image-classification''', '''vision'''], } if training_args.push_to_hub: trainer.push_to_hub(**snake_case__ ) else: trainer.create_model_card(**snake_case__ ) if __name__ == "__main__": main()
311
'''simple docstring''' from __future__ import annotations def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : List[str] = 2 A : Dict = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(snake_case__ ) if n > 1: factors.append(snake_case__ ) return factors if __name__ == "__main__": import doctest doctest.testmod()
311
1
'''simple docstring''' import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' return np.dot(snake_case__ , snake_case__ ) class A : def __init__( self , *, SCREAMING_SNAKE_CASE = np.inf , SCREAMING_SNAKE_CASE = "linear" , SCREAMING_SNAKE_CASE = 0.0 , ) -> None: """simple docstring""" A : int = regularization A : Any = gamma if kernel == "linear": A : Any = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError('''rbf kernel requires gamma''' ) if not isinstance(self.gamma , (float, int) ): raise ValueError('''gamma must be float or int''' ) if not self.gamma > 0: raise ValueError('''gamma must be > 0''' ) A : Union[str, Any] = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: A : Optional[Any] = F'Unknown kernel: {kernel}' raise ValueError(SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> float: """simple docstring""" return np.dot(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> float: """simple docstring""" return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" A : List[Any] = observations A : Optional[int] = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((A), ) : Union[str, Any] = np.shape(SCREAMING_SNAKE_CASE ) def to_minimize(SCREAMING_SNAKE_CASE ) -> float: A : str = 0 ((A), ) : Dict = np.shape(SCREAMING_SNAKE_CASE ) for i in range(SCREAMING_SNAKE_CASE ): for j in range(SCREAMING_SNAKE_CASE ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(SCREAMING_SNAKE_CASE ) A : Optional[Any] = LinearConstraint(SCREAMING_SNAKE_CASE , 0 , 0 ) A : str = Bounds(0 , self.regularization ) A : List[str] = minimize( SCREAMING_SNAKE_CASE , np.ones(SCREAMING_SNAKE_CASE ) , bounds=SCREAMING_SNAKE_CASE , constraints=[ly_contraint] ).x A : Any = l_star # calculating mean offset of separation plane to points A : Dict = 0 for i in range(SCREAMING_SNAKE_CASE ): for j in range(SCREAMING_SNAKE_CASE ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) A : Tuple = s / n def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" A : Optional[Any] = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , SCREAMING_SNAKE_CASE ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
311
'''simple docstring''' # Function to print upper half of diamond (pyramid) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for i in range(0 , snake_case__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(''' ''' , end='''''' ) for _ in range(0 , i + 1 ): # printing stars print('''* ''' , end='''''' ) print() def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for i in range(snake_case__ , 0 , -1 ): for _ in range(snake_case__ , 0 , -1 ): # printing stars print('''* ''' , end='''''' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(''' ''' , end='''''' ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if n <= 0: print(''' ... .... nothing printing :(''' ) return floyd(snake_case__ ) # upper half reverse_floyd(snake_case__ ) # lower half if __name__ == "__main__": print(R'| /\ | |- | |- |--| |\ /| |-') print(R'|/ \| |- |_ |_ |__| | \/ | |_') lowercase : List[str] = 1 while K: lowercase : List[Any] = int(input('enter the number and , and see the magic : ')) print() pretty_print(user_number) lowercase : Any = int(input('press 0 to exit... and 1 to continue...')) print('Good Bye...')
311
1
'''simple docstring''' import argparse from argparse import Namespace import torch from torch import nn from transformers import XGLMConfig, XGLMForCausalLM def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Optional[Any] = [ '''decoder.version''', '''decoder.output_projection.weight''', '''_float_tensor''', '''decoder.embed_positions._float_tensor''', ] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A, A : Any = emb.weight.shape A : str = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) A : Dict = emb.weight.data return lin_layer def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : List[Any] = torch.load(snake_case__ , map_location='''cpu''' ) A : int = Namespace(**checkpoint['''cfg''']['''model'''] ) A : Union[str, Any] = checkpoint['''model'''] remove_ignore_keys_(snake_case__ ) A : Dict = state_dict['''decoder.embed_tokens.weight'''].shape[0] A : List[str] = {key.replace('''decoder''' , '''model''' ): val for key, val in state_dict.items()} A : List[Any] = XGLMConfig( vocab_size=snake_case__ , max_position_embeddings=args.max_target_positions , num_layers=args.decoder_layers , attention_heads=args.decoder_attention_heads , ffn_dim=args.decoder_ffn_embed_dim , d_model=args.decoder_embed_dim , layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='''gelu''' , scale_embedding=not args.no_scale_embedding , tie_word_embeddings=args.share_decoder_input_output_embed , ) A : Optional[Any] = XGLMForCausalLM(snake_case__ ) A : List[Any] = model.load_state_dict(snake_case__ , strict=snake_case__ ) print(snake_case__ ) A : List[str] = make_linear_from_emb(model.model.embed_tokens ) return model if __name__ == "__main__": lowercase : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') lowercase : List[Any] = parser.parse_args() lowercase : Tuple = convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path) model.save_pretrained(args.pytorch_dump_folder_path)
311
'''simple docstring''' # limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class A ( __snake_case ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 50 , SCREAMING_SNAKE_CASE = "pil" , SCREAMING_SNAKE_CASE = True , **SCREAMING_SNAKE_CASE , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" A : List[Any] = torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=SCREAMING_SNAKE_CASE , ) A : Optional[Any] = image.to(self.device ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output A : Tuple = self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 A : List[Any] = self.scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample A : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) A : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": A : List[Any] = self.numpy_to_pil(SCREAMING_SNAKE_CASE ) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE ), "This is a local test"
311
1
'''simple docstring''' from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def lowerCAmelCase_ ( ): '''simple docstring''' A : Dict = [randint(-1000 , 1000 ) for i in range(10 )] A : Dict = randint(-5000 , 5000 ) return (arr, r) lowercase : Any = make_dataset() def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' for triplet in permutations(snake_case__ , 3 ): if sum(snake_case__ ) == target: return tuple(sorted(snake_case__ ) ) return (0, 0, 0) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' arr.sort() A : Tuple = len(snake_case__ ) for i in range(n - 1 ): A, A : Optional[Any] = i + 1, n - 1 while left < right: if arr[i] + arr[left] + arr[right] == target: return (arr[i], arr[left], arr[right]) elif arr[i] + arr[left] + arr[right] < target: left += 1 elif arr[i] + arr[left] + arr[right] > target: right -= 1 return (0, 0, 0) def lowerCAmelCase_ ( ): '''simple docstring''' A : Optional[Any] = ''' from __main__ import dataset, triplet_sum1, triplet_sum2 ''' A : str = ''' triplet_sum1(*dataset) ''' A : List[Any] = ''' triplet_sum2(*dataset) ''' A : Any = repeat(setup=snake_case__ , stmt=snake_case__ , repeat=5 , number=1_0000 ) A : Dict = repeat(setup=snake_case__ , stmt=snake_case__ , repeat=5 , number=1_0000 ) return (min(snake_case__ ), min(snake_case__ )) if __name__ == "__main__": from doctest import testmod testmod() lowercase : List[str] = solution_times() print(f'''The time for naive implementation is {times[0]}.''') print(f'''The time for optimized implementation is {times[1]}.''')
311
'''simple docstring''' import unittest from transformers import BertGenerationConfig, 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 BertGenerationDecoder, BertGenerationEncoder class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=50 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=None , ) -> str: """simple docstring""" A : Any = parent A : List[Any] = batch_size A : Union[str, Any] = seq_length A : Any = is_training A : int = use_input_mask A : Union[str, Any] = vocab_size A : List[Any] = hidden_size A : List[Any] = num_hidden_layers A : Optional[int] = num_attention_heads A : str = intermediate_size A : Tuple = hidden_act A : Union[str, Any] = hidden_dropout_prob A : Union[str, Any] = attention_probs_dropout_prob A : int = max_position_embeddings A : Optional[int] = initializer_range A : Any = use_labels A : Optional[int] = scope def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Optional[int] = None if self.use_input_mask: A : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: A : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Dict = self.get_config() return config, input_ids, input_mask, token_labels def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" return BertGenerationConfig( 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 , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" ( ( A ), ( A ), ( A ), ( A ), ) : Any = self.prepare_config_and_inputs() A : Tuple = True A : int = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A : str = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" A : List[str] = BertGenerationEncoder(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) A : int = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> Union[str, Any]: """simple docstring""" A : List[str] = True A : Union[str, Any] = BertGenerationEncoder(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , ) A : List[Any] = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" A : Optional[Any] = True A : Tuple = True A : Optional[int] = BertGenerationDecoder(config=SCREAMING_SNAKE_CASE ).to(SCREAMING_SNAKE_CASE ).eval() # first forward pass A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , use_cache=SCREAMING_SNAKE_CASE , ) A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A : List[str] = ids_tensor((self.batch_size, 3) , config.vocab_size ) A : Tuple = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and A : Dict = torch.cat([input_ids, next_tokens] , dim=-1 ) A : List[str] = torch.cat([input_mask, next_mask] , dim=-1 ) A : str = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE , )['''hidden_states'''][0] A : Any = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE , encoder_attention_mask=SCREAMING_SNAKE_CASE , past_key_values=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE , )['''hidden_states'''][0] # select random slice A : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() A : List[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() A : str = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" A : Optional[Any] = BertGenerationDecoder(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Optional[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A, A, A, A : Optional[int] = self.prepare_config_and_inputs() A : str = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class A ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () __magic_name__ = (BertGenerationDecoder,) if is_torch_available() else () __magic_name__ = ( {'''feature-extraction''': BertGenerationEncoder, '''text-generation''': BertGenerationDecoder} if is_torch_available() else {} ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : List[str] = BertGenerationEncoderTester(self ) A : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A, A, A, A : Tuple = self.model_tester.prepare_config_and_inputs() A : str = '''bert''' self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : int = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" ( ( A ), ( A ), ( A ), ( A ), ( A ), ( A ), ) : Tuple = self.model_tester.prepare_config_and_inputs_for_decoder() A : Union[str, Any] = None self.model_tester.create_and_check_model_as_decoder( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*SCREAMING_SNAKE_CASE ) @slow def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Optional[Any] = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) A : Optional[Any] = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]] ) with torch.no_grad(): A : Dict = model(SCREAMING_SNAKE_CASE )[0] A : Optional[Any] = torch.Size([1, 8, 1024] ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : Dict = torch.tensor( [[[0.1_775, 0.0_083, -0.0_321], [1.6_002, 0.1_287, 0.3_912], [2.1_473, 0.5_791, 0.6_066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[Any] = BertGenerationDecoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) A : Dict = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]] ) with torch.no_grad(): A : Optional[Any] = model(SCREAMING_SNAKE_CASE )[0] A : Optional[Any] = torch.Size([1, 8, 50358] ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) A : Any = torch.tensor( [[[-0.5_788, -2.5_994, -3.7_054], [0.0_438, 4.7_997, 1.8_795], [1.5_862, 6.6_409, 4.4_638]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
1
'''simple docstring''' # Function to print upper half of diamond (pyramid) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for i in range(0 , snake_case__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(''' ''' , end='''''' ) for _ in range(0 , i + 1 ): # printing stars print('''* ''' , end='''''' ) print() def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for i in range(snake_case__ , 0 , -1 ): for _ in range(snake_case__ , 0 , -1 ): # printing stars print('''* ''' , end='''''' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(''' ''' , end='''''' ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if n <= 0: print(''' ... .... nothing printing :(''' ) return floyd(snake_case__ ) # upper half reverse_floyd(snake_case__ ) # lower half if __name__ == "__main__": print(R'| /\ | |- | |- |--| |\ /| |-') print(R'|/ \| |- |_ |_ |__| | \/ | |_') lowercase : List[str] = 1 while K: lowercase : List[Any] = int(input('enter the number and , and see the magic : ')) print() pretty_print(user_number) lowercase : Any = int(input('press 0 to exit... and 1 to continue...')) print('Good Bye...')
311
'''simple docstring''' import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' return 1.0 / (1.0 + np.exp(-_outputs )) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Optional[int] = np.max(_outputs , axis=-1 , keepdims=snake_case__ ) A : Any = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=snake_case__ ) class A ( __snake_case ): __magic_name__ = '''sigmoid''' __magic_name__ = '''softmax''' __magic_name__ = '''none''' @add_end_docstrings( __snake_case , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class A ( __snake_case ): __magic_name__ = False __magic_name__ = ClassificationFunction.NONE def __init__( self , **SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE="" , **SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" A : Optional[Any] = tokenizer_kwargs A : int = {} if hasattr(self.model.config , '''return_all_scores''' ) and return_all_scores is None: A : int = self.model.config.return_all_scores if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) or top_k is None: A : Union[str, Any] = top_k A : Dict = False elif return_all_scores is not None: warnings.warn( '''`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of''' ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.''' , SCREAMING_SNAKE_CASE , ) if return_all_scores: A : Optional[int] = None else: A : Dict = 1 if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : Dict = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: A : int = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : str = super().__call__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. A : Any = '''top_k''' not in kwargs if isinstance(args[0] , SCREAMING_SNAKE_CASE ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Dict[str, GenericTensor]: """simple docstring""" A : List[Any] = self.framework if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): return self.tokenizer(**SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and len(SCREAMING_SNAKE_CASE ) == 1 and isinstance(inputs[0] , SCREAMING_SNAKE_CASE ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a''' ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.''' ) return self.tokenizer(SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" return self.model(**SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=True ) -> List[str]: """simple docstring""" if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: A : Optional[int] = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: A : Any = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , '''function_to_apply''' ) and function_to_apply is None: A : Optional[int] = self.model.config.function_to_apply else: A : Optional[int] = ClassificationFunction.NONE A : Any = model_outputs['''logits'''][0] A : List[Any] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: A : int = sigmoid(SCREAMING_SNAKE_CASE ) elif function_to_apply == ClassificationFunction.SOFTMAX: A : Any = softmax(SCREAMING_SNAKE_CASE ) elif function_to_apply == ClassificationFunction.NONE: A : int = outputs else: raise ValueError(F'Unrecognized `function_to_apply` argument: {function_to_apply}' ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} A : int = [ {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(SCREAMING_SNAKE_CASE ) ] if not _legacy: dict_scores.sort(key=lambda SCREAMING_SNAKE_CASE : x["score"] , reverse=SCREAMING_SNAKE_CASE ) if top_k is not None: A : Union[str, Any] = dict_scores[:top_k] return dict_scores
311
1
'''simple docstring''' import argparse import intel_extension_for_pytorch as ipex import torch from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline lowercase : 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') lowercase : List[Any] = parser.parse_args() lowercase : Union[str, Any] = 'cpu' lowercase : int = 'a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings' lowercase : str = 'path-to-your-trained-model' lowercase : Optional[Any] = StableDiffusionPipeline.from_pretrained(model_id) if args.dpm: lowercase : Dict = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) lowercase : Dict = pipe.to(device) # to channels last lowercase : Optional[Any] = pipe.unet.to(memory_format=torch.channels_last) lowercase : Dict = pipe.vae.to(memory_format=torch.channels_last) lowercase : List[str] = pipe.text_encoder.to(memory_format=torch.channels_last) if pipe.requires_safety_checker: lowercase : Any = pipe.safety_checker.to(memory_format=torch.channels_last) # optimize with ipex lowercase : Optional[int] = torch.randn(2, 4, 64, 64) lowercase : Optional[int] = torch.rand(1) * 9_99 lowercase : Dict = torch.randn(2, 77, 7_68) lowercase : str = (sample, timestep, encoder_hidden_status) try: lowercase : Any = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example) except Exception: lowercase : str = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True) lowercase : Any = ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True) lowercase : Optional[Any] = ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True) if pipe.requires_safety_checker: lowercase : int = ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True) # compute lowercase : Tuple = 6_66 lowercase : int = torch.Generator(device).manual_seed(seed) lowercase : Tuple = {'generator': generator} if args.steps is not None: lowercase : List[Any] = args.steps with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa): lowercase : Union[str, Any] = pipe(prompt, **generate_kwargs).images[0] # save image image.save('generated.png')
311
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCAmelCase_ ( snake_case__ = "laptop" ): '''simple docstring''' A : Tuple = F'https://www.amazon.in/laptop/s?k={product}' A : Optional[int] = { '''User-Agent''': '''Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36''', '''Accept-Language''': '''en-US, en;q=0.5''', } A : Any = BeautifulSoup(requests.get(snake_case__ , headers=snake_case__ ).text ) # Initialize a Pandas dataframe with the column titles A : List[str] = DataFrame( columns=[ '''Product Title''', '''Product Link''', '''Current Price of the product''', '''Product Rating''', '''MRP of the product''', '''Discount''', ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( '''div''' , attrs={'''class''': '''s-result-item''', '''data-component-type''': '''s-search-result'''} , ) , soup.find_all('''div''' , attrs={'''class''': '''a-row a-size-base a-color-base'''} ) , ): try: A : Optional[Any] = item.ha.text A : Union[str, Any] = '''https://www.amazon.in/''' + item.ha.a['''href'''] A : Tuple = item.find('''span''' , attrs={'''class''': '''a-offscreen'''} ).text try: A : int = item.find('''span''' , attrs={'''class''': '''a-icon-alt'''} ).text except AttributeError: A : Optional[int] = '''Not available''' try: A : str = ( '''₹''' + item.find( '''span''' , attrs={'''class''': '''a-price a-text-price'''} ).text.split('''₹''' )[1] ) except AttributeError: A : List[Any] = '''''' try: A : Dict = float( ( ( float(product_mrp.strip('''₹''' ).replace(''',''' , '''''' ) ) - float(product_price.strip('''₹''' ).replace(''',''' , '''''' ) ) ) / float(product_mrp.strip('''₹''' ).replace(''',''' , '''''' ) ) ) * 100 ) except ValueError: A : str = float('''nan''' ) except AttributeError: pass A : Union[str, Any] = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] A : List[str] = ''' ''' A : Optional[Any] = ''' ''' data_frame.index += 1 return data_frame if __name__ == "__main__": lowercase : Union[str, Any] = 'headphones' get_amazon_product_data(product).to_csv(f'''Amazon Product Data for {product}.csv''')
311
1
'''simple docstring''' from collections.abc import Generator from math import sin def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if len(snake_case__ ) != 32: raise ValueError('''Input must be of length 32''' ) A : Dict = B'''''' for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if i < 0: raise ValueError('''Input must be non-negative''' ) A : Dict = format(snake_case__ , '''08x''' )[-8:] A : Tuple = B'''''' for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode('''utf-8''' ) return little_endian_hex def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : int = B'''''' for char in message: bit_string += format(snake_case__ , '''08b''' ).encode('''utf-8''' ) A : Union[str, Any] = format(len(snake_case__ ) , '''064b''' ).encode('''utf-8''' ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(snake_case__ ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if len(snake_case__ ) % 512 != 0: raise ValueError('''Input must have length that\'s a multiple of 512''' ) for pos in range(0 , len(snake_case__ ) , 512 ): A : str = bit_string[pos : pos + 512] A : List[str] = [] for i in range(0 , 512 , 32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) ) yield block_words def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if i < 0: raise ValueError('''Input must be non-negative''' ) A : str = format(snake_case__ , '''032b''' ) A : List[str] = '''''' for c in i_str: new_str += "1" if c == "0" else "0" return int(snake_case__ , 2 ) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' return (a + b) % 2**32 def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if i < 0: raise ValueError('''Input must be non-negative''' ) if shift < 0: raise ValueError('''Shift must be non-negative''' ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Any = preprocess(snake_case__ ) A : Tuple = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states A : str = 0X67452301 A : Dict = 0XEFCDAB89 A : Optional[Any] = 0X98BADCFE A : str = 0X10325476 A : List[Any] = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(snake_case__ ): A : List[str] = aa A : Any = ba A : Optional[Any] = ca A : Tuple = da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f A : Union[str, Any] = d ^ (b & (c ^ d)) A : Tuple = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f A : str = c ^ (d & (b ^ c)) A : Union[str, Any] = (5 * i + 1) % 16 elif i <= 47: A : str = b ^ c ^ d A : int = (3 * i + 5) % 16 else: A : Optional[Any] = c ^ (b | not_aa(snake_case__ )) A : Optional[Any] = (7 * i) % 16 A : Optional[int] = (f + a + added_consts[i] + block_words[g]) % 2**32 A : Tuple = d A : List[str] = c A : Any = b A : Optional[int] = sum_aa(snake_case__ , left_rotate_aa(snake_case__ , shift_amounts[i] ) ) # Add hashed chunk to running total A : Tuple = sum_aa(snake_case__ , snake_case__ ) A : Tuple = sum_aa(snake_case__ , snake_case__ ) A : Optional[Any] = sum_aa(snake_case__ , snake_case__ ) A : str = sum_aa(snake_case__ , snake_case__ ) A : Any = reformat_hex(snake_case__ ) + reformat_hex(snake_case__ ) + reformat_hex(snake_case__ ) + reformat_hex(snake_case__ ) return digest if __name__ == "__main__": import doctest doctest.testmod()
311
'''simple docstring''' import colorsys from PIL import Image # type: ignore def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : Optional[int] = x A : str = y for step in range(snake_case__ ): # noqa: B007 A : str = a * a - b * b + x A : List[str] = 2 * a * b + y A : str = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255 ) for i in colorsys.hsv_to_rgb(snake_case__ , 1 , 1 ) ) def lowerCAmelCase_ ( snake_case__ = 800 , snake_case__ = 600 , snake_case__ = -0.6 , snake_case__ = 0 , snake_case__ = 3.2 , snake_case__ = 50 , snake_case__ = True , ): '''simple docstring''' A : List[Any] = Image.new('''RGB''' , (image_width, image_height) ) A : Tuple = img.load() # loop through the image-coordinates for image_x in range(snake_case__ ): for image_y in range(snake_case__ ): # determine the figure-coordinates based on the image-coordinates A : Optional[int] = figure_width / image_width * image_height A : Tuple = figure_center_x + (image_x / image_width - 0.5) * figure_width A : List[str] = figure_center_y + (image_y / image_height - 0.5) * figure_height A : str = get_distance(snake_case__ , snake_case__ , snake_case__ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: A : str = get_color_coded_rgb(snake_case__ ) else: A : List[Any] = get_black_and_white_rgb(snake_case__ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure lowercase : Optional[Any] = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
311
1
'''simple docstring''' from math import ceil def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : Optional[Any] = list(range(0 , snake_case__ ) ) A : List[str] = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check A : Tuple = [] for i in device_map_blocks: if device_map_blocks.count(snake_case__ ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(snake_case__ ) # Missing blocks A : int = [i for i in blocks if i not in device_map_blocks] A : List[str] = [i for i in device_map_blocks if i not in blocks] if len(snake_case__ ) != 0: raise ValueError( '''Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device.''' ''' These attention blocks were specified more than once: ''' + str(snake_case__ ) ) if len(snake_case__ ) != 0: raise ValueError( '''There are attention blocks for this model that are not specified in the device_map. Add these attention ''' '''blocks to a device on the device_map: ''' + str(snake_case__ ) ) if len(snake_case__ ) != 0: raise ValueError( '''The device_map contains more attention blocks than this model has. Remove these from the device_map:''' + str(snake_case__ ) ) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : List[Any] = list(range(snake_case__ ) ) A : Union[str, Any] = int(ceil(n_layers / len(snake_case__ ) ) ) A : str = [layers[i : i + n_blocks] for i in range(0 , snake_case__ , snake_case__ )] return dict(zip(snake_case__ , snake_case__ ) )
311
'''simple docstring''' import argparse import importlib from pathlib import Path # Test all the extensions added in the setup lowercase : Optional[int] = [ 'kernels/rwkv/wkv_cuda.cu', 'kernels/rwkv/wkv_op.cpp', 'kernels/deformable_detr/ms_deform_attn.h', 'kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh', 'models/graphormer/algos_graphormer.pyx', ] def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' for file in FILES_TO_FIND: if not (transformers_path / file).exists(): return False return True if __name__ == "__main__": lowercase : str = argparse.ArgumentParser() parser.add_argument('--check_lib', action='store_true', help='Whether to check the build or the actual package.') lowercase : Optional[Any] = parser.parse_args() if args.check_lib: lowercase : List[Any] = importlib.import_module('transformers') lowercase : str = Path(transformers_module.__file__).parent else: lowercase : List[Any] = Path.cwd() / 'build/lib/transformers' if not test_custom_files_are_present(transformers_path): raise ValueError('The built release does not contain the custom files. Fix this before going further!')
311
1
'''simple docstring''' from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging lowercase : Optional[int] = logging.get_logger(__name__) class A ( __snake_case ): __magic_name__ = ['''audio_values''', '''audio_mask'''] def __init__( self , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=[16, 16] , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=44100 , SCREAMING_SNAKE_CASE=86 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=0.0 , **SCREAMING_SNAKE_CASE , ) -> Optional[int]: """simple docstring""" super().__init__( feature_size=SCREAMING_SNAKE_CASE , sampling_rate=SCREAMING_SNAKE_CASE , padding_value=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) A : List[Any] = spectrogram_length A : str = num_channels A : Optional[Any] = patch_size A : int = feature_size // self.patch_size[1] A : int = n_fft A : Optional[int] = sampling_rate // hop_length_to_sampling_rate A : int = sampling_rate A : Optional[int] = padding_value A : List[Any] = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=SCREAMING_SNAKE_CASE , min_frequency=0.0 , max_frequency=22_050.0 , sampling_rate=SCREAMING_SNAKE_CASE , norm='''slaney''' , mel_scale='''slaney''' , ).T def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> np.ndarray: """simple docstring""" A : Union[str, Any] = spectrogram( SCREAMING_SNAKE_CASE , window_function(self.n_fft , '''hann''' ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters.T , log_mel='''dB''' , db_range=80.0 , ) A : Tuple = log_spec[:, :-1] A : Any = log_spec - 20.0 A : Dict = np.clip(log_spec / 40.0 , -2.0 , 0.0 ) + 1.0 return log_spec def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , **SCREAMING_SNAKE_CASE , ) -> BatchFeature: """simple docstring""" if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( '''This feature extractor is set to support sampling rate''' F' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled' F' with {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) A : Any = isinstance(SCREAMING_SNAKE_CASE , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(F'Only mono-channel audio is supported for input to {self}' ) A : Optional[Any] = is_batched_numpy or ( isinstance(SCREAMING_SNAKE_CASE , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: A : Dict = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE , np.ndarray ): A : List[str] = np.asarray(SCREAMING_SNAKE_CASE , dtype=np.floataa ) elif isinstance(SCREAMING_SNAKE_CASE , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): A : Optional[Any] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: A : int = [np.asarray([raw_speech] ).T] # Convert audio signals to log mel spectrograms, truncate by time axis A : str = [ self._np_extract_fbank_features(waveform.squeeze() ).T[: self.spectrogram_length] for waveform in raw_speech ] if isinstance(audio_features[0] , SCREAMING_SNAKE_CASE ): A : Any = [np.asarray(SCREAMING_SNAKE_CASE , dtype=np.floataa ) for feature in audio_features] # Create audio attention mask A : List[Any] = max( [ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len for feature in audio_features] ) # The maximum number of audio patches in a batch if return_attention_mask: A : str = [ (ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [1] + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [0] for feature in audio_features ] A : List[Any] = np.array(SCREAMING_SNAKE_CASE ).astype(np.floataa ) # convert into correct format for padding A : Optional[Any] = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch A : str = np.ones([len(SCREAMING_SNAKE_CASE ), 1, max_time_len, self.feature_size] ).astype(np.floataa ) A : str = padded_audio_features * self.padding_value for i in range(len(SCREAMING_SNAKE_CASE ) ): A : List[Any] = audio_features[i] A : Tuple = feature # return as BatchFeature if return_attention_mask: A : Optional[int] = {'''audio_values''': padded_audio_features, '''audio_mask''': audio_mask} else: A : Union[str, Any] = {'''audio_values''': padded_audio_features} A : int = BatchFeature(data=SCREAMING_SNAKE_CASE , tensor_type=SCREAMING_SNAKE_CASE ) return encoded_inputs
311
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig 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 ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=30 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=2 , ) -> List[str]: """simple docstring""" A : List[str] = parent A : Optional[Any] = batch_size A : Tuple = image_size A : int = patch_size A : Optional[int] = num_channels A : str = is_training A : List[Any] = use_labels A : Any = hidden_size A : Any = num_hidden_layers A : Optional[int] = num_attention_heads A : Any = intermediate_size A : List[str] = hidden_act A : str = hidden_dropout_prob A : Tuple = attention_probs_dropout_prob A : Any = type_sequence_label_size A : Optional[int] = initializer_range A : Dict = scope A : Tuple = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) A : List[Any] = (image_size // patch_size) ** 2 A : Tuple = num_patches + 2 def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A : Tuple = None if self.use_labels: A : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Tuple = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" return DeiTConfig( 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=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : Any = TFDeiTModel(config=SCREAMING_SNAKE_CASE ) A : str = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" A : Tuple = TFDeiTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE ) A : List[Any] = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A : Optional[int] = 1 A : str = TFDeiTForMaskedImageModeling(SCREAMING_SNAKE_CASE ) A : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Tuple = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" A : str = self.type_sequence_label_size A : Optional[Any] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE ) A : Optional[Any] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images A : Optional[Any] = 1 A : List[str] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE ) A : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Optional[int] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Optional[int] = self.prepare_config_and_inputs() A, A, A : Tuple = config_and_inputs A : Any = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class A ( __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) __magic_name__ = ( { '''feature-extraction''': TFDeiTModel, '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) __magic_name__ = False __magic_name__ = False __magic_name__ = False __magic_name__ = False def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = TFDeiTModelTester(self ) A : Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''DeiT does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" pass def __lowerCAmelCase ( self ) -> str: """simple docstring""" A, A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) A : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE , tf.keras.layers.Dense ) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A, A : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) A : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A : Union[str, Any] = [*signature.parameters.keys()] A : List[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ) -> Tuple: """simple docstring""" A : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def __lowerCAmelCase ( self ) -> str: """simple docstring""" for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A : List[str] = TFDeiTModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_ ( ): '''simple docstring''' A : str = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class A ( unittest.TestCase ): @cached_property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) if is_vision_available() else None ) @slow def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Union[str, Any] = TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) A : Dict = self.default_image_processor A : List[str] = prepare_img() A : Any = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='''tf''' ) # forward pass A : Optional[int] = model(**SCREAMING_SNAKE_CASE ) # verify the logits A : List[Any] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE ) A : str = tf.constant([-1.0_266, 0.1_912, -1.2_861] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
311
1
'''simple docstring''' import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A ( __snake_case , unittest.TestCase ): __magic_name__ = AudioLDMPipeline __magic_name__ = TEXT_TO_AUDIO_PARAMS __magic_name__ = TEXT_TO_AUDIO_BATCH_PARAMS __magic_name__ = frozenset( [ '''num_inference_steps''', '''num_waveforms_per_prompt''', '''generator''', '''latents''', '''output_type''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" torch.manual_seed(0 ) A : str = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=(32, 64) , class_embed_type='''simple_projection''' , projection_class_embeddings_input_dim=32 , class_embeddings_concat=SCREAMING_SNAKE_CASE , ) A : str = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) torch.manual_seed(0 ) A : Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) A : List[Any] = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) A : List[str] = ClapTextModelWithProjection(SCREAMING_SNAKE_CASE ) A : int = RobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-roberta''' , model_max_length=77 ) A : int = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=16000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=SCREAMING_SNAKE_CASE , ) A : List[str] = SpeechTaHifiGan(SCREAMING_SNAKE_CASE ) A : List[str] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''vocoder''': vocoder, } return components def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0 ) -> List[Any]: """simple docstring""" if str(SCREAMING_SNAKE_CASE ).startswith('''mps''' ): A : Any = torch.manual_seed(SCREAMING_SNAKE_CASE ) else: A : Optional[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(SCREAMING_SNAKE_CASE ) A : Dict = { '''prompt''': '''A hammer hitting a wooden surface''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, } return inputs def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Optional[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator A : Union[str, Any] = self.get_dummy_components() A : str = AudioLDMPipeline(**SCREAMING_SNAKE_CASE ) A : Any = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) A : Any = self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) A : int = audioldm_pipe(**SCREAMING_SNAKE_CASE ) A : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE ) == 256 A : Optional[Any] = audio[:10] A : int = np.array( [-0.0_050, 0.0_050, -0.0_060, 0.0_033, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_033] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Union[str, Any] = self.get_dummy_components() A : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE ) A : Dict = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) A : Tuple = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) A : Any = self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) A : Optional[int] = 3 * [inputs['''prompt''']] # forward A : Dict = audioldm_pipe(**SCREAMING_SNAKE_CASE ) A : List[str] = output.audios[0] A : Dict = self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) A : Optional[Any] = 3 * [inputs.pop('''prompt''' )] A : Any = 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 : List[Any] = text_inputs['''input_ids'''].to(SCREAMING_SNAKE_CASE ) A : str = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE , ) A : Any = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state A : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE , dim=-1 ) A : Optional[int] = prompt_embeds # forward A : Tuple = audioldm_pipe(**SCREAMING_SNAKE_CASE ) A : Tuple = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : List[Any] = self.get_dummy_components() A : Optional[int] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE ) A : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) A : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) A : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) A : Dict = 3 * ['''this is a negative prompt'''] A : Dict = negative_prompt A : str = 3 * [inputs['''prompt''']] # forward A : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE ) A : str = output.audios[0] A : int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) A : List[Any] = 3 * [inputs.pop('''prompt''' )] A : str = [] for p in [prompt, negative_prompt]: A : Union[str, Any] = 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 : Any = text_inputs['''input_ids'''].to(SCREAMING_SNAKE_CASE ) A : Any = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE , ) A : Any = text_embeds.text_embeds # additional L_2 normalization over each hidden-state A : Any = F.normalize(SCREAMING_SNAKE_CASE , dim=-1 ) embeds.append(SCREAMING_SNAKE_CASE ) A, A : Tuple = embeds # forward A : Optional[int] = audioldm_pipe(**SCREAMING_SNAKE_CASE ) A : List[str] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator A : Union[str, Any] = self.get_dummy_components() A : Tuple = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE ) A : Optional[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE ) A : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) A : Any = self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) A : Optional[int] = '''egg cracking''' A : Any = audioldm_pipe(**SCREAMING_SNAKE_CASE , negative_prompt=SCREAMING_SNAKE_CASE ) A : str = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE ) == 256 A : Dict = audio[:10] A : Dict = np.array( [-0.0_051, 0.0_050, -0.0_060, 0.0_034, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_032] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : str = '''cpu''' # ensure determinism for the device-dependent torch.Generator A : Optional[int] = self.get_dummy_components() A : Tuple = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE ) A : Optional[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE ) A : Tuple = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) A : Optional[Any] = '''A hammer hitting a wooden surface''' # test num_waveforms_per_prompt=1 (default) A : Any = audioldm_pipe(SCREAMING_SNAKE_CASE , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts A : Dict = 2 A : Any = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt A : int = 2 A : List[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts A : Optional[int] = 2 A : int = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Optional[int] = '''cpu''' # ensure determinism for the device-dependent torch.Generator A : List[str] = self.get_dummy_components() A : str = AudioLDMPipeline(**SCREAMING_SNAKE_CASE ) A : List[str] = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) A : Any = audioldm_pipe.vocoder.config.sampling_rate A : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) A : Optional[Any] = audioldm_pipe(audio_length_in_s=0.016 , **SCREAMING_SNAKE_CASE ) A : Tuple = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE ) / vocoder_sampling_rate == 0.016 A : List[Any] = audioldm_pipe(audio_length_in_s=0.032 , **SCREAMING_SNAKE_CASE ) A : int = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE ) / vocoder_sampling_rate == 0.032 def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Tuple = self.get_dummy_components() A : List[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE ) A : Optional[int] = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) A : Optional[Any] = ['''hey'''] A : str = audioldm_pipe(SCREAMING_SNAKE_CASE , num_inference_steps=1 ) A : List[Any] = output.audios.shape assert audio_shape == (1, 256) A : Dict = audioldm_pipe.vocoder.config config.model_in_dim *= 2 A : Union[str, Any] = SpeechTaHifiGan(SCREAMING_SNAKE_CASE ).to(SCREAMING_SNAKE_CASE ) A : str = audioldm_pipe(SCREAMING_SNAKE_CASE , num_inference_steps=1 ) A : int = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" 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 __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE ) @slow class A ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE="cpu" , SCREAMING_SNAKE_CASE=torch.floataa , SCREAMING_SNAKE_CASE=0 ) -> Tuple: """simple docstring""" A : Union[str, Any] = torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(SCREAMING_SNAKE_CASE ) A : Optional[Any] = np.random.RandomState(SCREAMING_SNAKE_CASE ).standard_normal((1, 8, 128, 16) ) A : Optional[Any] = torch.from_numpy(SCREAMING_SNAKE_CASE ).to(device=SCREAMING_SNAKE_CASE , dtype=SCREAMING_SNAKE_CASE ) A : Dict = { '''prompt''': '''A hammer hitting a wooden surface''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 2.5, } return inputs def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Optional[int] = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''' ) A : int = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) A : Union[str, Any] = self.get_inputs(SCREAMING_SNAKE_CASE ) A : Any = 25 A : int = audioldm_pipe(**SCREAMING_SNAKE_CASE ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE ) == 81920 A : int = audio[77230:77240] A : str = np.array( [-0.4_884, -0.4_607, 0.0_023, 0.5_007, 0.5_896, 0.5_151, 0.3_813, -0.0_208, -0.3_687, -0.4_315] ) A : List[str] = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : str = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''' ) A : List[str] = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) A : List[str] = audioldm_pipe.to(SCREAMING_SNAKE_CASE ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) A : List[str] = self.get_inputs(SCREAMING_SNAKE_CASE ) A : Dict = audioldm_pipe(**SCREAMING_SNAKE_CASE ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE ) == 81920 A : Optional[int] = audio[27780:27790] A : Tuple = np.array([-0.2_131, -0.0_873, -0.0_124, -0.0_189, 0.0_569, 0.1_373, 0.1_883, 0.2_886, 0.3_297, 0.2_212] ) A : Union[str, Any] = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
311
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase : List[str] = { 'configuration_cpmant': ['CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CpmAntConfig'], 'tokenization_cpmant': ['CpmAntTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[Any] = [ 'CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST', 'CpmAntForCausalLM', 'CpmAntModel', 'CpmAntPreTrainedModel', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys lowercase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
311
1
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer lowercase : Optional[Any] = ['gpt2'] lowercase : Optional[int] = 'gpt2' if is_tf_available(): class A ( tf.Module ): def __init__( self , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" super().__init__() A : List[Any] = tokenizer A : Optional[int] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE ) A : int = TFGPTaLMHeadModel.from_config(SCREAMING_SNAKE_CASE ) @tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name='''text''' ),) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" A : Tuple = self.tokenizer(SCREAMING_SNAKE_CASE ) A : Optional[int] = tokenized['''input_ids'''].to_tensor() A : Tuple = tf.cast(input_ids_dense > 0 , tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) A : Dict = self.model(input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE )['''logits'''] return outputs @require_tf @require_keras_nlp class A ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" super().setUp() A : Dict = [GPTaTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) for checkpoint in (TOKENIZER_CHECKPOINTS)] A : List[str] = [TFGPTaTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) A : str = [ '''This is a straightforward English test sentence.''', '''This one has some weird characters\rto\nsee\r\nif those\u00E9break things.''', '''Now we\'re going to add some Chinese: 一 二 三 一二三''', '''And some much more rare Chinese: 齉 堃 齉堃''', '''Je vais aussi écrire en français pour tester les accents''', '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''', ] A : Optional[int] = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in self.test_sentences: A : Tuple = tokenizer([test_inputs] , return_tensors='''tf''' ) A : List[str] = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors A : Any = python_outputs[key].numpy() A : List[str] = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(SCREAMING_SNAKE_CASE , tf.intaa ) == tf_outputs_values ) ) @slow def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" for tf_tokenizer in self.tf_tokenizers: A : int = tf.function(SCREAMING_SNAKE_CASE ) for test_inputs in self.test_sentences: A : List[Any] = tf.constant(SCREAMING_SNAKE_CASE ) A : Optional[int] = compiled_tokenizer(SCREAMING_SNAKE_CASE ) A : str = tf_tokenizer(SCREAMING_SNAKE_CASE ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def __lowerCAmelCase ( self ) -> Any: """simple docstring""" for tf_tokenizer in self.tf_tokenizers: A : Optional[int] = ModelToSave(tokenizer=SCREAMING_SNAKE_CASE ) A : int = tf.convert_to_tensor([self.test_sentences[0]] ) A : Union[str, Any] = model.serving(SCREAMING_SNAKE_CASE ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: A : List[Any] = Path(SCREAMING_SNAKE_CASE ) / '''saved.model''' tf.saved_model.save(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , signatures={'''serving_default''': model.serving} ) A : Union[str, Any] = tf.saved_model.load(SCREAMING_SNAKE_CASE ) A : Optional[Any] = loaded_model.signatures['''serving_default'''](SCREAMING_SNAKE_CASE )['''output_0'''] # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertTrue(tf.reduce_all(out == loaded_output ) ) @slow def __lowerCAmelCase ( self ) -> str: """simple docstring""" for tf_tokenizer in self.tf_tokenizers: A : str = tf.convert_to_tensor([self.test_sentences[0]] ) A : Dict = tf_tokenizer(SCREAMING_SNAKE_CASE ) # Build model with some sample inputs A : List[Any] = tf_tokenizer.get_config() A : List[str] = TFGPTaTokenizer.from_config(SCREAMING_SNAKE_CASE ) A : List[str] = model_from_config(SCREAMING_SNAKE_CASE ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" for tf_tokenizer in self.tf_tokenizers: # for the test to run A : Tuple = 123123 for max_length in [3, 5, 1024]: A : List[Any] = tf.convert_to_tensor([self.test_sentences[0]] ) A : int = tf_tokenizer(SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE ) A : str = out['''input_ids'''].numpy().shape[1] assert out_length == max_length
311
'''simple docstring''' from __future__ import annotations lowercase : Union[str, Any] = list[tuple[int, int]] lowercase : Optional[Any] = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] lowercase : Any = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" A : int = pos_x A : Optional[Any] = pos_y A : Optional[Any] = (pos_y, pos_x) A : str = goal_x A : Optional[int] = goal_y A : List[Any] = g_cost A : str = parent A : str = self.calculate_heuristic() def __lowerCAmelCase ( self ) -> float: """simple docstring""" A : Optional[int] = abs(self.pos_x - self.goal_x ) A : Optional[Any] = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self , SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" return self.f_cost < other.f_cost class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , SCREAMING_SNAKE_CASE ) A : Tuple = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , SCREAMING_SNAKE_CASE ) A : Optional[Any] = [self.start] A : list[Node] = [] A : Tuple = False def __lowerCAmelCase ( self ) -> Path | None: """simple docstring""" while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() A : Optional[int] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: A : Optional[int] = True return self.retrace_path(SCREAMING_SNAKE_CASE ) self.closed_nodes.append(SCREAMING_SNAKE_CASE ) A : Any = self.get_successors(SCREAMING_SNAKE_CASE ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(SCREAMING_SNAKE_CASE ) else: # retrieve the best current path A : str = self.open_nodes.pop(self.open_nodes.index(SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(SCREAMING_SNAKE_CASE ) else: self.open_nodes.append(SCREAMING_SNAKE_CASE ) if not self.reached: return [self.start.pos] return None def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> list[Node]: """simple docstring""" A : List[Any] = [] for action in delta: A : List[str] = parent.pos_x + action[1] A : Dict = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , SCREAMING_SNAKE_CASE , ) ) return successors def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Path: """simple docstring""" A : int = node A : Union[str, Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) A : int = current_node.parent path.reverse() return path if __name__ == "__main__": lowercase : Tuple = (0, 0) lowercase : List[str] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print('------') lowercase : int = GreedyBestFirst(init, goal) lowercase : Union[str, Any] = greedy_bf.search() if path: for pos_x, pos_y in path: lowercase : Dict = 2 for elem in grid: print(elem)
311
1